ASP.Net call codebehind on $.ajax success - javascript

I have a page (default.aspx) with codebehind. The a$.ajax url is getting a response from one place, and on its success I want to call the codebehind function.
(In case I made a mistake while obfuscating the code, the $.ajax works perfectly and I get the desired response).
How is this possible?
Code I'm using:
jQuery.support.cors = true; // force cross-site scripting (as of jQuery 1.5)
$.ajax({
type: "POST",
url: URL,
data: parameters,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var resultCount = response.d
alert("*** RESULT ****" + resultFields);;
var string = StringReturn(); // the codebehind
alert(string);
},
error: function (e) {
alert("Unavailable");
}
});
Codebehind:
[WebMethod]
protected static string StringReturn()
{
return "StringReturn() success";
}
However, I'm getting error messages saying that StringReturn isn't a valid function.
Any help would be appreciated?
I've added the following lines of code to the page as advised:
<asp:ScriptManager ID="ScriptMgr" runat="server" EnablePageMethods="true"> </asp:ScriptManager>
I've also changed the code to call a javascript function on the Success event, the function being:
function HelloWorlds() {
alert("HelloWorld() method");
message = PageMethods.StringReturn();
message.toString();
alert(message);
}
however that doesn't appear to work. What am I missing?

You need to have a scripmanager on your page and then you can call it like this PageMethods.StringReturn()

Related

AJAX indicates that WEBMETHOD was successful, but it never actually triggers the webmethod on code behind

I've been through countless posts and cant figure out what I am doing wrong. I have a asp.net website with C# code behind. In it, I need for a javascript function on the .aspx page to trigger a method on the aspx.cs page. I wrote the following code:
.aspx page (my ScriptManager):
</head>
<body id="bodycontainer">
<asp:ScriptManager ID="ScriptManager2" runat="server" EnablePartialRendering="false" EnablePageMethods="true"/>
The Javascript function using ajax on the .aspx page:
function ValidateForm() {
$.ajax({
type: "POST",
url: "default.aspx/Save",
data: {},
contentType: "application/json; charset=utf=8",
// dataType: "json", // NOT NEEDED IF NO RETURN VALUE
async: true, // OPTIONAL
success: function (msg) {
alert("success");
},
error: function (msg) {
alert("failed");
}
});
}
The aspx.cs page (Code Behind page):
[WebMethod]
public static void Save()
{
// throw new DivideByZeroException(); // USED THIS TO VERIFY IF WEBMETHOD IS HIT.
_default obj = new _default();
obj.Show("Save Method Works"); // THIS IS A POPUP MESSAGE BOX
obj.btnSave_Click(); // THIS IS THE SAVE METHOD ON THIS PAGE THAT WE WANT TO RUN
}
public void btnSave_Click()
{
// METHODS CODE HERE
}
The ValidateForm function responds with "success", however, it doesn't seem like it is even triggering the WebMethod on the Code Behind page. If I use the I.E. Console Network tab, I can see the POST request. However, on the code behind method, it never triggers the breakpoints in debug (Not sure if it should according to some posts). At one point I inserted line to throw a DivideByZero exception and it never raised the exception.
So, to summarize, I get confirmation that he Javascript call to the WEBMETHOD worked by virtue of the success message and the POST message in the F12 Console Network tab. However, it doesn't seem that the WEBMETHOD ever fires. Any help would be appreciated !
You could try this to test an error instead of throwing an exception
Response.Clear();
Response.StatusCode = 500;
Response.End;
Not sure what I did, but I think adding "UseHttpGet = false" allowed it to finally execute the webmethod.
[WebMethod(EnableSession = true)]
[System.Web.Script.Services.ScriptMethod(UseHttpGet = false)]
public static void Save()
{
// throw new DivideByZeroException(); // USED THIS TO VERIFY IF WEBMETHOD IS HIT.
_default obj = new _default(); // SINCE THIS METHOD IS STATIC, WE HAVE TO INSTANTIATE AND INSTANCE OF THE DEFAULT PAGE CLASS TO ACCESS METHODS ON THIS PAGE
obj.Show("Save Method Works"); // THIS IS A POPUP MESSAGE BOX
obj.btnSave_Click(); // THIS IS THE SAVE METHOD ON THIS PAGE THAT WE WANT TO RUN
}
function ValidateForm() {
var text = "This is a Test";
$.ajax({
type: "POST",
contentType: "application/json; charset=utf=8",
data: "{}",
url: "default.aspx/Save",
dataType: "json",
success: function (msg) {
alert("success");
},
error: function (XMLHttpRequest, textStatus, errorThrown){
alert("status: " + textStatus);
alert("Error: " + XMLHttpRequest.responseText);
}
});
}

