Just another jQuery AJAX not POST parameters correctly - asp.net

I've googled many similar situations, but none of them could solve my problem. Please take a look at my code:
JavaScript:
$.ajax({
type: 'POST',
url: 'alarmInfo.aspx',
data: {request:'BasicGpaInfo'},
dataType: "json",
success: function (data) {
alert(data);
},
error: function () {
alert("Error in loading alarm information!");
}
});
ASP.NET:
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Form["request"] == "BasicGpaInfo")
{
Response.Write(BasicGpaInfo());
}
else
{
Response.Write("Nothing");
}
}
This always returns "Nothing" and break point tells that Request.Form is null. And I have tried with GET and Request.QueryString which gives the same situation.
I guess there's something wrong with data in ajax function and I've tried with the following things that won't help:
data: $.param({request:'BasicGpaInfo'})
data: "{request:'BasicGpaInfo'}"
data: {request:'BasicGpaInfo'}
It won't work on all Web Browsers.
Please give some advice. Thanks!

I tested your code and it runs fine. However it always returns "Error in loading alarm information!" because you are not returning Json from the server.
Javascript is fine, once you return json, it will go into success.
You are returning the whole page, and your ajax method is getting the whole html instead of Json from BasicGpaInfo()
try putting a breakpoint in alert, and you will see all the data come inside data
error: function (data) {
alert("Error in loading alarm information!");
}
alternatively try
error: function (data) {
alert(data);
}
Here is the full code
$.ajax({
type: 'POST',
url: 'Default.aspx/BasicGpaInfoWebMethod',
data: { request: 'BasicGpaInfo' },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data);
},
error: function (data) {
alert("Error in loading alarm information!");
//alert(data); // uncomment to see the whole response
}
});
and your webmethod will be :
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string BasicGpaInfoWebMethod(string request)
{
return request;
}

Try this JSON.stringify before post. For using JSON.stringify in IE<=7 include json2.js file from json.org
$.ajax({
type: 'POST',
url: 'alarmInfo.aspx',
data: JSON.stringify({ request: 'BasicGpaInfo'}),
dataType: "json",
success: function (data) {
alert(data);
},
error: function () {
alert("Error in loading alarm information!");
}
});

Related

Web Method not called in ajax aspx web form

Here is my ajax request:
$("#<% =txtDiagnosisData.ClientID %>").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
url: 'EMR.aspx/SearchDiagnosis',
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (data) {
// response(data.d);
alert("success");
},
error: function (result) {
alert("error");
}
});
}
});
Here is my function:
[WebMethod]
public static List<string> SearchDiagnosis()
{
return new DataAccess().GetDiagnosis();
}
My method is not called from ajax, it always goes to the error part
How to solve this?
There could be an issue that you might be using Session variables inside you web method directly or indirectly.
Somewhere in the function DataAccess().GetDiagnosis();
In that case use attribute like [WebMethod(enableSession: true)] in stead of
[WebMethod]
Also try to get the error by implementing error properly like below
error: function (jqXHR, textStatus, errorThrown) {
if (jqXHR.status == 500) {
alert('Internal error: ' + jqXHR.responseText);
} else {
alert('Unexpected error.');
}
}
Ref : jQuery ajax error function and see what error exactly you are getting.

Asynchronous ajax call causing issue in KnockOutjs

I have a button on click of that i am calling something like :
ViewModel:
self.MyArray = ko.observableArray();
self.remove = function(c) {
ko.utils.arrayForEach(c.sData(), function(ser) {
if (ser.Check() == true) {
self.MyArray.push(service);
count++;
}
});
if (count) {
$.ajax({
url: "/api/LoadCustomer/?reason=" + reason,
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: ko.toJSON(self.MyArray),
success: function(data) {
ko.utils.arrayForEach(self.MyArray(), function(removedata) {
c.sData.remove(removedata);
});
}
});
self.MyArray([]);
}
};
If i include async:false in my ajax call i get everything fine but if i didn't include async (its default property is true) i dont know somehow in my success function of ajax call self.MyArray() remains Empty but its not the case if i keep it false (Awkward).
Sometimes i fear like if i have series of ajax calls with async:true while loading into a observable array(OnLoad) there may be a slight chance of misplacement of data .
Help me understand .
The reason your observable array MyArray is empty sometimes is because this line of code self.MyArray([]); executing before the ajax call is done. How about this instead -
if (count) {
$.ajax({
url: "/api/LoadCustomer/?reason=" + reason,
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: ko.toJSON(self.MyArray),
success: function (data) {
ko.utils.arrayForEach(self.MyArray(), function (removedata) {
c.sData.remove(removedata);
});
},
complete: function() { // complete fires after success and error callbacks
self.MyArray([]); // empty the array no matter what happens (error or success)
}
});
}

