I am using jQuery $.ajax() function to perform a database insert operation on a php page. So, on success it will do the regular operation but I want the ajax call to receive error if the update operation fails.
So it should be:
- $.ajax -> call php function
- Receive success on successful record insert
- Receive error on unsuccessfull insert
So, should I do a return false; from my php function? I think the $.ajax() success or error depends if the AJAX call was successful or not. So, I think even if I return false; from my php function it will still be considered a "success" for the ajax call. Right
Ajax is happening on the client.
Your PHP is over on the server.
Here's an excellent example that might help:
jQuery AJAX error handling
This is simple, in short: you can catch any thing returned from PHP.
IN DETAIL: the below code snippet may help you clearly understand the issue.
PHP
JQUERY
You need to handle PHP's success/error inside your $.ajax() success: function
Assume this is your ajax.php:
Assume this is your javascript $.ajax():
You could return the error message in your server response (or using JSON) as someone suggested. But I don't like it too much because this pollutes the data returned.
I like another way I've been using recently, which involves creating a custom HTTP header to inform if there was an error.
PHP code:
jQuery code:
As you can see, we created a custom HTTP header, called
DB_SUCCESS
to be used as metadata, so we can assign it server-side (php) and read it with client-side (javascript) to know if there was an error.Hope this helps. Cheers
I would build up an array in PHP. Such as
Depends on how you go with insert change those two values.
Then I would do http://php.net/manual/en/function.json-encode.php
json_encode
and echo it out. Your jQuery would receiveJSON
and if thecompleted
is true then its all fine. If false, check themessage
.You could also use
getJSON
method from jQuery to make it even easier.http://api.jquery.com/jQuery.getJSON/
I evaluate response from the server and if error occurred in the PHP, it simply outputs JavaScript code to show error.
Works well with all sorts of things including re-login on session-timeouts, access restrictions, exception handling and everything else.
I wish this approach would be more popular.
https://github.com/atk4/atk4/blob/master/templates/js/atk4_univ.js#L413