Code behind function of an aspx is not getting called using $.ajax - javascript

I have a web form IndexPage.aspx. The script part of this front end code is calling a code-behind function using ajax call.Here's the code:
$.ajax({
type: "POST",
url: '<%=ResolveUrl("~//IndexPage.aspx//SaveXml")%>',
data: JSON.stringify(logic),
contentType: "application/json; charset=utf-8",
dataType: "json",
//async: true,
//cache: false,
success: function (msg) {
alert("AJAX received : " + msg.d);
},
error: function (msg) {
alert("Failed : " + msg.d);
}
});
The "Failed" alert box is shown with return value 'undefined' after I run the code.
The code behind function is:
public static string SaveXml(string logic)
{
return logic;
}
This code-behind function is not getting called. The breakpoint which I have set at the code-behind function is not getting hit. I have tried almost all solutions from stack overflow. Please see if anythig is wrong in this code.

Thanks friends,
The issue was resolved. Checking browser console and network helped me a lot to solve the error.
I did two changes
1) Added [System.Web.Services.WebMethod] to code-behind function
2) Changed my => data: JSON.stringify(logic) ..... to ....=> data: '{ logic:\''+ logic +'\'}'
I did the second change after referring to this link: "Invalid JSON primitive" in Ajax processing
While sending just a string you need to add escape sequence.

Resolved
Ajax call:
$.ajax({
type: "POST",
url: '<%=Page.ResolveUrl("~/WebForm1.aspx/SaveXml")%>',
data: JSON.stringify({ "logic": "logic value" }),
contentType: "application/json; charset=utf-8",
dataType: "json",
//async: true,
//cache: false,
success: function (msg) {
alert("AJAX received : " + msg.d);
},
error: function (msg) {
alert("Failed : " + msg.d);
}
});
Web Method
[WebMethod]
public static void SaveXml(string logic) {
}
Web.config
<system.web>
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>

Related

500 Internal Server Error in ajax when calling web server method in C#

When I am calling server method from AJAX call at that time showing 500 internal server error. And this error also happens sometimes only, while sometimes it is working fine.
I am really confused that what is going on that it is sometimes working and sometimes not working. In fact I didn't change anything after working the code but when I check second day it is coming this type of error.
Here is my code
<input type="button" id="btn_save" value="Save" class="button" />
$(document).on("click", "#btn_save", function (e) {
$.ajax({
type: "POST",
url: "schoolregistration.aspx/EntrySave",
data: JSON.stringify({ schoolName: $('#txt_schoolname').val() }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function () {
document.getElementById("txt_schoolname").value = "";
alert("Error! Try again...");
}
});
});
function OnSuccess(response) {
document.getElementById("txt_schoolname").value = "";
alert(response.d);
}
[WebMethod]
public static string EntrySave(string schoolName)
{
//Here is the code
}
Sometimes working fine but sometimes not coming call in this entrysave method.
try this:
$.ajax({
type: "POST",
url: "schoolregistration.aspx/EntrySave",
data: { "schoolName": $('#txt_schoolname').val() },
contentType: "application/json; charset=utf-8",
dataType: "json",
success:function (data) {alert('ok');},
error: function () {alert('error');}
});

Webservice method not found by JQuery Ajax-Request error 500

JS:
function showComments(couponId) {
var jsontxt = JSON.stringify({ couponId });
$.ajax({
type: "POST",
url: "<% =Page.ResolveUrl("~/Admin/UserCoupons.aspx/GetComments") %>",
data: jsontxt,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
//async:true,
success: function (result) {
alert("We returned: " + result.d);
},
failure: function (response) {
alert(response.d);
}
});
}
C#:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string GetComments(string couponId)
{
//will return precomipled generated html for display in div
return "Success";
}
The C# code is in page's code behind .cs file
i have solved this all before using stack over flow
thanks to experts here.
but this time there is some thing else
i am getting my debug pointer in page_load method then in master page's page load method. but debug doesn't enters to the GetComments
and getting exception
Unknown web method GetComments.
Parameter name: methodName
Below is the stackTrace
at System.Web.Script.Services.WebServiceData.GetMethodData(String methodName)
at System.Web.Script.Services.RestHandler.CreateHandler(WebServiceData webServiceData, String methodName)
at System.Web.Script.Services.RestHandler.CreateHandler(HttpContext context)
at System.Web.Script.Services.RestHandlerFactory.GetHandler(HttpContext context, String requestType, String url, String pathTranslated)
at System.Web.Script.Services.ScriptHandlerFactory.GetHandler(HttpContext context, String requestType, String url, String pathTranslated)
at System.Web.HttpApplication.MaterializeHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Your data in ajax should be JSON.stringify({ couponId:'123' }) //parameter name & value.
function showComments(couponId) {
var jsontxt = JSON.stringify({ couponId:'123' });
$.ajax({
type: "POST",
url: "<% =Page.ResolveUrl("~/Admin/UserCoupons.aspx/GetComments") %>",
data: jsontxt,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
//async:true,
success: function (result) {
alert("We returned: " + result.d);
},
failure: function (response) {
alert(response.d);
}
});
}
after a long google and all others and applying every possible solutions. finally, i found a solution. and that's
edit the file at ~/App_start/RouteConfig.cs
replace
settings.AutoRedirectMode = RedirectMode.Permanent;
with
settings.AutoRedirectMode = RedirectMode.Off;
this solved my problem. any ways thanks to all who took interest and showed their generosity.

Having Trouble with a cross Domain jquery/Ajax service call

I've read through thread after thread on here and elsewhere trying to get a cross domain ajax call to work. I have a Restful WCF service that returns a simple bool. I have it setup with the proper response format (Json) and the expected url with the callback parameter:
[WebGet(RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "ShowCreditCardTextJQUERY?memberNumber={memberNumber}&callback={callback}",
BodyStyle = WebMessageBodyStyle.WrappedRequest)]
My Ajax looks like this:
$.ajax({
url: "http://example.com/service/service.svc/ShowTextJQUERY",
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
crossDomain:true,
data: "{'memberNumber':'" + memberNumber + "'}",
cache: false,
//success: alert(memberNumber),
success: function (data) {
var output = data;
if (!data) {
$("#dialog").dialog(
{
modal: true,
width: 735,
height: 550
});
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
}
});
I receive a 200 for the response but that is coming in the error block. I am at a loss (and still pretty new to jquery/ajax). Any help would be greatly appreciated.
May be these lines of code solve your problem, which is for regular web service call
var jsonData = [YOUR JSON PARAMETER];
$.ajax({
async: false,
type: "POST",
url: [YOUR WEB SERVICE URL],
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ json: jsonData }),
dataType: "json",
success: OnSuccess,
failure: function(err) {
alert("Error : " + err.d);
}
});
function OnSuccess(data) {
alert("Success:" + data.d);
}
You can do one thing for that just need to set Access-Control-Allow-Origin & Access-Control-Allow-Headers in CustomeHeaders your web service web.config file.
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
If you want to allow only for specific domain , you can do that with specific value of domain instead of * value

