Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When using $.ajax in jQuery, how can I deliberately throw an error in the loaded document?

In my document I have this script:

$.ajax({ type:"POST",url:"ajax.php",data:data,
    success: function() { 
        //onsuccess
    },
    error: function() { 
        //onerror
    }
}); 

How can I, in the document ajax.php, deliberately throw an error? Is it sufficient to just throw an 400 HTTP Status Code or something? (And if so, is 400 the right one?)

Why I'm asking is that I want to use this to submit a form to the server, and if a field isn't filled out properly I want to alert the user through the error parameter in $.ajax. I know I could do this using javascript in the first place, but I'm hoping I could do it this way (so I don't have to write the verification two times). But of course by doing it this way, I can't separate the different fields from the other.

Based on what I want to use it for, can I somehow throw a "custom error", so if the field name hasn't been filled out properly, it returns the name of the field (i.e. name). Is it sufficient to do something like this:

In ajax.php:

if (isFilledOutProperly($name) == false) {
    echo "name";
}
else {
    echo "success";
}

And:

success: function(data) { 
    if (data == 'name') {
        //error
    }
            else {
        //success
    }
},

I may be on the wrong track here, but if someone have a better suggestion on how I can do this, please tell me. Thanks!

like image 488
ehm Avatar asked Feb 06 '10 11:02

ehm


1 Answers

The error clause of $.ajax() calls isn't really for the circumstance you're referring to. error covers cases of, say, HTTP errors. Validation failures aren't really errors in this case. You're better off indicating those in the success callback with appropriate data returned from the server.

If you look at the documentation:

error(XMLHttpRequest, textStatus, errorThrown)Function

A function to be called if the request fails. The function is passed three arguments: The XMLHttpRequest object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror". This is an Ajax Event.

Note: the error conditions it talks about are parse errors, timeouts, errors (HTTP) and not modified (which is another HTTP response).

Technically your request succeeds but the validation fails, which isn't an error per se.

like image 113
cletus Avatar answered Oct 13 '22 00:10

cletus