$.post vs $.ajax - asp.net

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?

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

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

for $.post function second param should not be in "".
$.post("StandardBag.aspx/RemoveProductFromStandardBag",
{'standardBagProductId': standardBagProductId.trim() },
function () { $(".reload").click(); },
"json"
);

Try changing your post data like this,
{standardBagProductId: standardBagProductId.trim() }

Related

(JSON.stringify) ---> (asp.net function) ----> (JSON.parse) ---->Microsoft JScript runtime error: Invalid character

I have a simple javascript object. I serialize it with JSON.stringify I send it to a asp.net web function that just return it. But when I try to parse the returned string with JSON i get
Microsoft JScript runtime error: Invalid character
$(document).ready(function() {
$.ajax({
type: "POST",
url: "test.aspx/PassBackdata",
contentType: "application/json; charset=utf-8",
data: "{'args': '" + JSON.stringify(MyObject) + "'}",
dataType: "json",
success: AjaxSucceeded,
error: AjaxFailed
});
});
function AjaxSucceeded(result) {
var a=JSON.parse(result);
}
function AjaxFailed(result) {
alert(result.status + ' ' + result.statusText);
}
};
<System.Web.Services.WebMethod()> _
Public Shared Function PassBackdata(args As String)
Return args
End Function
How can I solve this problem? Thank you
If the error occurs on succes function, you may want to check the format of the result object. I had to use var a=JSON.parse(result.d); because that is how it was returned by webservice, it wasn't a direct json, but an object with a "d" field which was the json.
For checking the result I use fiddler.
Instead of:
"{'args': '" + JSON.stringify(MyObject) + "'}"
Try this:
JSON.stringify({args: MyObject})
Don't do yourself what JavaScript can do for you ;)
It would help to know what MyObject looks like, however:
JSON must have key names in double quotes, not single quotes. Try something like this instead:
$(document).ready(function() {
$.ajax({
type: "POST",
url: "test.aspx/PassBackdata",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({args:MyObject}),
dataType: "json",
success: AjaxSucceeded,
error: AjaxFailed
});
});
function AjaxSucceeded(result) {
var a=JSON.parse(result);
}
function AjaxFailed(result) {
alert(result.status + ' ' + result.statusText);
}
};
if I do: JSON.parse(result.d) instead of JSON.parse(result) it works.
function AjaxSucceeded(result) {
var a=JSON.parse(result.d);
}
don't know why

Accessing Data in Httphandler sent using post request

I have created a httphandler. Everything is working fine If you take the request type GET. But I really don't want GET request due to security reasons.
I am making a POST request using Jquery using following code:
$.ajax({
type: "POST",
async: false,
url: "SaveAccounts",
data: { a: "Sent Data" },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function OnSuccess(a) {
alert(a);
},
error: function OnError(request, status, error) {
alert('Error: ' + request + ' ' + status + ' ' + error);
},
complete: function () {
}
});
And the code for processing request is:
context.Response.ContentType = "application/json; charset=utf-8"
Dim s As String = context.Request.Params("a")
context.Response.Write(JsonConvert.SerializeObject(s))
This code is returning 'null' in javascript alert in client side.
Please note every thing is working fine when request type is changed to GET in $.ajax() function.
I have also tried to access posted data using context.Request.Form("a") and context.request.SserverVariables("a")
context.request.Params is a combined collection of 'Form', 'ServerVariables', 'Cookies' etc.
Please tell me where I am going wrong...??
Thanks for looking....
This is working by just removing contentType and dataType specification from the request.
Anything other than this will remain unchanged.
Try
data: { "a=Sent Data" },
e.g. from http://api.jquery.com/jQuery.ajax/
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
Also the HttpHandlers don't like JSON data so get rid of the contentType and the dataType.
Escaping it - a more complete example
var dataString = "{ 'first' : '" + escape($('#fname').val()) +
"', 'mail' : '" + escape($('#tbMail1').val()) +
"', 'mailinglist' : '" + $("input[name='ml']:checked").val() +
"' }";
/*alert(dataString.replace('\',','\',\n'));*/ // just for debugging ;)
$.ajax({
type: "POST",
url: "myAjaxHandler.asmx/ProcessSampleForm",
data: dataString,
cache: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$(".loadingimg").fadeOut();
window.location.replace(msg.d);
},
error:function(xhr,err){
$(".loadingimg").fadeOut();
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
}
});
Taken from http://www.jphellemons.nl/post/JQuery-with-webform-input-validation-ajax-posting-json-to-aspnet-C.aspx

2 page methods on an aspx page

I'm calling a page method with jquery and it works just fine. I'm creating a second one and it's not working at all; all I get is the error function. Is it possible to put more than 1 page method in an aspx page?
Here's my jquery on the client:
function LoadCount() {
var TheObject = $.toJSON(CurrentForm);
var TheParameter = "{'TheParameter' : '" + TheObject + "'}";
$('#testobj').html("loading");
$.ajax({
type: "POST",
url: "../Pages/MyPage.aspx/GetCount",
data: TheParameter,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFn,
error: errorFn
});
};
function successFn(thedata) { $('#result').html(thedata.d); };
function errorFn() { alert("problem getting count"); };
function LoadData() {
var ConfirmLoad = "test";
$.ajax({
type: "POST",
url: "../Pages/MyPage.aspx/GetLoaded",
data: ConfirmLoad,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successLoad,
error: errorLoad
});
};
function successLoad(thedata) { alert((thedata.d)); };
function errorLoad() { alert("problem getting loaded"); };
And on the server side, I have this:
[WebMethod]
public static string GetCount(string TheParameter)
{
// some code
return JsonResult;
}
[WebMethod]
public static string GetLoaded(string ConfirmLoad)
{
return "test string";
}
LoadCount and GetCount work great, I thought I'd copy the implementation to create another page method but the second time, nothing good happens. Thanks for your suggestions.
You need to set dataType: "text" in the $.ajax() call properties if you're just returning plain text instead of a JSON encoded string.
You might also want to leave the contentType unspecified (at the default value of 'application/x-www-form-urlencoded') if your're sending plain text instead of a JS object.

