Having problems with JQuery function in asp.net? - javascript

I have written a jQuery function which calls a c# method.
If the function returns a success then it calls another method from the c# code which is responsible for incrementing the counter variable in my c# class.
I wanted to do automatic counter increment every 1 minute and this is what I noticed. I set up a breakpoint in my Counter() function in my c# class. As the page loads up and the Counter method is called, I proceed with my debugging and notice that things work fine but once the counter variable reaches the value "2", when I press F10 to step into my Counter method(), it doesn't reach the end of the method and increments the counter variable by 2 and then from here on things get worse.
I wonder what could I be doing wrong? Can anyone review my script and give me suggestions on what could be causing the error?
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Dtata.aspx.cs" Inherits="Dtata" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="/scripts/jquery-3.1.1.min.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<script type="text/javascript">
klm();
function klm() {
$.ajax({
type: "POST",
url: "Dtata.aspx/Hello",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{ 'name' : 'hello' }",
success: function(result) {
console.log(result.d);
Counter() //<-- CALL OTHER AJAX METHOD TO INCREASE COUNTER ON BACK END
},
error: function(result) {
alert(result.responseText);
}
});
}
function Counter() {
$.ajax({
type: "POST",
url: "Dtata.aspx/Counter",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result) {
console.log(result.d);
},
error: function(result) {
alert(result.responseText);
}
});
setInterval(Counter, 60000);
}
</script>
</form>
</body>
</html
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Dtata: System.Web.UI.Page {
public static int counter = 0;
protected void Page_Load(object sender, EventArgs e) {
}
[WebMethod]
public static string Hello(string name) {
return name;
}
[WebMethod]
public static int Counter() {
counter = counter + 1;
Console.WriteLine("I have been called" + counter);
return counter;
}
}

One thing. You call counter in klm and also in setInterval.
If you want to loop an AJAX function, instead do this:
function Counter() {
$.ajax({
type: "POST",
url: "Dtata.aspx/Counter",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result) {
console.log(result.d);
setTimeout(Counter,60000); // call again if ok - or in .done
},
error: function(result) {
alert(result.responseText);
}
});
}
Another thing - I would expect your C# to read and write the counter to a DB and I do not see the C# return any JSON with a { d:counter}

Related

Calling a C# method from .js file

I have a aspx page and in that i have method UpdateScreenAlertStatus();
I want to have a file called dtml.js and in that i have function openmodelpopup().
I want to call UpdateScreenAlertStatus(); in javscript method openmodelpopup().
function MyMethod() {
$.ajax({
type: "POST",
url: "abc.aspx/UpdateScreenAlertStatus ",
contentType: "application/json; charset=utf-8",
dataType: "json"
});
}
Call the above ajax in your js function openmodelpopup().
[WebMethod]
public static void UpdateScreenAlertStatus()
{....}
Make it a web method
[WebMethod]
public static string UpdateScreenAlertStatus()
{....}
Refer this MSDN article.
From javascript you can access this as YourPage.aspx/UpdateScreenAlertStatus or through PageMethods in same aspx page. You can call this with the following javascript.
function openmodelpopup() {
$.ajax
({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "YourPage.aspx/UpdateScreenAlertStatus",
success: (function (data) {
$("#statusDiv").text(data.d);
$("#statusDiv").show();
}),
error: (function () {
alert("Error occurred in server!");
})
});
}
I'm assuming here, 1. your C# method is static and marked WebMethod. 2. Code is compiled properly. 3. You are using jQuery. 4. The url in javascript is correct. 5. Your C# method returns a string status. 6. You are trying to update html element statusDiv with that string.

Jquery ajax not calling server side function

I have solution structure as:
I want to call recommendationProcess function from CTL_RateRecommendationDetails.ascx.cs from
CTL_RateRecommendationDetails.ascx
So i written code as:
$.ajax({
type: "POST",
url: "/UserControls/CTL_RateRecommendationDetails.ascx/recommendationProcess",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(value) {
alert(value.d);
},
error: function(e) {
alert("Ajax Error" + JSON.stringify(e));
}
});
But every time it comes in error block.
I have tried with :
url: "/CTL_RateRecommendationDetails.ascx/recommendationProcess",
And
url: "CTL_RateRecommendationDetails.ascx/recommendationProcess",
But its not calling function.
[System.Web.Services.WebMethod]
public static void recommendationProcess()
{
}
You can't call code behinds of user controls from JQuery Ajax
Ref : http://forums.asp.net/t/1423555.aspx
Using jQuery AJAX to call ASP.NET function in control code-behind instead of page code-behind
how-to-access-server-side-method-in-ascx-control-using-jquery-ajax-method

