Difference between $.post and $.ajax?

69,949

Solution 1

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 results
jqxhr.done(function(result) {
    //alert("ajax success");
});
jqxhr.fail(function() {
    //alert("ajax error");
});
jqxhr.always(function() {
    //alert("ajax complete");
});

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

Solution 2

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} 
});

Solution 3

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.

Solution 4

Are you specifying this as the data parameter. $.post is just a shorthand for $.ajax which is expecting the following.

$.ajax({
    type : 'POST',
    url : url,
    data : data,
    success : success,
    dataType : dataType
});

Solution 5

Just as a complementary, in the accepted answer, it is mentionned that "The $.ajax method's data param does something different than the $.post method does, not sure what exactly, but there is a difference"

please try using :

    { 
        ... 
        data: JSON.stringify(yourJsonData), 
        ... 
    }

Else the json object get's inserted in the payload as a url-encoded string.

Share:
69,949
Ed DeGagne
Author by

Ed DeGagne

Highly effective, results-driven software professional with 20+ years direct experience in creative conceptualization, software development and design, usability, project coordination, team management and strategic business development. Excels in creating win-win scenarios for clients and companies. Highly responsive and adaptive to client and company needs, both internally and externally. Exemplary relationship-building and interpersonal skills. Works seamlessly and effectively with a wide variety of professionals and personalities at all levels. Specialties: Digital Experimentation, Personalization, A/B Testing, Strong OOP methodologies, C#, VB.NET, VB 3-6, XML, HTML, JavaScript, usability, CSS, Oracle, MS SqlServer, Project Management, Team Building, Department Management (35+ resources).

Updated on July 05, 2022

Comments

  • Ed DeGagne
    Ed DeGagne almost 2 years

    Curious if anyone knows what the difference is in regards to the data parameter.

    I have a $.post method that takes a $('#myform').serialize() as my data param and works.

    If I try the same using the $.ajax() approach, it doesn't work as my data param doesn't appear correct.

    Does anyone know the difference and what I might use instead of the above .serialize?

  • blurgoon
    blurgoon over 8 years
    That's not true. You can get a returned result through: $.post ("your.php", function(data) { _reference **data** as your returned result_ })
  • Ed DeGagne
    Ed DeGagne about 8 years
    nagaking, this is absolute incorrect information and should not have any upvotes. $.ajax, $.post, and $.get can ALL return results.
  • nagaking
    nagaking over 7 years
    @EdDeGagne You cant able to get the return response outside of the post function
  • Nmaster88
    Nmaster88 over 7 years
    Async option has been deprecated from what i've seen, to get a result from the ajax call there are better ways that wont leave us with a browser that can turn out unresponsive. Like using the success callback.
  • Dennis Heiden
    Dennis Heiden over 5 years
    "The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callback methods are removed as of jQuery 3.0." - api.jquery.com/jquery.post
  • Ed DeGagne
    Ed DeGagne over 5 years
    Well aware. This post was from 4 years ago.
  • Dennis Heiden
    Dennis Heiden over 5 years
    Why did you rollback my additions to your answer?
  • Ed DeGagne
    Ed DeGagne over 5 years
    Dennis, my apologies, it was completely by mistake. I corrected it.
  • Dennis Heiden
    Dennis Heiden about 5 years
    No problem, just had to ask to check if I did something wrong or should improve my edit. Have a nice week.