jquery form plugin, no error handling

19,121

Solution 1

The jQuery Form Plugin does handle errors and the documentation is correct in stating it can use the $.ajax options. However there are two modes the plugin will run in - normal and file upload. The problem you are having is because you are performing a file upload. (You don't say this but you have "#uploadingImg" and "#polygonUploadForm" and, recursive reasoning, you are having this problem.)

This is commonly stated, but you can't upload a file with AJAX. This workaround is to use an iframe. Form submit POSTs a normal HTTP request and loads the server response in the iframe. The plugin grabs the response and voila. Because this happens as a normal HTTP request, the rules and behaviors of $.ajax don't apply (because it isn't being used). The only thing Form plugin can do is treat whatever it gets as a success. In code terms, file uploading will never trigger the 'error' attribute assigned to ajaxForm() or ajaxSubmit(). If you really want to prove this isn't an AJAX request, attach an ajaxComplete() handler to the form (i.e. completely independent of the Form plugin's methods). It won't get triggered either. Or look at Firebug's Net->XHR panel.

So that's that - the upload is not an AJAX request. The best you can do is work within the 'success' or 'complete' callbacks of ajaxForm()/ajaxSubmit(). You are limited without access to the actual HTTP response code, but you can examine the response. If the response is empty or not what you expect, you can actually trigger the 'error' callback by calling xhr.abort(). Instead of doing "if(good response) {yay!} else {oh no!}", calling abort() and triggering 'error' makes the code a little cleaner and more understandable IMHO. Here's a code example:

$("#uploadForm").ajaxForm({
    success: function(response, textStatus, xhr, form) {
        console.log("in ajaxForm success");

        if (!response.length || response != 'good') {
            console.log("bad or empty response");
            return xhr.abort();
        }
        console.log("All good. Do stuff");
    },
    error: function(xhr, textStatus, errorThrown) {
        console.log("in ajaxForm error");
    },
    complete: function(xhr, textStatus) {
        console.log("in ajaxForm complete");
    }
});

A bad will response will print this in the console log:

[jquery.form] state = uninitialized
"NetworkError: 404 NOT FOUND - http://server/fileupload/"
[jquery.form] state = loading
[jquery.form] isXml=false
in ajaxForm success
bad or empty response
[jquery.form] aborting upload... aborted
in ajaxForm error
in ajaxForm complete
in ajaxForm complete

I don't know why the 'complete' callback is run twice - anyone? One final thing, read this thread if you are asking why jQuery or the Form plugin can't just read the HTTP headers of the iframe.

Solution 2

Just found out that the jquery.form plugin itself doesn't handle server error, because it doesn't have access to response headers due to the way 'file input' tag handles file upload. So I think the W3C needs to review that troublesome tag that not only doesn't let you style it with CSS but also doesn't make server response handling easy.

There must be a way around it though...

Let me know if I said something wrong and let me know your thoughts about this 'file input' tag...

Solution 3

Jquery Form Plugin handle the server response status success (code 200), i think that information is enough.

From that you can create you response status server side

            return $this->returnJson(array(
                'response' => 'success',//error or whatever
                'data' => 'Succesfully saved in the database'
            ));

of course returnJson is a function to send the Json data (you can build one or doing inside your method)

in the frontend on success handle (is fired when response is 200) you just need to check your status field (in this case 'response'), example below:

  var options = {
        dataType : 'json',
        success: handleResponse
    };


    function handleResponse (responseText, statusText, xhr, $form){

          if(responseText.response == 'success') {
                  //do something

                }else if(responseText.response == 'error'){
                    //do something

            }


    }
Share:
19,121

Related videos on Youtube

Shaoz
Author by

Shaoz

Updated on May 06, 2022

Comments

  • Shaoz
    Shaoz about 2 years

    It seems that there are no error handling facility in the Jquery.Form plugin, which is very frustrating. Even though the documentation says we can use the $.ajax options, I still cannot make use of the 'error' option when the server returns an error, especially the 500 and 400 series. Is it that this plugin cannot handle any error at all from the server or is it a bug, etc? Can someone please tell me how I can handle errors (400, 500, etc) with this plugin? I need your help... All I want is a simple error handling... Thank you.

    $("#uploadingImg").hide();
    
    var options = {//Define ajax options
        type: "post",
        target: "#responsePanel",
        beforeSend: function(){
            $("#uploadingImg").show();
        },
        complete: function(xhr, textStatus){
            $("#uploadingImg").hide();
        },
        success: function(response, statusString, xhr, $form){
            // I know what to do here since this option works fine
        },
        error: function(response, status, err){
            // This option doesn't catch any of the error below, 
            // everything is always 'OK' a.k.a 200
            if(response.status == 400){
                console.log("Sorry, this is bad request!");
            }
            if(response.status == 601){
                sessionTimedOut();
            }
        }
    }
    $("#polygonUploadForm").submit(function(){
        $(this).ajaxSubmit(options); // Using the jquery.form plugin
        return false;
    });
    
  • Robert Watkins
    Robert Watkins almost 12 years
    +1. Note that this is a problem only when the iFrame workaround is used - that is, in browsers that do not support the HTML5 features correctly. (coughiecough)
  • will824
    will824 over 10 years
    +1 I really like when people take their time to share their knowledge. Thanks a lot @JCotton, I really appreciate your clear and informative answer :)
  • Jude Niroshan
    Jude Niroshan about 9 years
    Thanks for nice solution