简体   繁体   中英

jquery ajax issue. strange behavour in .done() function

Im seeing some very odd stuff in a simple ajax/jquery code I wrote and I can't explain why Im seeing what Im seeing.

I have a php file called complete.php, the only thing this does at the moment is:

echo "saved";

I have a jquery ajax call, which has a .done() function, which looks like this:

jQuery.ajax({
        type: "POST",
        url: "complete.php",
        data: "id=someIdHere",
        }).done(function(d){

         alert(d);

          if(d == "saved"){
                alert('loading done');
          }else{
                alert('error');
          }
    });

My firebug confirms the response from the complete.php is 'saved'.

when I typeof the 'd' response, it is of type 'string',

however for some reason, the alert I get in the .done() function, is 'error' and not 'loading done'.

the 'alert(d)' just before the if statement gives 'saved'.

What am I missing here?

You should use a more robust return type, such as JSON:

header('Content-Type: application/json');
echo json_encode(array(
    'status' => 'saved',
));

Then in your success handler:

if (d.status == 'saved') { ... }

try

jQuery.ajax({
    type: "POST",
    url: "complete.php",
    data: "id=someIdHere",
    success: function(){ alert('loading done'); },
    error: function(){ alert('error'); }
    });

Very odd but Iv found the issue.

my php was

echo "saved";

which is right, however when I debugged the return as per @mplungjan suggestion, the return was " saved" (with white space) this was odd as the php had no white space, I then changed the php to

echo trim("saved");

but when I again debugged the return, it again was " saved" (with the white space)

No idea why the white space is being applied, but I have resolved it by replacing the white space in the return / .done() function

I wont select this as the answer, but if anyone knows hoe the white space could have been added Id love to know.

Im using firefox 18 on mountain lion

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