0

I am trying to figure out that how can I handle different responses sent from PHP to AJAX differently (I am using toastr for nice message display on front end). Say someone tried to insert some value into the database and the value got inserted successfully, then i sent I message from PHP by

echo "Data inserted";

and this gets caught by ajax response and gets handled by

success: function(response) {
 toastr.success(response);
}

But I want that, when PHP sends a message something like

echo "Unable to insert data";

My AJAX handles it as an error and I want to use toastr.danger() instead of toastr.success().

How can I handle this situation ?

  • 2
    Use HTTP status codes? Then use the relevant toastr method in the appropriate success or error handler function. – Jonnix Feb 01 '19 at 09:08
  • Just send back JSON: `{ "success": true, "message": "Data inserted" }`. In the browser, use `fetch(...).then(r => r.json()).then(reply => { ... })` and check `reply.success`. –  Feb 01 '19 at 09:12
  • Btw, a trivial way is to use a special character to separate stuff: `success#Data inserted`, then `var results = response.split("#");` –  Feb 01 '19 at 09:14

3 Answers3

2

In PHP, you can use the http_response_code() function to send the 400 HTTP status code:

http_response_code(400);
echo "Unable to insert data";

In jQuery, use the error callback to handle the 400 response:

error: function(response) {
  toastr.danger(response);
}
Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
  • Is this a common practice though? This will obviously work fine, but to me it feels wrong, given that client-server communication errors are used to indicate that data is bad in a very different way. What if there's an actual 400 / 500 error? Wouldn't that be confusing? –  Feb 01 '19 at 09:17
  • Personally I think it's more confusing for an error or failure to return a 200. – Jonnix Feb 01 '19 at 09:22
  • Sorry, that's nonsense. Invalid data was submitted successfully, and a reply indicating so was also submitted successfully. The fact that the data is invalid is completely separate from the fact that the communication with the server succeeded without issue. If you send a written application to a university and you get rejected, do you want to get your own letter back as "return to sender"? Or do you want to receive a letter from the uni with a meaningful response? –  Feb 01 '19 at 09:28
  • What you just described is exactly what status code 400 is for... The response body is completely up to the developer, but that's true for 200 too. – Jonnix Feb 01 '19 at 09:30
  • Ok then. But this answer should note that you're supposed to use a custom status code then, like 450. 400 is "Bad Request", which is definitely not the case here. –  Feb 01 '19 at 09:38
  • It depends on the context. It's arguable that "Unable to insert data" could be a 5xx code, if there is a DB connection issue for example, or it could mean that they tried an insert when not all data was submitted (i.e. no validation) in which case a 400 may be appropriate. Personally I think the answer is fine. We expect readers to be able to take answers and modify they to their needs and understanding. And if they have questions, they can comment. – Jonnix Feb 01 '19 at 09:51
  • @ChrisG Assuming that the error was caused by the user inputing invalid data, 400 or 422 code is appropriate (see [Right HTTP status code to wrong input](https://stackoverflow.com/q/7939137/3853934)). However, many people choose to always return 200 in REST APIs and put error codes and messages in JSON body. This might be the "right" way, but since the OP is clearly a beginner programmer, I decided to use the simples solution. – Michał Perłakowski Feb 01 '19 at 10:00
0

As Jon Stirling said in comment, check HTTP status code (200: OK, 404: Not found, 500: Server error...), statusCode in $.ajax options.

Or use error in $.ajax options (opposed to success options).

Or (but not the best really), check for a word in your response with String.indexOf('yourWord')

Kévin Bibollet
  • 3,573
  • 1
  • 15
  • 33
0

Try to send this in php

header("HTTP/1.0 403 Forbidden");
exit 'Bad user name / password';

header('HTTP/1.1 500 Internal Server Error');
exit("Something went wrong when we tried to save your comment. Please try again later. Sorry for any inconvenience");

header('HTTP/1.1 400 Bad Request');
exit("This is a message about your invalid fields. Please correct before resubmitting.");
eborrallo
  • 750
  • 1
  • 8
  • 17