ajax failing only in IE

i have this jquery code
$("#ProfileBtn").click(function () {
if (true) {
$.ajax({
type: "POST",
url: "sMaster.Master/outClick",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
alert("~");
location.reload();
},
error: function () {
alert("!");
}
});
}
});
that calls the asp.net function:
[ScriptMethod, WebMethod]
public static void outClick()
{
}
when i try it using chrome or firefox everything is fine (alert("~")), but on Internet Explorer it fails (alert("!")).
any idea why..?
update: i've tried putting this instead of the error:
error: function (jqXHR, textStatus, errorThrown) {
alert(jqXHR);
alert(textStatus);
alert(errorThrown);
}
and what i get in the alerts is:
[object XMLHttpRequest]
error
undefined
i've also tried jqXHR.Status and it gave me 404 in the alert.
As far as I understood the problem is that ajax (maybe only in IE) can't call functions from master page. (I tried moving the jQuery and asp.net function to an aspx and aspx.cs page and it all worked)
Thought I did also find a better way to do what I intended.
Thanks anyway.

X-editable with .Net and c# web methods

I am using X-Editable Plugin in Asp.net.
I have tried this: Usage with .Net and C# Webmethods
But it gives me error. It is not calling the WebMethod as it should be.
How to solve this problem?
Please help.
Javascript:
$('#username').editable({
url: function (params) {
return $.ajax({
url: 'Default.aspx/TestMethod',
data: JSON.stringify(params),
dataType: 'json',
async: true,
cache: false,
timeout: 10000,
success: function (response) {
alert("Success");
},
error: function () {
alert("Error in Ajax");
}
});
}
});
HTML:
superuser
WebMethod in Default.aspx:
[System.Web.Services.WebMethod]
public static String TestMethod(String params)
{
//access params here
}
If you want to call a page method, first of all you need to make a request of type POST (also having content-type set will not do any harm):
$('#username').editable({
url: function (params) {
return $.ajax({
type: 'POST',
url: 'Default.aspx/TestMethod',
data: JSON.stringify(params),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: true,
cache: false,
timeout: 10000,
success: function (response) {
alert("Success");
},
error: function () {
alert("Error in Ajax");
}
});
}
});
Also the JSON will be auto deserialized on server side, so you should expect the name, pk and value parameters on server side (this is what plugin is sending according to docs)
[System.Web.Services.WebMethod]
public static String TestMethod(string name, string pk, string value)
{
//access params here
}
In your case the pk will be null as you haven't set one.

2 page methods on an aspx page

I'm calling a page method with jquery and it works just fine. I'm creating a second one and it's not working at all; all I get is the error function. Is it possible to put more than 1 page method in an aspx page?
Here's my jquery on the client:
function LoadCount() {
var TheObject = $.toJSON(CurrentForm);
var TheParameter = "{'TheParameter' : '" + TheObject + "'}";
$('#testobj').html("loading");
$.ajax({
type: "POST",
url: "../Pages/MyPage.aspx/GetCount",
data: TheParameter,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFn,
error: errorFn
});
};
function successFn(thedata) { $('#result').html(thedata.d); };
function errorFn() { alert("problem getting count"); };
function LoadData() {
var ConfirmLoad = "test";
$.ajax({
type: "POST",
url: "../Pages/MyPage.aspx/GetLoaded",
data: ConfirmLoad,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successLoad,
error: errorLoad
});
};
function successLoad(thedata) { alert((thedata.d)); };
function errorLoad() { alert("problem getting loaded"); };
And on the server side, I have this:
[WebMethod]
public static string GetCount(string TheParameter)
{
// some code
return JsonResult;
}
[WebMethod]
public static string GetLoaded(string ConfirmLoad)
{
return "test string";
}
LoadCount and GetCount work great, I thought I'd copy the implementation to create another page method but the second time, nothing good happens. Thanks for your suggestions.
You need to set dataType: "text" in the $.ajax() call properties if you're just returning plain text instead of a JSON encoded string.
You might also want to leave the contentType unspecified (at the default value of 'application/x-www-form-urlencoded') if your're sending plain text instead of a JS object.

Resources