Not geting expected data from jquery ajax call - c#

Here is the c# web method
[WebMethod]
public string Hello()
{
return "Hello World";
}
Here is the jquery ajax code
$.ajax({
url: "http://10.0.2.2/SampleService/Service/HelloWorld.asmx",
dataType: 'text',
cache: false,
crossDomain: true,
timeout: 15000,
success: function (rtndata) {
alert('Got Success ::'+ rtndata);
},
error: function (xhr, errorType, exception) {
alert("Excep:: "+exception +"Status:: "+xhr.statusText);
}
});
But instead of getting Hello World in rtndata i'm getting the full html response page.

You need to return a json model or disable layout

If you receive an html page is because you are sending a html page.
You should double check your code to know if anything is append to the response before send the output.
Try to send a JSON formatted response to the ajax call like:
{'hello':'world'}
Then you add dataType as an option of $.ajax. If you want to print the output, you can do alert(JSON.stringify(response)).
$.ajax({
url: "http://10.0.2.2/SampleService/Service/HelloWorld.asmx",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
crossDomain: true,
timeout: 15000,
success: function (rtndata) {
alert('Got Success ::' + JSON.stringify(rtndata));
},
error: function (xhr, errorType, exception) {
alert("Excep:: " + exception + "Status:: " + xhr.statusText);
}
});
There are an important thing... More times you add cache: false, but this does not work properly and you should do a trick to solve.
Add the timestamp as a parameter of the call like:
var date = new Date();
$.ajax({
url: "http://10.0.2.2/SampleService/Service/HelloWorld.asmx?timestamp="+date.now(),
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
crossDomain: true,
timeout: 15000,
success: function (rtndata) {
alert('Got Success ::' + JSON.stringify(rtndata));
},
error: function (xhr, errorType, exception) {
alert("Excep:: " + exception + "Status:: " + xhr.statusText);
}
});
Hope this helps...

The html page you get is an overview of all the available webmethod in the servicer - an API of sorts. Try navigating to it in a browser.
If you want to call your Hello WebMethod you should add "/Hello" as the method name to the url:
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: 'http://10.0.2.2/SampleService/Service/HelloWorld.asmx/Hello',
dataType: 'json',
cache: false,
crossDomain: true,
timeout: 15000,
success: function (rtndata) {
alert('Got Success ::'+ rtndata);
},
error: function (xhr, errorType, exception) {
alert("Excep:: "+exception +"Status:: "+xhr.statusText);
}
});
You can read more here: http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/

You have to append the method name to the URL (/HelloWorld, for example) and specify method: "post" in your ajax call (if you want to use a POST request). Try this:
$.ajax({
url: "http://10.0.2.2/SampleService/Service/HelloWorld.asmx/HelloWorld",
method:"POST",
dataType: "text",
cache: false,
crossDomain: true,
timeout: 15000,
success: function (rtndata) {
alert('Got Success ::' + rtndata);
},
error: function (xhr, errorType, exception) {
alert("Excep:: " + exception + "Status:: " + xhr.statusText);
}
});
If you want to use GET as the request method, make sure you have this tags in your web.config file:
<system.web>
<webServices>
<protocols>
<add name="HttpGet" />
<add name="HttpPost" />
</protocols>
</webServices>
</system.web>
Also, you need to decorate the service method with the ScriptMethodAttribute:
[ScriptMethod(UseHttpGet = true)]
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
The ajax call (method: "GET" is optional, as it is the default method for text):
$.ajax({
url: "http://localhost:57315/helloworld.asmx/HelloWorld",
method: "GET"
dataType: "text",
cache: false,
crossDomain: true,
timeout: 15000,
success: function (rtndata) {
alert('Got Success ::' + rtndata);
},
error: function (xhr, errorType, exception) {
alert("Excep:: " + exception + "Status:: " + xhr.statusText);
}
});
As you are using cache: false, probably you want to use the GET request:
Setting cache to false will only work correctly with HEAD and GET requests.
It works by appending "_={timestamp}" to the GET parameters.

Related

Ajax method always goes to error function