Passing a string from code behind to ajax

I am accessing a method on the server side. The only problem is that I don't have alot of experience in AJAx. I am unable to retrieve the returned string in the ajax from the .cs method
$.ajax({
type: 'GET',
url: '/frmGpsMap.aspx?name=load',
dataType: 'text',
success: function(data) {
alert(data.d);
}
});
protected void Page_Load(object sender, EventArgs e)
{
string crrName = Request.QueryString["name"];
if (!String.IsNullOrEmpty(crrName))
{
if (crrName.ToLower().Equals("load"))
{
string fh= loadKMLFileToString();
hdnUsername.Value = fh;
}
}
}
public string loadKMLFileToString()
{
return "hello world";
}
The alert is returning the html of the page. I want to display the "Hello World" string
To get the code behind method to work with ajax you need to use System.Web.Services.WebMethod. By default you need to use POST unless you specify HTTP GET attribute in code behind
[System.Web.Services.WebMethod]
public static string LoadKMLFileToString()
{
return "Hello World";
}
Here is the ajax method for call
$.ajax({
type: "POST",
url: "frmGpsMap.aspx/LoadKMLFileToString",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
alert(response.d),
failure: function(response) {
alert(response.d);
}
});
I hope it helps.
More examples: http://weblogs.asp.net/karan/calling-server-side-method-using-jquery-ajax
I think you can decorate your cs method with the WebMethod attribute and call it directly from ajax. Like this:
$.ajax({
...
url: '/frmGpsMap.aspx?loadKMLFileToString',
...
});
[System.Web.Services.WebMethod]
public string loadKMLFileToString()
{
return "hello world";
}
Cheers! =)

How to call this.Page (server page) from javascript

I have methos to display content of page at server side like
DisplayDetails(Page PageNema)
{
///
}
How can i call this function from javascript as well as how can i pass Page argument from Javascript
If it's WebForm you must set this method as WebMethod, so then you can call this method from jQuery. Something like that:
Client Side.
$.ajax({
type: "POST",
url: "PageName.aspx/MethodName",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something interesting here.
}
});
Server side:
public partial class _Default : Page
{
[WebMethod]
public static string DisplayDetails()
{
//your code to retrieve details here
return Details;
}
}
[WebMethod]
public static string DisplayDetails(parameter1,parameter2,etc...)
{
return something;
}
Client side code
<script type="text/javascript">
function functionName(callback) {
$.ajax({
type: "POST",
url: 'PageName.aspx/DisplayDetails',// your function name
data: '{"argument1","argument2",etc...}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
// If u want something from serverside function then write your code here
},
error: function (e) {
}
});
}
</script >

AJax Internal Server Error 500

I have a page method issue I have this page method on a ASP.net webform
[WebMethod(true)]
public static int GetInt(int id){
return 10;
}
and I call it from JQuery like this
$.ajax({
type: "POST",
url: "webforms.aspx/GetInt",
data: "{id:'1'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
},
error: function (err) {
}
});
This all works just fine, when I put a break point on the server side it hits, but for some odd reason I after the PageMethod returns, I get the error call back of the ajax call never success! Any ideas.
I cant use a script manager on this one! I open to any cross browser solution!.
I used your code and am having no issues. Here is my exact code:
WebForm1.aspx
<head runat="server">
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
<script>
$.ajax({
type: "POST",
url: "/WebForm1.aspx/GetInt",
data: "{id:'1'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert("SUCCESS: " + msg.d);
},
error: function (err) {
alert("FAILURE");
}
});
</script>
</body>
</html>
WebForm1.aspx.cs
using System.Web.Services;
namespace WebApplication3
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod(true)]
public static int GetInt(int id)
{
return 10;
}
}
}

Categories