Json PaserError when calling web service - asp.net

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.

Related

Using Webservice to call external Json file using ajax call

I have a Json file and an ajax call in Javascript file. Trying to write correct webservice method using Hello World asmx file template. What should I write in method in order to make it display/return/read json data on website?
$(document).ready(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "http://localhost:56537/WebService.asmx/HelloWorld",
data: "{}",
dataType: "json",
success: function (Result) {
debugger;
Result = Result.d;
var data = [];
var dataResource = response
Thats is the solution that worked for me:
[WebMethod]
public string HelloWorld() {
using (StreamReader r = new StreamReader(#"C:\Users\data.json"))
{
string json = r.ReadToEnd();
return json;
}

Call code-behind function from java script in c#

Is it even possible? To call a code-behind c# function from java script in a visual web part?
It is a complex function so converting all codes to client side is not an option.
I want the logic that is there in this function to happen without a page refresh.
Thanks.
We can call a method in codebehind from the JQuery AJAX call and depending upon the status whether it is error or success the corresponding method will be executed.
function MyMethod() {
$.ajax({
type: "POST",
url: "CodeBehind.aspx/ClearData",
contentType: "application/json;charset=utf-8",
data: '',
dataType: "json",
success: function (data, textStatus) {
closePopUpwindow1();
},
error: function (data, textStatus) {
closePopUpwindow2();
}
});}
[WebMethod]
public static void ClearData(){
Page.SetGridSessionData(gridID, null);
}
If the server side method is successfully executed then closePopUpwindow1 method is executed else closePopUpwindow2 method will be executed.
You can use j Query ajax to call server side method and get the response to be used in java script.
This article has simple and good example to show what you need to do.
public partial class _Default : Page
{
[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToString();
}
}
Java script
$.ajax({
type: "POST",
url: "PageName.aspx/MethodName",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something interesting here.
}

asp.net web api 2 attribute route is not found

I have this route in an API controller called Recruiting:
ResponseType(typeof (int))]
[Route("Recruiting/setprimary/")]
public async Task<IHttpActionResult> PutUpdatePrimary(string userId, string orgId)
{
return Ok();
}
I am trying to hit this routing via ajax like so:
self.updatePrimary = function () {
var orgKey = self.selectedOrgKey();
alert(orgKey);
$.ajax({
type: "PUT",
contentType: "application/json; charset=utf-8",
url: "/Recruiting/setprimary/" + "?userId=" + userId + "&?orgId=" + orgKey,
data: null,
dataType: "json",
success: function (data) {
bootbox.alert('Changes saved successfully.');
},
error: function (err) {
bootbox.alert('An error occured while trying to set primary organisation. Please try again :/');
}
});
return true;
};
Fiddler is saying it cannot find the route. What do I have wrong here?
Looks like you have a typo in your request url: Instead of "&?orgId="..it should be "&orgId="

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