The javascript does not get value from the web method.
It says undefined for the value of s located in CallMe()..
My aim is get an object from the web method…. to use the data in js..
What am I missing_?
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Script.Services;
public partial class _Default : System.Web.UI.Page
{
Label lblGeneral;
protected void Page_Load(object sender, EventArgs e)
{
lblGeneral = textMessager;
}
[System.Web.Services.WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string ShowMessage()
{
return ExternalManager.Write();
}
}
js
// JScript File
function CallMe()
{
// call server side method
var s = PageMethods.ShowMessage();
s = eval(s);
}
(function() {
var status = true;
var fetchService = function() {
if(status){
CallMe();
status = false;
}
setTimeout(fetchService, 5000);
status = true;
}
window.onload = fetchService;
}())
****The Util Class ******
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Script.Services;
using System.Web.Script.Serialization;
/// <summary>
/// Summary description for ExternalManager
/// </summary>
public class ExternalManager
{
public ExternalManager()
{
//
// TODO: Add constructor logic here
//
}
public static string Write()
{
string s = "Okay Buddy" + DateTime.Today.ToLongDateString();
JavaScriptSerializer jss = new JavaScriptSerializer();
string serializedPerson = jss.Serialize(s);
return s;
}
}
Used Tech:
Asp.net 2.0 + Ajax Enabled
C#
It’s an AJAX call. You cannot write:
and expect to use the
svariable immediately because the call is asynchronous (it returns immediately but the result is available only later after the server responds). You need to use the callback. Here’s a full working example:Also notice that you should not use
JavaScriptSerializermanually. It is used internally byPageMethods. In yourShowMessagemethod you could also return complex objects.If the method had for example two arguments you would pass them before the success and error callbacks: