PHP custom errors for AJAX calls

I am building a web application and I am wondering how to handle errors using AJAX calls. For example, if the user enters some data that is invalid (bad email address, the user already exists), I want you to be able to throw an error from PHP.

I saw here http://php4every1.com/tutorials/jquery-ajax-tutorial/ that you can just use the JSON object and handle the error report from the JQuery Success function, but that doesn't seem like the right way to do this. It would be reasonable for me that the jQuery error function be used when an error occurs. I guess I'm a supporter of this kind of thing.

This is how I do it right now.

//In my PHP file called from JQuery function error($msg) { header("HTTP/1.0 555 ".$msg); die(); } //Then that error is handled accordingly from JQuery 

So, I am creating error code 555, which is not defined as anything, and tied to my own error message. Is this the right way to do this? Should I just use JSON? There should be a standard way to send error messages like this, right?

If you need to know more about my code to get a better idea, the whole project runs on github: https://github.com/josephwegner/fileDrop . This file is located in config / phpFuncts.php .

+6
source share
3 answers

I would just use a JSON object and an HTTP header of 200. There was nothing wrong with the request itself, and your server behaved as expected - the error was at a different level of abstraction.

+6
source

Family 400 HTTP status codes indicate that a problem has occurred with the request. I would set the response code to 400 and include the list of error messages in the response body as JSON.

+2
source

I hate using HTTP status codes to indicate failures. HTTP codes must be reserved for actual HTTP-level errors, and errors associated with the AJAX request must be sent back through the JSON structure.

eg.

 $data = array() if (some big ugly computation fails) { $data['errorcode'] = -123; $data['error'] = true; $data['success'] = false; $data['errormessage'] = 'some helpful error message'; } else { $data['success'] = true; $data['error'] = false; $data['response'] = 'whatever you wanted to send back....'; } echo json_encode($data); 

Then on the client side

 if (data.error) { alert('Request blew up: ' + data.errormessage); } 
+2
source

Source: https://habr.com/ru/post/885740/


All Articles