Difference between $.post and $.ajax? Difference between $.post and $.ajax? ajax ajax

Difference between $.post and $.ajax?


This jquery forum thread sums it up:

$.post is a shorthand way of using $.ajax for POST requests, so there isn't a great deal of difference between using the two - they are both made possible using the same underlying code. $.get works on a similar principle.

—addyosmani

In short, this:

$.post( "/ajax", {"data" : json }) 

Is equivalent to the following:

$.ajax({   type: "POST",   url: "/ajax",   data: {"data": json} });


The problem here is not the fact $.ajax() is not working, it is because you did not set the type parameter in the Ajax request and it defaults to a GET request. The data is sent via the query string for get and if your backend expects them as post parameters, it will not read them.

$.post is just a call with $.ajax(), just with the type set. Read the docs and you will see that $.ajax() defaults to a GET as I mentioned above.

If you go to the jQuery.post page in the jQuery docs it shows you the $.ajax request with the type set. Again read the docs.


After re-reading some online documentation, I decided to stick with $.post over $.ajax.

The $.ajax method's data param does something different than the $.post method does, not sure what exactly, but there is a difference.

The only reason I wanted to use $.ajax is because I wanted to be able to handle events and didn't realize I could do so with $.post.

Here is what I ended up with

function GetSearchItems() {    var url = '@Url.Action("GetShopSearchResults", "Shop", New With {.area = "Shop"})';    var data = $("#ShopPane").serialize();    // Clear container    $('#shopResultsContainer').html('');    // Retrieve data from action method    var jqxhr = $.post(url, data);    // Handle results    jqxhr.success(function(result) {        //alert("ajax success");        $('#shopResultsContainer').html(result.ViewMarkup);    });    jqxhr.error(function() {        //alert("ajax error");    });    jqxhr.complete(function() {        //alert("ajax complete");    });    // Show results container    $("#shopResultsContainer").slideDown('slow');}

JQuery 3.x

The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callback methods are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

var jqxhr = $.post(url, data);// Handle resultsjqxhr.done(function(result) {    //alert("ajax success");});jqxhr.fail(function() {    //alert("ajax error");});jqxhr.always(function() {    //alert("ajax complete");});

https://api.jquery.com/jquery.post/