Search code examples
javascriptphpajaxjsonconcrete5

Returning a json array using AJAX


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');