3

Is it possible to force an error state to return to an ajax request from a PHP script?

I am handling the success and error states in an ajax request and I want a way to force the error. The error only seems to be triggered by xhttp error and I want to trigger this when a condition is not met at the server. Its seems confusing to have to return success and have to actually put a flag in the response for an error

2 Answers 2

7

You could approach this from two angles:

  • Force an error to be thrown by outputting an HTTP header such as a 404 or 503.
  • Force an error to be thrown based on certain condition of the resulting data.

Force an error to be thrown by outputting an HTTP header such as a 404 or 503:

PHP

<?php
if(User::Login($_POST['username'], $_POST['password'])) { // Your logic here
  print 'Login successful!';
} else {
  header("HTTP/1.0 403 Forbidden");
  print 'Bad user name / password';
}

jQuery

$.ajax({
  'url': '/some/url',
  'type': 'POST',
  'data': {
    'username': '[email protected]',
    'password': 'rhd34h3h'
  },
  'success': function(data) {
    alert(data);
  },
  'error': function(jqXHR, textStatus, errorThrown) {
    alert('ERROR: ' + textStatus);
  }
});

Force an error to be thrown based on certain condition of the resulting data:

PHP

<?php
$return = array();
if(User::Login($_POST['username'], $_POST['password'])) { // Your logic here
  $return['success'] = True;
  $return['message'] = 'Login successful!';
} else {
  $return['success'] = False;
  $return['message'] = 'Bad user name / password';
}
print json_encode($return);

jQuery

$.ajax({
  'url': '/some/url',
  'type': 'POST',
  'dataType': 'json',
  'data': {
    'username': '[email protected]',
    'password': 'rhd34h3h'
  },
  'success': function(data) {
    if(data['success']) { // Successful login
      alert(data['message']);
    } else { // Login failed, call error()
      this.error(this.xhr, data['message']);
    }
  },
  'error': function(jqXHR, textStatus, errorThrown) {
    alert('ERROR: ' + textStatus);
  }
});
Sign up to request clarification or add additional context in comments.

Comments

4

You can use header to do this, for example:

header('HTTP/1.1 503 Service Unavailable');

1 Comment

Also, the code could be any of a number of standard HTTP 'error' status codes in the 400-500 range: en.wikipedia.org/wiki/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.