raphadko raphadko - 6 months ago 11
jQuery Question

Reading json data from PHP back to ajax post

I have an ajax post function that gets data from the backend.

$.ajax({
type: "POST",
url: action,
result: "json",
data: formData,
})
.done(function( msg ) {

console.log(msg.status);

});


Php is

return json_encode(array('status' => 'ok'));


But when i try to read msg.status the result is undefined. If I log msg value,it has: {"status":"ok"}

How do I read it in json format?

Answer

There is no result property in $.ajax. If you want to tell jQuery to parse the JSON for you, you need to use dataType.

$.ajax({
     type: "POST",
     url: action,
     dataType: "json",
     data: formData,
})
.done(function(msg) {
    console.log(msg.status);
});