David
David

Reputation: 415

JavaScript/jQuery and PHP Ajax force an error

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

Upvotes: 3

Views: 6257

Answers (2)

Joshua Burns
Joshua Burns

Reputation: 8572

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);
  }
});

Upvotes: 7

cambraca
cambraca

Reputation: 27837

You can use header to do this, for example:

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

Upvotes: 4

Related Questions