sasori
sasori

Reputation: 5445

how to use jquery's $.ajax error parameter

how to use the error parameter of the jquery's $.ajax thing ? let's say i have a form, and then when I submit it, the data is being saved to the table using the PHP script used in the ,

   $.ajax({
      type: "POST",
      url: "classes/ajax.submitcv.php",
      data: "userid="+userid+"&resumetitle="+resumetitle+"&resumeintro="+resumeintro+
            "&name="+name+"&dob="+dob+"&contacttel1="+contacttel1+"&contacttel1type="+contacttel1type+
            "&contacttel2="+contacttel2+"&contacttel2type="+contacttel2type+"&contacttel3="+contacttel3+
            "&contacttel3type="+contacttel3type+"&primaryemail="+primaryemail+"&secondaryemail="+secondaryemail+
            "&skype="+skype+"&facebook="+facebook+"&linkedin="+linkedin+"&twitter="+twitter+
            "&messenger="+messenger+"&yahoo="+yahoo+"&aol="+aol+"&summaryofpositionsought="+
            summaryofpositionsought+"&summaryofskills="+summaryofskills+"&gender="+gender,
      success: function(){
        $('form#wsrecruitcvhead').fadeOut("normal",function(){
           $('div.success').fadeIn(1000);
        });
      },
      });
      return false;
   });
 });

based from the code above, if the data went through the database table, the form disappears and the success message inside a tag shows, so how am I gonna output an error message instead, let's say I have a php function and the data to be inserted returns false, how to update the html file given the message and the form won't fadeOut ? in short..how to use the error param of $.ajax ?

Upvotes: 0

Views: 2148

Answers (4)

Anthony Jack
Anthony Jack

Reputation: 5553

To elaborate on what @John Kurlak posted, the error() param is not used for "form errors". It is called when a request fails. The suggestion that he gave you to return "success" or "failure" is the way that you would go about handling form validation.

Below is an example of how you could handle the actual request error...

function ajax_error(request, type, errorThrown)
{
    var message = "There was an error with the AJAX request.\n";
    switch (type) {
        case 'timeout':
            message += "The request timed out.";
            break;
        case 'notmodified':
            message += "The request was not modified but was not retrieved from the cache.";
            break;
        case 'parseerror':
            message += "XML/Json format is bad.";
            break;
        default:
            message += "HTTP Error (" + request.status + " " + request.statusText + ").";
    }
    message += "\n";
    alert(message);
}

Then call ajax_error from the error() param of your ajax calls...

$.ajax({
    type: "POST",
    url: "classes/ajax.submitcv.php",
    data: "userid="+userid+"&resumetitle="+resumetitle+"&resumeintro="+resumeintro+
    "&name="+name+"&dob="+dob+"&contacttel1="+contacttel1+"&contacttel1type="+contacttel1type+
    "&contacttel2="+contacttel2+"&contacttel2type="+contacttel2type+"&contacttel3="+contacttel3+
    "&contacttel3type="+contacttel3type+"&primaryemail="+primaryemail+"&secondaryemail="+secondaryemail+
    "&skype="+skype+"&facebook="+facebook+"&linkedin="+linkedin+"&twitter="+twitter+
    "&messenger="+messenger+"&yahoo="+yahoo+"&aol="+aol+"&summaryofpositionsought="+
    summaryofpositionsought+"&summaryofskills="+summaryofskills+"&gender="+gender,
    success: function(){
        $('form#wsrecruitcvhead').fadeOut("normal",function(){
            $('div.success').fadeIn(1000);
        });
    },
    error: ajax_error
});

Upvotes: 0

gred
gred

Reputation: 537

In order for you to handle a type of error in your app from an ajax call you need to send this kind of error to your page. I myself in ajax cases usually return a json which contains a status and a message among other things. Let me give you an example of what I would do: I would first of all return a json like the followin: in success case:

{"status":"OK", "message":"The data saved!", "data":[some kind of data]}

in error case:

{"status":"ERROR", "message":"Could NOT save DATA!", "data":[some kind of data]}

so then in the handler:

 $.getJSON("myAjaxUrl",  function(response) {
       if(response.status=='ERROR') {
          //handle the error and maybe alert the message
          alert(response.message);
       } else {
          //do whatever. Everything went ok, maybe alert a message if any
          alert(repsonse.message);
       }
    )};

the advantage of the previous is that you can add aditional statuses.

With the previous you can handle the so called Business errosr, errors inside your app. Maybe you would also like to handle an error caused by let's say the application went down and the ajax can't reach the url. For the last case you need an error handler for th ajax call. You nedd to do something like the following:

$.getJSON("myAjaxUrl",  function(response) {
       if(response.status=='ERROR') {
          //handle the error and maybe alert the message
          alert(response.message);
       } else {
          //do whatever. Everything went ok
       }
    )}
    .error(function() { alert("Fatel Error!!"); });

You can see tha documentation for this here

Upvotes: 0

Vladislav Ross
Vladislav Ross

Reputation: 581

If you want to use the error param of $.ajax, you need to send HTTP status header with error code from the php page (before any other output!). For example:

if(some_function(...) === FALSE)
{
   header("HTTP/1.0 403 Forbidden");
   exit;
}

Upvotes: 1

John Kurlak
John Kurlak

Reputation: 6680

The error() function is used to call a function whenever the request fails. We're going to assume that your request doesn't fail (in an HTTP sense; that is, the request can return with an error without failing). What you need to do is have ajax.submitcv.php print out some sort of text indicating whether the data was successfully saved. Then, in your success() function, you can do something like:

success: function(data) {
   if (data === 'success') {
       // code for success
   }
   else if (data === 'failure') {
       // code for failure
   }
}

I would recommend sending the results back as JSON. Something like:

{ "response": "success" }

And:

success: function(data) {
   var returned = $.parseJSON(data);

   if (returned.response === 'success') {
       // code for success
   }
   else if (returned.response === 'failure') {
       // code for failure
   }
}

By the way, I'm being very general. Actual production code should check for null values and other things (and have an error handler for when requests fail).

Upvotes: 1

Related Questions