Passing multiple parameters with Ajax - asp.net

I have a function in my .aspx page where I collect the first name and last name from the user and would like it to pass back to the server side code(c#). Ajax is being used and runs fine when one parameter is passed, although when a second parameter is passed I receive an error : can someone shed a little light, thanks
ERROR:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
POST http://ingleParam.aspx/GetCurrentTime 500 (Internal Server Error) jquery-.11.1.min.js:4
send jquery-1.11.1.min.js:4
m.extend.ajax jquery-1.11.1.min.js:4
ShowCurrentTime SingleParam.aspx:12
onclick
.ASPX Code
function ShowCurrentTime() {
$.ajax({
type: "Post",
url: "SingleParam.aspx/GetCurrentTime",
data: { name: $("#<%=txtUserName.ClientID%>").val(),
lastName: $("#<%=txtLastName.ClientID%>").val() },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
alert(response.d);
}
Server Side Code:
[WebMethod]
public static string GetCurrentTime(string name, string lastname) {
return "Hello " + name + Environment.NewLine + "The current time is " + DateTime.Now.ToString();
}

I've had issues with sending json objects to webmethods. I've had success when I stringify the data being sent across. Like so:
data: JSON.stringify({name: $("#<%=txtUserName.ClientID%>").val(),
lastName: $("#<%=txtLastName.ClientID%>").val()}),
Give that a try and see if it helps.

Related

Json PaserError when calling web service

I am getting this "Json ParserError" in chrome console when looping through the response returned by web service. I am using dataType: jsonp as i am trying to call cross domain ajax call in development environment, BUT stuck with this error.
$.ajax
function callajax1() {
$.ajax({
url: "http://www.sample.com/Integration/PhotoCompetitionHelper.asmx/SayHello",
data: "",
dataType: 'jsonp',
type: 'POST',
contentType: "application/json; charset=utf-8",
jsonpCallback: 'showResult',
success: function (data) {
console.log(data.d)
},
error: function (data, status) {
console.log("FAILED:" + status);
}
});
}
function showResult(data) {
console.log(data.d);
}
WebService
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string SayHello()
{
return "Hello";
}
JSON Response
{"d":"Hello"}
ERROR
FAILED:parsererror
You are getting the parser error because when your dataType is jsonp, it expects a script and not json. Try to include a callback function.

javascript post 500 serrver internal error

i'm using ajax and web methods and when i execute this code appear an error thar say
post POST 500 (Internal Server Error)
but this path Exist!!!
this code is i'm using in this moment
function fnSendID() {
$.ajax({
type: "POST",
url: "GMap.aspx/SendCommands",
data: '{IDMobile: "'+$("#<%=Ddl_MobileCustomer.ClientID%>").val()+'"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
console.log("Entro : " + response.d);
},
failure: function (response) {
console.log("Fallo : " + response.d);
}
});
<WebMethod()> _
Public Shared Function SendCommands(ByVal IDMobile As String) As String
'iIDMobile = GetMobileID(iIDMobile)
Dim sResponse As String = IDMobile + "Buenas"
Return sResponse
End Function
A 500 means the path you are hitting caused an error on the server side not that the path doesn't exist.
Debug the code and set a breakpoint at Dim sResponse As String = IDMobile + "Buenas".
Does it reach here? Is there any exception before the return?

unable to get correct status code in AJAX Error handler

I am not able to get correct error code in the error handler of AJAX request. Everytime the error occurs, it returns me statusCode = 500. I tried to set it explicitly in my service as HttpContext.Current.Response.StatusCode = 403;, but still it gives me status = 500.
This is how my AJAX request looks like:
$.ajax({
type: "POST",
url: "Services/someSvc.asmx/SomeMethod",
cache: true,
contentType: "application/json; charset=utf-8",
data:"{}",
dataType: "json"
error: ajaxFailed
});
function ajaxFailed(xmlRequest) {
alert(xmlRequest.status + ' \n\r ' + //This is always 500.
xmlRequest.statusText + '\n\r' +
xmlRequest.responseText);
}
What am i missing here?
Looks like you were almost there, here is an example [WebMethod] that would throw a StatusCode 403.
[WebMethod]
public static string HelloWorld(string name)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.StatusCode = 403;
return null;
}
Here is the calling jQuery Code.
$(document).ready(function ()
{
var jsonRequest = { name: "Zach Hunter" };
$.ajax({
type: 'POST',
url: 'Demo.aspx/HelloWorld',
data: JSON.stringify(jsonRequest),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data, text)
{
$('#results').html(data.d);
},
error: function (request, status, error)
{
$('#results').html('Status Code: ' + request.status);
}
});
});
If you don't return a value as specified in your method signature you'll get a status code 500 returned.
According to the documentation:
error(jqXHR, textStatus, errorThrown)
A function to be called if the request fails. The function receives
three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a
string describing the type of error that occurred and an optional
exception object, if one occurred. Possible values for the second
argument (besides null) are "timeout", "error", "abort", and
"parsererror". When an HTTP error occurs, errorThrown receives the
textual portion of the HTTP status, such as "Not Found" or "Internal
Server Error." As of jQuery 1.5, the error setting can accept an array
of functions. Each function will be called in turn. Note: This handler
is not called for cross-domain script and JSONP requests. This is an
Ajax Event.
So change your code to something more like this:
$.ajax({
type: "POST",
url: "Services/someSvc.asmx/SomeMethod",
cache: true,
contentType: "application/json; charset=utf-8",
data:"{}",
dataType: "json",
error: ajaxFailed (jqXHR, textStatus, errorThrown)
});
function ajaxFailed(jqXHR, textStatus, errorThrown) {
alert(errorThrown + ' \n\r ' + textStatusText);
}
You might also find this answer provides some additional info.

webservice not returning values to on jquery ajax request

I would like consume cross-domain web-service from client with jquery.here is my code
function getId() {
var testid = ($('#<%=PreviousTest.ClientID %> OPTION:selected').val());
jQuery.support.cors = true;
jQuery.ajax({
type: "POST",
url: "../FalconWebService.asmx/minlatency",
data: "{'testId':" + testid + "}",
contentType: "application/json; charset=utf-8",
dataType:"json",
success: function (data) {
alert("catch");
var msg = jQuery.parseJSON(data.Table);
return msg;
},
Error: function () {
alert("error");
}
my webservice returns values in this format
{"Table":[{"minlatency":16.0,"Time":"/Date(1328248782660+0530)/"},{"minlatency":7.0,"Time":"/Date(1328248784677+0530)/"},{"minlatency":13.0,"Time":"/Date(1328248786690+0530)/"},{"minlatency":6.0,"Time":"/Date(1328248788690+0530)/"},{"minlatency":20.0,"Time":"/Date(1328248790707+0530)/"},{"minlatency":12.0,"Time":"/Date(1328248792723+0530)/"},{"minlatency":26.0,"Time":"/Date(1328248794723+0530)/"},{"minlatency":18.0,"Time":"/Date(1328248796723+0530)/"}]}
Calls in cross-domain work in a different way. They create dynamic javascripts that are inserted to the page using a callback function. This function is used to handle the response from the service. The Jquery calls add a "?callback=?" to the URL of the service, where "callback" is the name of the function that will be inserted.
To call cross-domain services with JQuery you have to do the following:
jQuery.ajax({
type: "POST",
url: "../FalconWebService.asmx/minlatency",
data: "{'testId':" + testid + "}",
contentType: "application/json; charset=utf-8",
dataType: "jsonp", //The data type that you must use is JSONP. Basically tells JQuery that the request is cross-domain
success: function (data) {
alert("catch");
var msg = jQuery.parseJSON(data.Table);
return msg;
},
Error: function () {
alert("error");
},
jsonpCallback: 'callback' //Dude to the fact that the JS is being generated dynamicaly, this tells JQuery to use the name "callback" for the function that will handle the result, as it adds "?callback=?" to the URL
});
You could also use "jsonp" instead of "jsonpCallback" if you want to "override the callback function name in a jsonp request" (from JQuery).
It worked for me (in WCF REST services which communicate with JSON messages, but it should work the same way in your case). This is all explained in the JQuery Ajax documentation.
Hope this helps.

$.ajax success not executing

I have in my .js file a function that call a webservices method called getStudents:
[WebMethod(Description = "white student list")]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<Job> getStudents(long classId)
{
return (new classManager()).getStudents(classId);
}
the method is callled like:
function loadStudents() {
var parameters = JSON.stringify({ 'classId': 0 });
alert(parameters);
$("#ProcessingDiv").show('fast', function() {
$.ajax({
type: "POST",
url: "myWebService.asmx/getStudents",
data: parameters,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
$("#ProcessingDiv").hide();
var students= response.d;
alert('yes');
},
error: function(request, status, error) {
alert(request.responseText);
}
,
failure: function(msg) {
alert('somethin went wrong' + msg);
}
});
});
}
$(document).ready(function() {
loadStudents();
});
when i debug,the service web method is executed successfully but i don't get my alert('yes') and neither msg error.
What's wrong?
If you're returning (serialized to JSON) List of objects, then in response you will get JS array of JS objects, so (assuming Job has property p) try response[0].p for p value from first element.
note: I don't know ASP.NET, so maybe response is serialized in another way, thats where tools like Firebug (or other browsers Dev tools) are extremely useful - because you can look how exactly you'r http requests and responses looks like.
ps. And change alert to console.log and look for logs in Firebug console - its better than alert in many, many ways ;]

Resources