JavaScript / jQuery and PHP Ajax throw an error

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

I handle success and error states in an ajax request, and I want to cause an error. The error only seems to be caused by the xhttp error, and I want to call it when the condition is not met on the server. The return of success and the need to flag the error answer seem confusing.

+3
source share
2 answers

You can approach this from two sides:

  • Force an error by calling an HTTP header, such as 404 or 503.
  • Force an error based on the specific state of the received data.

, HTTP, , 404 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': 'someone@example.com',
    'password': 'rhd34h3h'
  },
  'success': function(data) {
    alert(data);
  },
  'error': function(jqXHR, textStatus, errorThrown) {
    alert('ERROR: ' + textStatus);
  }
});

, :

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': 'someone@example.com',
    '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);
  }
});
+6

header, :

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

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


All Articles