I have this simple ajax method:
$.ajax({
type: 'POST',
url: 'http://localhost:1195/widget/postdata',
datatype: "jsondata",
async: false,
success: function (data) {
alert("ok")
},
error: function (data) {
alert(data.status + ' ' + data.statusText);
}
});
And this simple method in c#:
[HttpPost]
public JsonResult PostData()
{
return Json("1");
}
When I check the inspector console I have "1" in response but my ajax method always goes to error function.
Why is it so?
In your AJAX call it should be dataType: "json" and not datatype: "jsondata". You can refer to the docs
Also use #Url.Action tag in your url call: url: '#Url.Action("postdata", "widget")'
For a small test, I have used the following AJAX call to the same controller method that you have posted and I am getting the correct result:
$(document).ready(function () {
$("#button_1").click(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url:'#Url.Action("PostData", "Home", null, Request.Url.Scheme)',
datatype: "json",
async: false,
success: function (result) {
alert(result);
},
error: function (error) {
alert(error);
}
});
});
});
</script>
<button id="button_1" value="val_1" name="but1">Check response</button>
Output:
Change the Ajax request to the following :
$.ajax({
type: 'POST',
url: '/widget/postdata',
datatype: "json",
async: false,
success: function (data) {
console.log(data);// to test the response
},
error: function (data) {
alert(data.status + ' ' + data.statusText);
}
});
Always use relative URL instead of full URL that contains the domain name, this will make the deployment easier so you don't have to change the URls when going live

async ajax call error won't show Error.cshtml

I'm calling a function in the controller using ajax. If there is an error in the controller, it goes to the Error.cshtml page, sends an error email from that page, but it won't render the Error.cshtml page on the screen, it stays on the page with the ajax call.
How do I fix that?
Here is the ajax call:
$("#County").change(function () {
$.ajax({
url: '#Url.Action("UpdateCountySessionVariables", "Home")',
type: 'POST',
data: JSON.stringify({ countyId: $("#County").val() }),
datatype: 'json',
contentType: "application/json; charset=utf-8",
success: function (data) {
location.reload();
},
failure: function (data) {
alert('failure');
},
});
});
Here is the customErrors from the main web.config:
<customErrors mode="On" defaultRedirect="~/Error" redirectMode="ResponseRedirect"/>
In your $.ajax definition you should use error property, not failure, check documentation. Like this:
$.ajax({
url: '#Url.Action("UpdateCountySessionVariables", "Home")',
type: 'POST',
data: JSON.stringify({ countyId: $("#County").val() }),
datatype: 'json',
contentType: "application/json; charset=utf-8",
success: function (data) {
location.reload();
},
error: function (data) {
alert('failure');
},
});
You also can get full error page like this:
error: function (httpRequest) {
console.log(httpRequest.responseText);
},

Ajax post returning error "Not Found"

Im having the following ajax cal in my JS file in Durundal ,
var dataJSON ={ID : "jo"};
self.js = $.ajax({
type: "POST",
dataType: text,
url: "http://localhost:53081/api/File",
data: JSON.stringify(dataJSON),
error: function (xhr, status, error) {
alert(error);
},
success: function (json) {
alert("Data Returned: " + JSON.stringify(json));
}
});
and my REST api is
[HttpPost]
public string upload(string ID)
{
string givenId = ID;
return givenId;
}
but when i call thsi methos im simply getting error alert . what went wrong
update
i have updated my code but now im getting Not found error
Change string to Text:
self.js = $.ajax({
type: "POST",
dataType: **Text**,
url: "url",
data: JSON.stringify(dataJSON),
error: function (xhr, status, error) {
alert(status);
},
success: function (json) {
alert("Data Returned: " + JSON.stringify(json));
}
});
click here for list of datatype and there representation.
You may need to change the name of the method to be PostFile. I had issues getting this to work without having the proper naming convention, even though I had the [HttpPost] attribute at the beginning of the method.
Also: try changing your dataType to "json" and adding the content type:
dataType: "json",
contentType: "application/json"

JQuery Method control goes to success block but msg.d showing Undefined

