Tyler Hughes
Tyler Hughes

Reputation: 602

JQuery/Ajax: Error Handling

$.ajax({  
  type: 'POST',  
  url: 'doSomething.php',  
  data: $('#form').serialize(),
  dataType: "json",  
  success: function(data) {
    //Success Message
  },  
  error: function() {
   //Error Message          
  }  
});

I have a form input going to a PHP page which I error check on that page. My question is can I send errors (data array) through error: function(data) { or is it ONLY for actual errors with Ajax not going through correctly?

If that's the case would I be able to send the error array the success function?

Not sure on how to go about this.

If I could send data from my PHP page to the error function, I wouldn't even know how on the PHP page.

Upvotes: 1

Views: 5156

Answers (1)

webnoob
webnoob

Reputation: 15934

You can raise your own errors, if you do this:

$.ajax({  
  type: 'POST',  
  url: 'doSomething.php',  
  data: $('#form').serialize(),
  dataType: "json",  
  success: function(data) {
    //Success Message
  },  
  error: function(req, status, error) {
   alert(req.responseText);      
  }  
});

when you throw an exception in your app it will be alerted out. For instance, in PHP you could do:

throw new Exception("Something bad happened");

You can see more about exceptions here

Upvotes: 4

Related Questions