views:

203

answers:

1

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!

+3  A: 

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.

cletus
According to the REST principle, responding to a POST request with HTTP 200 means that the resource is successfully created. You can respond with a HTTP 400 and also provide detailed information about the error in text/html/json/xml format.
Leventix
I know that, but as I was asking: I can deliberately throw the "error" part of `$.ajax()` by forcing an HTML error?
Eikern
Yes, if you respond with other than HTTP 2xx, the "error" part will be called.
Leventix