Avoid JQuery.post() or JQuery.get() If Possible. Use JQuery.ajax() instead

Over the past few several months, work has been crazy developing a JS intensive application for one of our clients. It been going great and I’ve finally found a need to use Node.js and Websockets after reading so many good things about them.

During development as Team Lead on the project, I’ve taken the opportunity from time to time to review the code being written for various parts of the application, especially when things break. I noticed that most often when some feature broke, it was usually because of some AJAX call that failed to load something. Upon inspection, I would find that $.post() or $.get() is being used to make the AJAX calls. I would usually fix the code by using $.ajax() instead, and the “error” callback to determine what is failing in the response from the server.

I noticed most often that $.post() or $.get() was used because it was more convenient to code, however, I believe its usage is too trusting of the response of the server, which for many reasons could fail to return the right response. $.ajax() may be more verbose to type, but I feel is a better option because you can explicitly handle the error condition if the response should not be as expected.

If you would want to use $.post() and $.get() for syntactical brevity, then I would recommend you setup your global JQuery AJAX options before hand, to handle the error conditions, but I believe that is not the best option in all cases, because sometimes you need to have fine grained control of error handling.

So to conclude, I recommend, staying away from $.post() or $.get() when doing heavy duty AJAX communication in which error handling should be priority, and using $.ajax() instead.

I would be glad to hear other experiences and whether or not this view is supported by the larger web application development community.

—————————————————————————————————————————

While you here, take a break from your hard coding life to enjoy some Twi Pop music.

Advertisements

11 thoughts on “Avoid JQuery.post() or JQuery.get() If Possible. Use JQuery.ajax() instead

  1. It depends on the version of jquery your using if your using jquery >= 1.5 then using $.get and $.post are equally as powerful using the deferreds.

    http://api.jquery.com/jQuery.get/

    From the docs:


    // Assign handlers immediately after making the request,
    // and remember the jqxhr object for this request
    var jqxhr = $.get("example.php", function() {
    alert("success");
    })
    .success(function() { alert("second success"); })
    .error(function() { alert("error"); })
    .complete(function() { alert("complete"); });

    // perform other work here ...

    // Set another completion function for the request above
    jqxhr.complete(function(){ alert("second complete"); });

    1. That’s a pretty good point. But why not just use $.ajax() which takes these parameters straight away, if you are going to try to handle the errors again using deferreds?

      I guess it will all boil down to a matter of style in that case.

    1. I believe keeping it simple is what won many to the library in the first place. So they can be kept as is, but people just need to be mindful when using them

  2. Use the global ajax setup settings, and use .get() or .post(), handling the error conditions in one place will make your code easier to maintain.

    1. That may be true for smaller projects and sites, but for larger applications, the AJAX calls may be varied and in different corners, so a of size fits all error handling approach may not be the most conducive.

  3. what about this:
    $.getJSON(url, function (data) {
    var result = ”;
    // Is there any error or user is unauthorized?
    if (data.Code == ‘-1’) {
    handleError(data.Error);
    return;
    };
    if (data) {},callback(result);
    }

    Is this more safe than $.get?

    1. The point of this article is not about safety but productivity and less error prone code. $.getJSON is pretty much a wrapper for the $.ajax() with the ‘json’ dataType. I recommend you use it but be sure you account for potential and several unseen error conditions if the code it is being used for is mission critical.

  4. Speaking of which! Francis, I just ran into a very stupid problem that you might be able to solve with your insight (I’m pretty new at jQuery and Ajax). I wrote this chat code that’s only in its early stages. The code calls a PHP file and expects nothing in return. It worked for weeks and suddenly, it stopped calling the PHP. The code is as simple as this:

    $.post(“chatPost.php”, {v_text: v_clientmsg});

    I have already checked file permissions for chatPost.php, but to no avail. It gives no indication of being opened by jQuery, and the following test code:

    $.ajax({
    type: ‘POST’,
    cache:false,
    url: ‘chatPost.php’,
    data: ‘v_text=sdaddada’,
    success: function() { alert(‘success’); },
    error: function() { alert(‘fail’);
    }
    });

    says everything is ok. I’ll very grateful if you have any idea about might be going on here. Thanks in advance!

    1. Could it be that the call is being cached? What do you see in your browser console? If it is being cached, try:

      $.ajaxSetup ({
      // Disable caching of AJAX responses
      cache: false
      });

Comments are closed.