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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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"
});
Method 2
This is another way to do it not using ajax. It uses post and returns a json object.
data = {};
data.standardBagProductId = standardBagProductId.trim();
$.post("StandardBag.aspx/RemoveProductFromStandardBag", data , function(response){
$(".reload").click();
},"json");
Method 3
for $.post function second param should not be in “”.
$.post("StandardBag.aspx/RemoveProductFromStandardBag",
{'standardBagProductId': standardBagProductId.trim() },
function () { $(".reload").click(); },
"json"
);
Method 4
Try changing your post data like this,
{standardBagProductId: standardBagProductId.trim() }
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0