简体   繁体   中英

Accessing value set inside onSuccess function in Prototype

I am using Ajax with Prototype library.

Here is my function that calls the Ajax function.

function Testfn()
{

    var DateExists = '';

    new Ajax.Request('testurl',{
            method: 'post',
            parameters: {param1:"A", param2:"B", param3:"C"},
            onSuccess: function(response){
            //DateExists = response.responseText;
                            DateExists = 1;
        }
        });
    // I want to access the value set in the onsuccess function here
    alert(DateExists);

}

When i alert the DateExists value i am getting null value instead of the value that is set in the onsuccess function of my Ajax call which is 1. How is that possible?

Thanks for any help.

The A in AJAX stands for Asynchronous. This means that as soon as you dispatch that Ajax request using new Ajax.Request the request is sent to the server and immediately returns control to your script. Thus, alert(DateExists) will show '' which you initially set.

To see the value of DateExists after returning from the AJAX request, you must move it inside the onSuccess() method.

Example:

function Testfn() {

    var DateExists = '';

    new Ajax.Request('testurl', {
      method: 'post',
      parameters: {param1:"A", param2:"B", param3:"C"},
      onSuccess: function(response){
        DateExists = response.responseText;
        alert(DateExists);
      }
    });
}

The onSuccess callback is executed asynchronously, when the A JAX request ends, so the alert is firing before the callback is called.

You should work with your response, inside the callback or if you want, make another function:

new Ajax.Request('testurl',{
            method: 'post',
            parameters: {param1:"A", param2:"B", param3:"C"},
            onSuccess: function(response){
                        var dateExists = response.responseText;
                        doWork(dateExists);
                        // or alert(dateExists);
                }
        });

function doWork (data) {
    alert(data);
}

CMS is exactly right. The solution is to call the javascript that needs access to DateExists from within the AJAX callback, like this:

function Testfn()
{

  var DateExists = '';

  new Ajax.Request('testurl',{
    method: 'post',
    parameters: {param1:"A", param2:"B", param3:"C"},
    onSuccess: function(response){
      //DateExists = response.responseText;
      DateExists = 1;
      doTheRestOfMyStuff(DateExists);
    }
  });
  // I want to access the value set in the onsuccess function here
  function doTheRestOfMyStuff(DateExists)
  {
    alert(DateExists);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM