I’ve been browsing SO for a few now and can’t find an answer that works for me, anyway, here’s the JS:
jQuery.ajax({
url:'scripts/form.php?'+
'name='+$('#name').val()+
'&comment='+$('#comment').val(),
type:'POST',
dataType:'json',
complete:function(success) {
alert(success.responseText);
alert(success.name);
}
});
Here’s the (summarized) script being
header('Content-type: application/json');
$name = $_GET['name'];
$comment = $_GET['comment'];
echo json_encode(array('name'=>$name, 'comment'=>$comment));
Here’s the output from the alert boxes:
- {“name”:”test name”,”comment”:”test comment”}
- undefined
I’ve tried a bunch of different things, but I’m at a loss.
You should be using the
successevent instead of thecompleteevent — otherwise, the response does not get parsed as JSON automatically.If you want to use the
completehandler, you will need to parse the return value with$.parseJSONbefore being able to use it as an object: