Question

Hi;

when i'm using from jQuery ajax, the page getting to freeze until request end. this is my JavaScript code:

function GetAboutContent(ID, from) {
var About = null;

if (from != true)
    from = false;

$.ajax({
    type: "POST",
    url: "./ContentLoader.asmx/GetAboutContent",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    data: JSON.stringify({ 'ID': ID, 'from': from }),
    async: true,
    success: function (msg) {
        var Result = msg.d.Result;

        if (Result == 'session') {
            warning('Your session has expired, please login again!');
            setTimeout(function () {
                window.location.href = "Login.aspx";
            }, 4000);
            return;
        }

        if (Result == 'failed' || Result == false) {
            About = false;
            return;
        }

        About = JSON.parse(msg.d.About)[0];
    }
});

return About;

}

and this is my WebService

[WebMethod(EnableSession = true)]
public object GetAboutContent(int ID, bool from = false)
{
    try
    {
        if (HttpContext.Current.Session["MahdParent"] != null ||
            HttpContext.Current.Session["MahdTeacher"] != null ||
            from)
        {
            functions = new GlobalFunctions();
            DataTable queryResult = new DataTable();

            queryResult = functions.DoReaderTextCommand("SELECT Field FROM TT WHERE  ID = " + ID);
            if (queryResult.Rows.Count != 0)
                return new { Result = true, About = JsonConvert.SerializeObject(queryResult.Rows[0].Table) };
            else
                return new { Result = false };
        }
        else
            return new { Result = "session" };
    }
    catch (Exception ex)
    {
        return new { Result = "failed", Message = ex.Message };
    }
}

How can i solve that problem? please help me

Was it helpful?

Solution

In the last line you try to return About. That cannot work due to the asynchronous nature of an AJAX request. The point at which you state return About doesn't exist any more when the success function of your AJAX request runs.

I assume you try do do somehting like this:

$('div#content').html(GetAboutContent());

In a procedural lantuage like PHP or Perl this works fine, yet JavaScript functions in a very different way. To make something like this work you'd do something like this:

$.ajax({
    type: "post",
    url: "./ContentLoader.asmx/GetAboutContent",
    dataType: "json",
    data: { 
      'ID': ID, 
      'from': from 
    },
    success: function(result) {
        $('div#content').html(result)
    }
});

The difference between the two bits of code is that the first would expect JavaScript to know the value at the time you request it. However, your function GetAboutContent() doesn't have instant access to these data. Instead it fires up an AJAX request and ends right after that with the request still in progress for an unknown amount of time.

Once the request finishes successfully the data is available to JavaScript. and you can work with it in the callback function defined for success. By then the request has absolutely no connection to the function that started it. That's why it's asynchronous.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top