php - How to Alert the returned data of ajax?
741
I have a jQuery page with AJAX, and is submitted in a separate PHP file that has no UI. so what i want is if say for example an insert query in my PHP file will fail, anecho(your insert failed)
in my PHP will be alerted in my jQuery page. how to do that?
something like thisalert(data);
Answer
Solution:
EDIT 2:
Alerting anything that PHP echos:
EDIT 1:
If you want the errors to appear in an alert, do this:
for debugging ajax, you can check the xhr, status, and error like so:
But this might not always display the full message, especially if the error message contains lots of data. it might end up going off the screen.
ORIGINAL ANSWER:
for debugging ajax, you can check the xhr, status, and error like so:
In your HTML you should have the 2 divs
Answer
Solution:
You can use
success
handler in$.ajax
call as diEcho wrote. Inside of this handler, you can decide by some flag whether your PHP operation succeeded or failed.error
handler of$.ajax
is more likely for ajax call fail, than for status of requested operation.Edit:
applying to example by diEcho:
EDIT2:
in PHP you could use following
Answer
Solution:
try like this
Reference
Answer
Solution:
Regarding the code of @diEcho, You also need to test in
success: function()
your returned answer with a status code (wrote by PHP).In other hand, you can force the error in your PHP script by sending an "Error 500" header, that generate the "Fail" callback. But it's not a good way !
In your PHP:
More information here: http://www.rachaelarnold.com/dev/archive/trigger-ajax-error-event
Answer
Solution:
To alert what is echoed in your PHP, "data" is passed into the success function as the first parameter, which is then output in an alert in this example:
Answer
Solution:
I know this is an old topic, but as i found it searching for something similar, i decided to add some information that could be useful for later searches.
I think a solution to this could be aproached by sending the appropriate header() or http_response_code($HTTP_ERROR_CODE); in your PHP Script, depending on the answers of your PHP Script. You can find related info in this posts:
How to make a ajax call to a php page a success or error?
How to send a server error response using php?
The function you select (header or http_response_code) it depends on the version of PHP you are using, it seems that http_response_code is available from PHP 5.4.
A workaround to avoid "PHP version crosscompiling" might be achieved by coding your own http_response_code in the case that testing for it existance results in failure, as is suggested in this other post of php.net:
http://php.net/manual/en/function.http-response-code.php
Latter, on your HTML/jQuery document, you can check your request.fail, request.done and request.always to retrieve the information provided by your PHP Script to use it at your convenience.
Hope this helps.