Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$.post vs $.ajax

I'm trying to use the $.post method to call a web service, I've got it working using the $.ajax method:

$.ajax({
    type: "POST",
    url: "StandardBag.aspx/RemoveProductFromStandardBag",
    data: "{'standardBagProductId': '" + standardBagProductId.trim() + "' }",
    success: function(){
                 $((".reload")).click();
             },
    dataType: "json",
    contentType: "application/json"
});

But when I move the same method into the $.post method, it will not work:

$.post("StandardBag.aspx/RemoveProductFromStandardBag",
    "{'standardBagProductId': '" + standardBagProductId.trim() + "' }",
    function () { $((".reload")).click(); },
    "json"
);

What am I missing?

like image 799
Martinffx Avatar asked Sep 23 '11 12:09

Martinffx


People also ask

Should I POST or get Ajax?

GET is basically used for just getting (retrieving) some data from the server. Note: The GET method may return cached data. POST can also be used to get some data from the server. However, the POST method NEVER caches data, and is often used to send data along with the request.

What is the difference between POST and Ajax?

$. 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.

Is Ajax a post request?

data : A plain object or string that is sent to the server with the request. success : A callback function that is executed if the request succeeds.it takes as an argument the returned data. It is also passed the text status of the response.

What is difference between GET and Ajax?

get() executes an Ajax GET request. The returned data (which can be any data) will be passed to your callback handler. $(selector). load() will execute an Ajax GET request and will set the content of the selected returned data (which should be either text or HTML).


1 Answers

It doesn't work because in your $.post method you cannot set the content type of the request to application/json. So it is not possible to invoke an ASP.NET PageMethod using $.post because an ASP.NET PageMethod requires a JSON request. You will have to use $.ajax.

I would just modify the data in order to ensure that it is properly JSON encoded:

$.ajax({
    type: "POST",
    url: "StandardBag.aspx/RemoveProductFromStandardBag",
    data: JSON.stringify({ standardBagProductId: standardBagProductId.trim() }),
    success: function() {
        $(".reload").click();
    },
    dataType: "json",
    contentType: "application/json"
});
like image 184
Darin Dimitrov Avatar answered Oct 06 '22 07:10

Darin Dimitrov