Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the best practices when using jQuery Ajax calls?

I'm reviewing some code for a colleague and while there's nothing inherently wrong with the jQuery Ajax calls I'm looking at, I would like to be more certain about what should and should not appear in a normal Ajax call to an ASP.Net MVC controller action.

For example, in the following code:

    $(function() {
        $.ajax({
            url: "/Controller/action",
            type: "POST",
            data: ({ myObjectOrParameters }),
            success: function(data) { alert(data); }
        });
    });

Is this pattern just fine as-is, or are there other things that should also be there? Is contentType advisable? What about dataFilter? Is that unnecessary since we aren't using Microsoft Ajax and aren't concerned about the ".d" that it returns, should I even worry?

What about the type? Is it best practice to use "GET" or even "PUT" when reading or updating information, or is "POST" the most appropriate to use in every case?

Is it more appropriate to use $.ajaxSetup in every case, or can we get away with explicitly defining our arguments each time?

like image 224
Phil.Wheeler Avatar asked Feb 03 '10 02:02

Phil.Wheeler


1 Answers

Call me a man of brevity...

I would prefer seeing the $.post() method used in this case. Unless you're using the more esoteric options in $.ajax(), I don't see any reason to use it when there are shorter and more succinct methods available:

$.post("/Controller/action", { myObjectOrParameters }, function(data) {
  alert(data);
});
like image 72
Sampson Avatar answered Oct 26 '22 06:10

Sampson