AJAX to asmx (VB) webmethod - GET with parameters

I've been reading a lot of questions about this error, but just can't seem to get around it (it's incredible how many questions can be found on the web on this topic!!). Let me be straight:
test.asmx
'Simple POST (obviously with parameters)
<WebMethod(EnableSession:=True)>
<ScriptMethodAttribute(ResponseFormat:=ResponseFormat.Json)>
Public Function TestarPost(ByVal Valor as String) As String
Dim x
End Function
'Simple GET - no parameters
<WebMethod(EnableSession:=True)>
<ScriptMethodAttribute(ResponseFormat:=ResponseFormat.Json, UseHttpGet:=True)>
Public Function Testar() As String
return "ok ;>D"
End Function
'GET with parameters
<WebMethod(EnableSession:=True)>
<ScriptMethodAttribute(ResponseFormat:=ResponseFormat.Json, UseHttpGet:=True)>
Public Function TestarGet(ByVal Valor as String) As String
return Valor
End Function
Trying it out in js console window:
obj = { Valor: "x" }
$.ajax({
type: "POST",
url: "test.asmx/TestarPost",
dataType: "json",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
success: function(ret) {
console.log(ret.d);
},
error: function(xhr,textStatus,errorThrown) {
console.log(xhr.status + "||" + xhr.responseText);
}
});
Success!
$.ajax({
type: "GET",
url: "ServerSide.asmx/Testar",
contentType: "application/json; charset=utf-8",
success: function(ret) {
console.log(ret.d);
},
error: function(xhr,textStatus,errorThrown) {
console.log(xhr.status + "||" + xhr.responseText);
}
});
Success! Returns correctly data in JSON format
$.ajax({
type: "GET",
url: "test.asmx/TestarGet",
dataType: "json",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
success: function(ret) {
console.log(ret.d);
},
error: function(xhr,textStatus,errorThrown) {
console.log(xhr.status + "||" + xhr.responseText);
}
});
Fails! Doing the same as in Post
The message error is "Invalid web service call, missing value for parameter: \u0027Valor\u0027." Also fails if I send object literal ("Invalide JSON primitive"). However, if I access URL .../ServerSide.asmx/TestarGet?Valor=x, it returns "opa" (maybe a clue?)
What I don't get (pardon the pun) is why, since it's the same as in POST. Maybe because the POST isn't affecting anything and I can't see the result (but it returns no errors, at least).
My goal is to create a function serverSide(asmxMethod, obj) to make a generalized bridge between client and server functions.
I've found a solution (but not an answer). According to a friend, GET doesn't accept json parameters. Unfortunately, even if I send dataType: "text" it fails.
The solution is to use always POST. POST is also able to return data (didn't know that). So with the POST example I can send and receive data in json format without a problem.

ajax call to webmethod doesn't hit success in asp.net

i have an ajax request in a page say Test.aspx
$.ajax({
type: "POST",
url: "Test.aspx/TestMethod",
data: "{ 'Parameter':'Parameter'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (res) {
alert('success');
},
error: function (xhr, ajaxOptions, thrownError) {
alert('error getting Regions');
}
});
and in the code behind
[WebMethod()]
public static string TestMethod(string Parameter)
{
return "teststring";
}
Issue is control is not going in to success inside ajax, any idea?''
Testtry this
$.ajax({
type: "POST",
url: "Test.aspx/TestMethod",
data: "{ 'Parameter':'Parameter'}",
contentType: "application/json; charset=utf-8",
success: function (res) {
var s = JSON.stringify(res);
alert(s);
},
error: function () {
alert('error getting Regions');
}
});
There are few things you need to make sure you are doing.
First thing you need to add script manager with enable page method property true like below.
<asp:ScriptManager ID="scriptManager" runat="server" EnablePageMethods="true">
</asp:ScriptManager>
See my blog post about How to call ASP.Net page method with jQuery
Check the Page URL and everything. It should be correct and should be exactly same as page name and method name as it is case sensitive.
Check parameter also. There is another good post with parameter is also below for your reference.
http://www.aspsnippets.com/Articles/Call-ASPNet-Page-Method-using-jQuery-AJAX-Example.aspx

Categories

Resources