Get ServerDateTime from client side

I Have a javascript client side function to set the DateTime function.
function SetDateTime()
{
var presentDate = new Date();
}
Instead I like to get the date from server side whenever SetDateTime() function is called.
in .cs I have this method to return server time.
[System.Web.Services.WebMethod]
protected static string GetCurrentTime()
{
HiddenField hdnCurrentDateTime = new HiddenField();
hdnCurrentDateTime.Value = DateTime.Now.ToString();
return hdnCurrentDateTime.Value;
}
How to access this method from client side javascript? Thank you for your time.
using ajax call we can call webmethod like this
$.ajax({
type: "Post",
url: "pagename/GetCurrentTime",
contentType: "application/json",
dataType: "json",
success: function (data) {
alert(data);
}
}
});
As your method is static and assuming you have hdDate in your page, try this:
<asp:HiddenField ID="hdDate" runat="server"
value="<%# YourClassName.GetCurrentTime()%>" />

Ajax POST never gets triggered, neither success nor error

What I am trying to do by using AJAX is when I click "Select" Button, all the related information coming from SQL DB will be assigned to the related labels.
The problem is that the AJAX code below($.ajax) never gets triggered (neither success nor error). alert(res[0]) is showing the true result on screen (so the clientid parameter is true).
This is from a WebApplication Project in Asp.Net
function BindClientSummaryForm() {
var skillsSelect = document.getElementById('<%= ddlSFoundClients.ClientID %>');
var selectedText = skillsSelect.options[skillsSelect.selectedIndex].text;
var res = selectedText.split('-');
document.getElementById('<%= hiddenClientID.ClientID %>').value = res[0];
alert(res[0]);
$.ajax({
type: "POST",
url: "Default.aspx/GetClientSummaryData",
contentType: "application/json;charset=utf-8",
data: "{ 'clientid': " + res[0] + "}",
dataType: "json",
success: function (data) {
alert("deneme");
document.getElementById('<%= lblClientNameSurnameD.ClientID %>').innerHTML = data.d.Firstname + " " + data.d.Lastname;
document.getElementById('<%= lblDateOpenedD.ClientID %>').innerHTML = data.d.DateFileOpened;
document.getElementById('<%= lblCityD.ClientID %>').innerHTML = data.d.City;
...
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Error occured while filling ClientSummary part.");
}
});
return false;
}
<asp:Button runat="server" CssClass="btnSelect fieldButton" ID="btnSSelect" Text="Select" OnClientClick="return BindClientSummaryForm()"></asp:Button>
CodeBehind
[WebMethod]
public static MyClient GetClientSummaryData(String clientid) //GetData function
{
...
return client;
}
the debugger never drops to the GetClientSummaryData(clientid) method in c# as well.
I appreciate for your helps.
Try to change the value of content-type to text/plain on both, the client and the server, and use eval ('('+data+')') in the success function.
I know that this is not correct because the server response is json, but happened to me the same thing and I discovered (i don't know the reason) when you return the content as content-type: application/json on the server, jQuery does not call the success function.
What for do you specify POST as a request type? It seems like it will be more natural if you use GET (even method name tells us about that).
Also I'm not sure about this syntax data: "{ 'clientid': " + res[0] + "}" because I prefer to write scripts in separate files. Anyway, you can try to write data: { clientid: res[0] } instead

Appending Div after AJAX post

I'm struggling to understand why the following is occurring. I am calling a very simple webservice as shown below. For some reason, my jquery appends the div, but it vanishes immediately? Apologies for the poorly formatted thread...
Also, using jquery 1.7.1 as provided by VS2013
<WebMethod()>
Public Function GetTime() As String
Dim time As String = ""
time = Now().TimeOfDay.ToString
Return time
End Function
My AJAX below
function CallWebServiceFromJquery() {
$.ajax({
type: "POST",
url: "WebService.asmx/GetTime",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: setTime,
error: OnError
});
}
Success function
function setTime(data, status) {
//alert(data.d);
$("#time").css("visibility", "visible")
$("#time").append("<h1>" + data.d + "</h1>")
}
Lastly, the onclick
<asp:Button ID="btnCallWebService" runat="server" OnClientClick="CallWebServiceFromJquery()" Text="Call Webservice" />
The button click itself is causing a postback, hence why the appended div seems to disappear. You need to stop the default event behaviour using preventDefault():
<asp:Button OnClientClick="CallWebServiceFromJquery(event)" ...
function CallWebServiceFromJquery(e) {
e.preventDefault();
$.ajax({
// ajax settings...
});
}
Make sure CallWebServiceFromJquery returns false. Based on your description of the div appearing and disappearing, your page is doing a postback.

Pass javascript function from .Net code behind shared function or web method to page

I need to send a script to the page from WebMethod used by Ajax that fires when click HTML link. I couldn't use the script manager with "Me" or "Page" control and can't reference any controls.
I just need to return that session is nothing , Any Ideas?
The button clicked to send Ajax is HTML link and all I need to check if session expired (which I can check it on load) so if it's expired want to alert user since I already don't complete the process after checking it in code behind
<WebMethod()> _
Public Shared Function Send(ByVal data As String) As String
If Not System.Web.HttpContext.Current.Session("MemberID") Is Nothing Then
Try
''''' my code
''''''''''''''''''''''
If Not System.Web.HttpContext.Current.Session("MemberID") Is Nothing Then
Return "Success"
Else
Return "noSession"
End If
Catch ex As Exception
Return "failure"
End Try
Else
ScriptManager.RegisterStartupScript(Me, GetType(String), "Checkeng", [String].Format("LevelsMsg();"), True)
End If
End Function
JQuery Ajax
It's more complecated but I thinkk this is the main part:
$(document).on("click", "#Add", function() {
var _fulldata = $('#basket').html();
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'Order.aspx/SendOrder',
data: "{'fulldata':'" + _fulldata + "'}",
async: false,
success: function(response) {
},
error: function() {
alert("There is a problem in saving data");
}
});
});
Your WebMethodis a Shared function which is equivalent to a Static function in C#. This means you will not be able to access any variables other than those declared inside of this Shared function. However, the nature of WebMethods allow a return to "its" caller via "Success" or "error" which can be "intercepted". Thus, no need to use ScriptManager.RegisterStartupScript since your POST will return to AJAX realm anyway, which means you can call any JavaScript function there.
You could Change your code this way:
VB.NET Code-Behind:
<WebMethod()> _
Public Shared Function Send(ByVal data As String) As String
If Not System.Web.HttpContext.Current.Session("MemberID") Is Nothing Then
Try
' YOUR CODE
Return "Success"
Catch ex As Exception
Return "Failure"
End Try
Else
Return "NoSession";
End If
End Function
JavaScript:
$(document).on("click", "#Add", function() {
var _fulldata = $('#basket').html();
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'Order.aspx/SendOrder',
data: "{'fulldata':'" + _fulldata + "'}",
async: false,
success: function(response) {
/* since we put "NoSession", then we should check for it here */
if(response.d == "NoSession") {
/* This is where you "replace" the use of RegisterStartupScript
by safely calling any JS function here */
LevelsMsg();
}
},
error: function() {
alert("There is a problem in saving data");
}
});
});

Categories

Resources