jQuery ajax() / post() & success

10,239

Solution 1

You either need to have your PHP respond with a non-200 "OK" HTTP status, or inspect the message your PHP is responding with, and change your logic accordingly.

You'll find that if you accept an argument in the success function, e.g. `success: function(o)', there are properties of the response from the AJAX call that will assist with doing this.

In general, you'd do well to review some additional examples using AJAX, both with and without jQuery. http://api.jquery.com/jQuery.ajax/ , in particular, will be of some use.

Solution 2

the success callback on $.ajax() triggers when your server sends a HTTP 200 response code. 200 means that:

  • your server received a request, optionaly with data
  • it accepted it
  • it processed it
  • it knew what to do with it
  • it returned a valid response to your client (optional, it can send an empty body)

So there are 2 ways you can do this:

  1. make your server return a non-200 HTTP code on error. For example a 400 (Bad request, which one could argue it is, if the parameters do not validate). That would trigger the error callback of $.ajax() and not your success callback (what you asked)
  2. put the error handling in application logic instead of http layer. That means, you introduce your own convention to report an application level error in the server response.

For 2, here are possible json responses (up to you to come up with whatever convention you like)

// in case of success:
{status: 'ok', error: {errno: 0, msg: ""}}

// in case of error:
{status: 'fail, 'error: {errno: 1, msg: "invalid parameters"}}

Then handle the response accordingly in your ajax call

jQuery('#contact').validator().submit(function(e)
{
    e.preventDefault();
    $.ajax(
    {
        type: "POST",
        dataType: 'json',
        url: this.action,
        mail: $('input[name="mail"]').val(), 
        message: $('textarea[name="message"]').val(),
        success: function(data)
        {
             if (data && data.error && data.errorno)
             {
                   // there is an application-level error. Hande it.
                   // ...
                   return;
             }
             alert('yo!);
        }
    }); 
});

One more thing: if you intend to do a preventDefault() in all cases. You should put that call as the first entry in your event handler. That will ensure the default event will indeed be prevented, in case any error occurs in the rest of your function (causing it to abort).

Share:
10,239

Related videos on Youtube

Wordpressor
Author by

Wordpressor

Updated on July 12, 2022

Comments

  • Wordpressor
    Wordpressor almost 2 years

    I have very simple e-mail send form, just one e-mail field and a textarea.

    jQuery('#contact').validator().submit(function(e){
        $.ajax({
          type: "POST",
          url: this.action,
          data: { 
            mail: $('input[name="mail"]').val(), 
            message: $('textarea[name="message"]').val(), },
          success: function(){
                    alert('yo');
                   }
         }); 
         e.preventDefault();
    });
    

    My action file (send.php) just does basic email and textarea checks and then sends them using mail() (if they validated).

    The problem I'm facing is that the alert message "yo" shows even when I'm sending the wrong data / all fields are empty.

    Any ideas how to fix that? Is there any way I can "tell" ajax when input fails and when succeeds from my send.php file?

    I'm using jQuery Tools Validator to validate the fields, I know there's onSuccess action, but can't use that one in my case.

  • Wordpressor
    Wordpressor about 11 years
    That's exactly what I'm looking for, I've found in jQuery documentation that success gets passed three arguments, but I have no idea how to respond with non-200 "OK" HTTP status via my php file?
  • ziesemer
    ziesemer about 11 years
    @Wordpressor - you can do it one way or the other (I mentioned both) - but if you choose to have PHP return a non-success status (which can be misleading sometimes), see php.net/manual/en/function.http-response-code.php .
  • Wordpressor
    Wordpressor about 11 years
    Thanks, works like a charm, I've been browsing jQuery api docs for a while now, but this is not explained well enough (and I'm just a newbie when it comes to JS), had no idea where to go with a string describing the status. Thanks a lot for making it clear.