-1

I use jQuery's ajax function to call a url asynchron like this:

jQuery.ajax({
    url: url,
    type: "GET",
    data: {key : value},
    success: function(data) {
        console.log(data);
    }
}

On the server side I don't know what to return to get something meaningful inside the variable data. The console's log is just empty string.

I already tried return 0, return 1, return array('status' => 1), return true

Background: I want to know if any exceptions have been thrown on the server side to pass something like false or true if it was successful without exceptions.

EDIT: Server side language is PHP

tester
  • 3,977
  • 5
  • 39
  • 59
  • 2
    What server-side language are you using? does `return` in that language output html to the page? – Kevin B Apr 08 '13 at 19:49
  • 1
    What is your server side language? PhP, Ruby, C#,..? Also, what does the server side method look like? – Nope Apr 08 '13 at 19:49
  • PHP, no its not html which will be returned – tester Apr 08 '13 at 19:50
  • @tester html, text, json, it's all the same, just text. – Kevin B Apr 08 '13 at 19:53
  • @tester: `I don't know what to return to get something meaningful inside the variable data`. We commonly return a JSON object which contains the HTML or what ever data in one property, for example: `data.returnValue`, another property which contains an array of violation objects, i.e: `data.violations` and another containing a status like `Success/Error`, i.e: `data.status` (That one could be a boolean too I suppose). They are custom object we understand in the receiving end but you can design your own off course. – Nope Apr 08 '13 at 19:54

1 Answers1

0

Assuming you are using PHP, you would just echo a string return value.

echo "true";
exit;

or

echo "false";
exit;

then you can parse that with jQuery:

if ( $.trim(data) == "true" ) {
    console.log("success!")
}
else {
    console.log(data);
}

You could also echo 0 or 1, but keep in mind it's still a string, not a number when it gets to jQuery. For more complex data, such as an array, you can json_encode it.

echo json_encode( $myarray );
exit;

and set your dataType to "json" in jQuery's $.ajax method.

Kevin B
  • 94,570
  • 16
  • 163
  • 180