How do I use AJAX to return a variable in PHP? I am currently using echo in my controller to display a price on dropdown .change
in a div
called pr
if u are returning only single value from php respone to ajax then u can set it hidden feild using val method
$("#hidden_fld").val(return_val);
Well.. One option would be to return a JSON object. To create a JSON object in PHP, you start with an array of values and you execute json_encode($arr)
. This will return a JSON string.
$arr = array(
'stack'=>'overflow',
'key'=>'value'
);
echo json_encode($arr);
{"stack":"overflow","key":"value"}
Now in your jQuery, you'll have to tell your $.ajax
call that you are expecting some JSON return values, so you specify another parameter - dataType : 'json'
. Now your returned values in the success
function will be a normal JavaScript object.
$.ajax({
type: "POST",
url: "...",
data: query,
dataType: 'json',
success: function(data){
console.log(data.stack); // overflow
console.log(data.key); // value
}
});
echo json_encode($RESPONDE);
exit();
The exit is not to display other things except answer. RESPONDE is good to be array or object. You can access it at
success: function(data)
{ data }
data is the responde array or whatever you echo.. For example...
echo json_encode(array('some_key'=>'yesss')); exit();
at jquery
success: function(data){ alert(data.some_key); }