How To Handle Ajax Resonsetext With Conditions
Solution 1:
I would suggest adding the dataType: 'json'
property to your $.ajaxForm
call. Then in your php instead of returning 'Thanks' you can return:
return json(array('status'=>'success'));
or
return json(array('status'=>'failed'));
Then in show-response you can run something like :
if(responseText.status === 'failed') { // do something })
Solution 2:
You will have to get your PHP to send an error string such that it appears in responseText. Then in your JavaScript code, you'll have to interpret that error string. It won't be an AJAX error because, as far as AJAX is concerned, everything worked beautifully. AJAX doesn't know that your program found an error; it only knows that it sent a request and got a response back.
To put it another way: the separation of powers and responsibilities between AJAX and your program means that AJAX isn't allowed to intervene in your program's operation.
Solution 3:
If you detect an error server side, have your php code set the response status to 500 and return your error message. That will trigger ajaxForm's error callback.
I'm not a PHP guy so I'm not sure how you'd set your response to 500, but I use this method with Asp.net and it works perfectly.
Solution 4:
I used to return 200 regardless if an error occured or not, and I was returning an error code by returning different string messages but that was not a good practice according to RESTful structures. Here's a link about what I'm referring to.
So, throwing an appropriate exception at your serverside code seems to be the best practice.
throw new Exception('Division by zero.');
When that happens, your ajax client would get a response with Http Status Code (500). Jquery understands and triggers the error(jqXHR, textStatus, errorThrown) event using this Status code (which is 500=internal server error), and it would return your custom exception details.
Then, you can parse these 3 parameters and give a proper response to your client.
Post a Comment for "How To Handle Ajax Resonsetext With Conditions"