Pass Multiple Parameters to jQuery ajax call

I have the following jquery code to call a webmethod in an aspx page
$.ajax({
type: "POST",
url: "popup.aspx/GetJewellerAssets",
contentType: "application/json; charset=utf-8",
data: '{"jewellerId":' + filter + '}',
dataType: "json",
success: AjaxSucceeded,
error: AjaxFailed
});
and here is the web method signature
[WebMethod]
public static string GetJewellerAssets(int jewellerId)
{
This works fine.
But now I need to get two parameters passed to the web method
the new web method looks like this
[WebMethod]
public static string GetJewellerAssets(int jewellerId, string locale)
{
}
How do I change the client code to successfully call this new method signature ?
EDIT:
The following 2 syntaxes worked
data: '{ "jewellerId":' + filter + ', "locale":"en" }',
and
data: JSON.stringify({ jewellerId: filter, locale: locale }),
where filter and locale are local variables
Don't use string concatenation to pass parameters, just use a data hash:
$.ajax({
type: 'POST',
url: 'popup.aspx/GetJewellerAssets',
contentType: 'application/json; charset=utf-8',
data: { jewellerId: filter, locale: 'en-US' },
dataType: 'json',
success: AjaxSucceeded,
error: AjaxFailed
});
UPDATE:
As suggested by #Alex in the comments section, an ASP.NET PageMethod expects parameters to be JSON encoded in the request, so JSON.stringify should be applied on the data hash:
$.ajax({
type: 'POST',
url: 'popup.aspx/GetJewellerAssets',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ jewellerId: filter, locale: 'en-US' }),
dataType: 'json',
success: AjaxSucceeded,
error: AjaxFailed
});
data: '{"jewellerId":"' + filter + '","locale":"' + locale + '"}',
simply add as many properties as you need to the data object.
$.ajax({
type: "POST",
url: "popup.aspx/GetJewellerAssets",
contentType: "application/json; charset=utf-8",
data: {jewellerId: filter , foo: "bar", other: "otherValue"},
dataType: "json",
success: AjaxSucceeded,
error: AjaxFailed
});
DO not use the below method to send the data using ajax call
data: '{"jewellerId":"' + filter + '","locale":"' + locale + '"}'
If by mistake user enter special character like single quote or double quote
the ajax call fails due to wrong string.
Use below method to call the Web service without any issue
var parameter = {
jewellerId: filter,
locale : locale
};
data: JSON.stringify(parameter)
In above parameter is the name of javascript object and stringify it when passing it to the data attribute of the ajax call.
$.ajax({
type: 'POST',
url: 'popup.aspx/GetJewellerAssets',
data: "jewellerId=" + filter+ "&locale=" + locale,
success: AjaxSucceeded,
error: AjaxFailed
});
Has anyone else noticed that the json string/object is invalid in all answers except for David Hedlund's? :)
JSON objects must be formatted in the following manner: {"key": ("value" | 0 | false)}. Also, writing it out as a string requires much less than stringifying the object...
var valueOfTextBox=$("#result").val();
var valueOfSelectedCheckbox=$("#radio:checked").val();
$.ajax({
url: 'result.php',
type: 'POST',
data: { forValue: valueOfTextBox, check : valueOfSelectedCheckbox } ,
beforeSend: function() {
$("#loader").show();
},
success: function (response) {
$("#loader").hide();
$("#answer").text(response);
},
error: function () {
//$("#loader").show();
alert("error occured");
}
});
Just to add on [This line perfectly work in Asp.net& find web-control Fields in jason Eg:<%Fieldname%>]
data: "{LocationName:'" + document.getElementById('<%=txtLocationName.ClientID%>').value + "',AreaID:'" + document.getElementById('<%=DropDownArea.ClientID%>').value + "'}",
Its all about data which you pass; has to properly formatted string.
If you are passing empty data then data: {} will work.
However with multiple parameters it has to be properly formatted
e.g.
var dataParam = '{' + '"data1Variable": "' + data1Value+ '", "data2Variable": "' + data2Value+ '"' + '}';
....
data : dataParam
...
Best way to understand is have error handler with proper message parameter, so as to know the detailed errors.
I successfully passed multiple parameters using json
data: "{'RecomendeeName':'" + document.getElementById('txtSearch').value + "'," + "'tempdata':'" +"myvalue" + "'}",
data: JSON.stringify({ "objectnameOFcontroller": data, "Sel": $(th).val() }),
controller object name

Calling asp.net webmethod with params from jquery errors

I managed to setup a simple webmethod which i called from jquery and sure enough it returns ... then i added parameters on the method and added the params to jquery but it errors with
Message":"Invalid JSON primitive: one.","StackTrace":"
my signature on my webmethod is like so
[WebMethod]
public static string GetDate(string one, string two)
{
return "yes";
}
and my jquery is like this, what am i doing wrong?
$.ajax({
type: "POST",
url: "MyService.aspx/GetDate",
data: { one: "value", two: "value" },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg.d);
},
error: function(msg) {
alert('error');
}
});
Try enclosing your data parameter in quotes:
data: '{ one: "value", two: "value" }',

Resources