简体   繁体   中英

ajax call with a return json never catch in success

I'm trying to get a variable from my ajax call:

$.ajax({
    type: "POST",
    url: "insert",
    data: { title:title, start:dstart, end:dend },
    contentType: "application/json",
    dataType : 'json',
    success : function(data) {
       data = JSON.parse(data);
           console.log('data = '); // is showing the data with double quotes
           console.log(data);
    }
});

and there is my PHP:

$id = $calendar->getId();
$json = array ( 'id' => $id );
var_dump(json_encode($json));
json_encode($json);

And with my var_dump I can see my json_encore , like that for example:

string '{"id":156}' (length=10)

but in my ajax() success, console.log() don't show anything in my console.

Where can I see if my success: function(data) is empty or not ? I would just catch the id in my ajax success.

UPDATE : issue fixed. in fact i'm working with symfony, and I haven't seen that on my action insert where is my PHP, the page called by symfony (indexSuccess.php) was not empty which was why its not working at all.)

If you take a look at your PHP code, you're basically doing nothing with the output of json_encode() ...

Please update the last line of your PHP code to:

echo json_encode($json);

Now you should get the data you want as response.

EDIT: @1nsan3, you asked in the comment if echo not does the same as var_dump() ... I think you get an answer here: What's the difference between echo, print, and print_r in PHP?

EDIT2:

Please remove the JSON.parse() call. The response of your AJAX request is already parsed by jQuery when using dataType : 'json' , as explained in http://api.jquery.com/jQuery.ajax

Are you sure your php returns valid json data ?

php

$id = $calendar->getId();
$json = array('id' => $id);
echo json_encode($json);         <-- your php code must echo only this valid json, 
return;                              make sure no other values are echoed 
                                     above or below this which will break json.

js

success : function(data) {
  if($.trim(data) != '') {
    console.log(data);
  } else {
    console.log('no data');
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM