Returning an exception with PHP to javascript FETCH API

Viewed 1998

I am currently coding with javascript and I've hit a wall. Javascript FETCH api to POST is this:

('form') is my form #ID in html.

fetch(URL_TO_POST, {
            method: 'post',
            body: new FormData(document.querySelector('form'))
        }).then(response => {
            console.log(response);
        });

php file:

if( !isset($_POST['email'])){
   throw new exception (blabla);
 }   

URL_TO_POST is like a "validation.php" and inside the code I retrieve some POST informations and do some stuff there. The problem is that I can't throw any exception to the javascript response! Any thoughts on that? Note: I'm not using ajax to post because I'm trying to stay simple and clean with only js code. Thanks!

1 Answers

In your JavaScript you could use the reject handler to handle invalid data sent to the server:

fetch(
  URL_TO_POST, 
  {
    method: 'post',
    body: new FormData(document.querySelector('form'))
  }
)
.then(
  function(response) {
    //https://httpstatuses.com/422
    if (response.status === 422) {
      return Promise.reject(response.json());
    }
    //check for other things that could have gone wrong
    return response.json();
  }
).then(
  function(json) {
    console.log("received success json",json)
  }
  ,function(json) {
    console.log("received reject json",json)
  }
)

Not clear what you use for PHP but you can provide status code of 422 with some json:

http_response_code(422);
echo json_encode(array("error" => "missing field", "field" => "email"));
Related