Thursday, 22 June 2017

.net - Calling simple web service (.asmx file) from AJAX and JQuery using JSON - parse error



Making my first steps in trying to use all these technologies together.. I'm having some toubles..
Here is my Server side:





[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string simplestMethod()
{
return "Simplest method returned";
}



And here is my client side:



 $(document).ready(function(){
$("a").click(function(event){
$.ajax({
type: "POST",
url: "http://localhost:53346/d2/TAPI.asmx/simplestMethod",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",

success: function (data) {
alert(data.d);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Error Occured!" +" | " + XMLHttpRequest +" | " + textStatus +" | " +
errorThrown );
}
});
});
});



The result is an alert that says:
Error Occured! | [object XMLHttpRequest] | parseerror | undefined.
What parsing failed and why?
I should mention that calling the WS method directly does work.
Thanks a lot!


Answer



Your code looks like good with one suspected place: url. You should replace url to something like "TAPI.asmx/simplestMethod" or "/d2/TAPI.asmx/simplestMethod".



Moreover if you want study to how to call web method with parameters or return more complex data from the web method look at How do I build a JSON object to send to an AJAX WebService? and asmx web service, json, javascript/jquery?, Can I return JSON from an .asmx Web Service if the ContentType is not JSON?. How to decode error messages from the exception inside of web method see Get xhr object in vb.net while ajax calling fails.


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...