i am calling this javascript method "test" in .net1.1 onload of body.My webmethod returns string data,but i am not able to get that data in my Jquery method.
In HiddenPage.aspx
==============================
function test()
{
debugger;
$.ajax({
type: "POST",
url: "HiddenPage.aspx/GetServerTime",
//async : false,
//data: "i=1",
contentType: "application/json",
//dataType: "text",
success: function(msg)
// error: function(, textStatus, errorThrown) {
{
debugger;
alert(msg.d);
},
error: function(msg)
//complete: function (jqXHR, textStatus) {
{
debugger;
alert(msg.d);
alert("Error! Try again...");
//return false;
}
})
// return '';
}
In HiddenPage.aspx.cs i have put webmthod.My WebMethod is :-
[WebMethod()]
public static string GetServerTime()
{
return DateTime.Now.ToString();
}
Can you please post your code of returning data.
I suggest you to create an ASMX file to use a webservice. It is easy to use.
Create a webservice and Then make sure that you have add below line in your webservice before your webmethod.
[System.Web.Script.Services.ScriptService]
After that you can add your web method same as you have written.
Your jquery should be like this.
$.ajax({
type: "POST",
url: "webservice/WebService1.asmx/GetServerTime",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccessCall,
error: OnErrorCall
});
function OnSuccessCall(msg) {
alert(msg.d);
}
function OnErrorCall(msg) {
alert(msg.status + " " + msg.statusText);
}
It may help you. Happy coding.
Not quite sure about how your return data looks like but you can try the following.
$.ajax({
type: "POST",
url: "HiddenPage.aspx/GetServerTime",
//async : false,
//data: "i=1",
contentType: "application/json",
dataType: "html",
success: function(data){
alert(data);
},
error: function(jqXHR, textStatus) {
debugger;
if (jqXHR.status === 0) alert('Not connect.\n Verify Network.');
else if (jqXHR.status == 404) alert('Requested page not found. [404]');
else if (jqXHR.status == 500) alert('Internal Server Error [500].');
else if (textStatus === 'parsererror') alert('Requested JSON parse failed.');
else if (textStatus === 'timeout') alert('Time out error.');
else if (textStatus === 'abort') alert('Ajax request aborted.');
else alert('Uncaught Error.\n' + jqXHR.responseText);
//return false;
}
//return '';
}​
try the following
$.ajax({
type: "POST",
url: "HiddenPage.aspx/GetServerTime",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg.d);
// Do something interesting here.
}
});

How to use jQuery to make a call to c# webservice to get return value

I want to use jQuery to make a call to a c# web service called c.ashx which checks whether that username is valid and returns an error message as a string.
What should I put for data: and content type: if the return value of the c# webservice is a string value?
jQuery.ajax({
type: "GET",
url: "/services/CheckUserName.ashx",
data: "",
contenttype: "",
success: function (msg) {
alert("success");
},
error: function (msg, text) {
alert(text);
}
});
I have created a .asmx file instead, but it doesn't get called by the jQuery. Is the following correct?
jQuery.validator.addMethod("UsernameCheck", function (value, element) {
jQuery.ajax({
type: "POST",
url: "/services/CheckUsername.asmx?CheckUsername",
data: '{ "context": "' + jQuery("#username").value + '"}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
alert("success");
},
error: function (msg, text) {
alert(text);
}
});
});
Data should contain the parameters of the method you are calling in a web service. However, the ashx extension is for an HTTP Handler, which is not a good choice for this scenario. A web service should by used instead.
So if you were calling /services/LoginServices.asmx?CheckUserName, and CheckUserName.asmx had a webmethod ValidateUser such as
public string ValidateUser(string username)
then the data attribute for jQuery would be
data: '{ "username": "' + usernameValue + '"}'
your contentType should be application/json; charset=utf-8, and dataType should be "json".
Note that you're not going to call /services/CheckUserName.asmx, the name of the method in the web service has to be appended to the webservice url, /services/LoginServices.asmx?CheckUserName.
Also, you'll need to change your type to "POST".
Here's a complete example:
$.ajax({
type: 'POST',
url: 'LoginServices.asmx/CheckUserName',
data: '{"username": "' + usernameValue + '"}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(msg) {
alert("Result: " + msg);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error: " + textStatus);
}});
Hope this helps
The jQuery code wasn't working because it wasn't calling the webservice. I fixed this by creating a HTTP handler class and passing it the username. I changed the value for data: to the following and it passed the username entered by the user:
data: "username=" + jQuery("#username").val(),

Categories

Resources