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
Related
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
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
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() }
I have the following code and it`s pointing out errors as follows
Error 1 The name 'date' does not exist in the current context
Error 2 The name 'person' does not exist in the current context
What is wrong?
$("#test").Click(function () {
var date = $("#DateFrom").val();
var person = Model.SelectedPerson;
$.ajax({
url: '#Url.Action("testEmp","Employee",new {dateFrom = date, selectedPerson= person})',
type: 'GET',
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function (result) {
$('#text).html(result);
},
});
return false;
});
Try this:
$.ajax({
url: '#Url.Action("ActionName")',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({ date: '..', person: '...' }),
success: function(result) {
}
});
EDIT: Take a look at this answer for the complete solution.
jquery ajax forms for ASP.NET MVC 3
In my javascript, I have:
var testdate = "{'TheNewDate' : '12/02/2011'}";
$("#mydiv").click(function () {
$.ajax({
type: "POST",
url: "../Pages/Appointments.aspx/GetAppointements",
data: testdate,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFn,
error: errorFn
});
});
In my code behind I have
[WebMethod]
public static string GetAppointements(string DateInput)
{
var t = DateInput;
However, when I click to run the call, I get the error function to activate. When I change the code behind function to public static string GetAppointement() it works. But I guess my goal is to pass a parameter to the code behind. What am I missing?
Thanks.
Your parameter is called DateInput and not TheNewDate, so:
$('#mydiv').click(function () {
$.ajax({
type: 'POST',
url: '../Pages/Appointments.aspx/GetAppointements',
data: JSON.stringify({ dateInput: '12/02/2011' }),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: successFn,
error: errorFn
});
});
You should make your JSON data match the parameter name in the web service method.
var testdate = "{'DateInput' : '12/02/2011'}";