0

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

Rasool Ghafari
  • 4,128
  • 7
  • 44
  • 71
  • you ***CAN NOT*** return the result from an **asynchronous** function – adeneo Apr 23 '14 at 19:45
  • possible duplicate of [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – adeneo Apr 23 '14 at 19:45
  • Did you mean i should set `async` to `false` – Rasool Ghafari Apr 23 '14 at 19:46
  • 1
    No, I did not mean that, and you should under no circumstances do that, read the link posted above instead. – adeneo Apr 23 '14 at 19:53
  • You don't need JSON.stringify there you can pass in the object. You shouldn't need JSON.parse either if you have a datatype not sure what you have there in About though. – Wilmer Apr 23 '14 at 20:08

1 Answers1

1

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.

anno1337
  • 117
  • 10