I came across a little problem and struggling to solve it... Was wondering if you had any ideas... I have read A LOT of stackoverflow posts about the same issues, but still can't solve mine. I am workin in CodeIgniter.
I am trying to send the variable to PHP controller form the view using jQuery ($.post). Here is mine js code, that is embedded into the view:
$('#testbtn').on('click', function() {
var orderValue = this.value;
$.post('http://localhost/codeigniter/welcome/index', {val: 'myValue'}, function(data) {
alert(data);
});
});
Here is the PHP code in the controller:
$a = isset($_POST['val']) ? $_POST['val'] : 'Not set yet.';
echo $a ;
Here is the button: <button id="testbtn" value="thevalue">button</button>
The button is clicked, I get the alert message with the variable and the html code of the whole page, but PHP echo doesn't change, still says: "Not set yet.".
Basically it seems to be very easy, but I can't still find the error...
Without diving into the code more, this would work.
HTML:
<button id="testbtn" value="thevalue">button</button>
Javascript:
$('#testbtn').on('click', function() {
var orderValue = {"orderValue": $(this).val()};
$.ajax({
url: 'http://localhost/codeigniter/welcome/index',
method: 'POST',
data: orderValue,
success: function(data) { alert(data); }
});
PHP:
public function index() {
$a = isset($_POST['orderValue']) ? $_POST['orderValue'] : 'Not set yet.';
return a;
}
As stated in other comments though, this may not be the best practice.