$ .post vs $ .ajax

I'm trying to use the $ .post method to call a web service, it works for me 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 transfer the same method to the $ .post method, it will not work:

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

What am I missing?

+16
jquery ajax asp.net-ajax
Sep 23 '11 at 12:12
source share
4 answers

This does not work because in your $.post method you cannot set the content type of the application/json request. Thus, it is not possible to call ASP.NET PageMethod using $.post because ASP.NET PageMethod requires a JSON request. You will need to use $.ajax .

I would just modify data to make sure it is JSON encoded correctly:

 $.ajax({ type: "POST", url: "StandardBag.aspx/RemoveProductFromStandardBag", data: JSON.stringify({ standardBagProductId: standardBagProductId.trim() }), success: function() { $(".reload").click(); }, dataType: "json", contentType: "application/json" }); 
+23
Sep 23 '11 at 12:15
source share

This is another way to do this without using ajax. It uses a post and returns a json object.

 data = {}; data.standardBagProductId = standardBagProductId.trim(); $.post("StandardBag.aspx/RemoveProductFromStandardBag", data , function(response){ $(".reload").click(); },"json"); 
0
Jun 15 '15 at 22:34
source share

for the $ .post function, the second parameter must not be in "".

 $.post("StandardBag.aspx/RemoveProductFromStandardBag", {'standardBagProductId': standardBagProductId.trim() }, function () { $(".reload").click(); }, "json" ); 
-one
Sep 23 '11 at 12:15
source share

Try changing your details to send,

  {standardBagProductId: standardBagProductId.trim() } 
-one
Sep 23 '11 at 12:16
source share



All Articles