Returning a json array using AJAX
-
21-12-2019 - |
Question
Here's the javascript:
var data = $('form#registration-form').serialize();
$.post(
'<?php echo $this->url('/register', 'do_register')?>',
function(data) {
alert(data);
},
'json'
);
And here's the ending of the do_register() method:
if( $_REQUEST['format']=='JSON' ){
$jsonHelper=Loader::helper('json');
echo $jsonHelper->encode($registerData);
die;
}
The $registerData
variable holds all the data I need. I want the function to return it after the ajax call. However, when I specify dataType: 'json' nothing is returned. Any suggestions?
Solution
I think your problem is in url
$.post(
'<?php echo $this->url("/register", "do_register"); ?>?format=JSON',
function(data) {
alert(data);
},
'json'
);
Also you can use following line in php part to get json values
header('Content-Type: application/json');
OTHER TIPS
I suppose problem is somewhere here:
'<?php echo $this->url('/register', 'do_register')?>',
in using quotes.
Use double and single quotes:
"<?php echo $this->url('/register', 'do_register')?>",
.
It's impossible to receive right suggestion with little description.
Y'd better to paste more php & javascript code, with much more context, thing to be simple.
And another suggestion, mixed coding is bad. separating the javascript and php with php template such as Smarty.
var data = $('form#registration-form').serialize();
$.post(
'<?php echo $this->url('/register', 'do_register')?>',
function(data) {
alert(data);
},
'json'
);
this source file of above code is a php file ?
Debug with firebug to capture weather the ajax request sent or not
Why use JSON helper??
json_decode(string $json);
json_encode(mixed $value); //normally array...
it is built-in in php.