最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - need to store ajax response to a global variable - Stack Overflow

programmeradmin1浏览0评论

I am using ajax to get some values from a database. In my java script file I have a global variable that some functions need to access it. I need to fill that variable from the values from the database. When I use ajax then the variable stays empty. If I use the async:false in my ajax code I get that warning message in my browser's dev tools:

jquery-3.2.1.min.js:4 [Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check /.

Moreover using the above it doesn't fill the variable resulting to errors in the other functions. Plus, from what I read this is deprecated and should not be used in any circumstances.

my code

var array ={};
var flag = 'true';
        $.ajax({
            url: "name.php",
            method: "post",
            data:{flag:JSON.stringify(flag)},
            success: function(data) {
                array = JSON.parse(data);

            },
             async: false,
            error: function(xhr, ajaxOptions, thrownError) {
            console.log(thrownError);
            }
        });

What, basically I'm trying to do, is to fill the array variable and make it an proper array.

the data from the the database is like this

{ 'something': { 'act1': 'act1a','act2': 'act2a'}, 'something2': { 'act1': 'act1a','act2': 'act2a'} }

anyone have any suggestions on how to achieve that?

PS: I need to fill a variable with the ajax response which will be accessible by other functions... not Convert a JSON Object into Javascript array...Im retrieving the data in string format

I am using ajax to get some values from a database. In my java script file I have a global variable that some functions need to access it. I need to fill that variable from the values from the database. When I use ajax then the variable stays empty. If I use the async:false in my ajax code I get that warning message in my browser's dev tools:

jquery-3.2.1.min.js:4 [Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg/.

Moreover using the above it doesn't fill the variable resulting to errors in the other functions. Plus, from what I read this is deprecated and should not be used in any circumstances.

my code

var array ={};
var flag = 'true';
        $.ajax({
            url: "name.php",
            method: "post",
            data:{flag:JSON.stringify(flag)},
            success: function(data) {
                array = JSON.parse(data);

            },
             async: false,
            error: function(xhr, ajaxOptions, thrownError) {
            console.log(thrownError);
            }
        });

What, basically I'm trying to do, is to fill the array variable and make it an proper array.

the data from the the database is like this

{ 'something': { 'act1': 'act1a','act2': 'act2a'}, 'something2': { 'act1': 'act1a','act2': 'act2a'} }

anyone have any suggestions on how to achieve that?

PS: I need to fill a variable with the ajax response which will be accessible by other functions... not Convert a JSON Object into Javascript array...Im retrieving the data in string format

Share Improve this question edited Dec 6, 2017 at 16:56 johnmmm asked Dec 6, 2017 at 16:41 johnmmmjohnmmm 1154 silver badges11 bronze badges 17
  • What do you want to fill the array variable with? Is headers_array just a typo? – Luca Kiebel Commented Dec 6, 2017 at 16:43
  • What does data look like in the success function when you debug it? – Matt Spinks Commented Dec 6, 2017 at 16:44
  • Another way to do this would be to pass the ajax promise around. If you passed the promise to the method that needs it, some time in the future, that method could attach a then() to the promise to get the value. If the promise has already resolved that then will immediately fire and perform whatever logic you want it to with the response passed in to that callback. – Taplar Commented Dec 6, 2017 at 16:45
  • 2 never use async:false... – noel293 Commented Dec 6, 2017 at 16:50
  • 2 @johnmmm that's definitely a concept you should bee familiar with. I'd advise giving learn.jquery./ajax a read. I'll put together a short example in an answer what I'm suggesting too. – Taplar Commented Dec 6, 2017 at 16:50
 |  Show 12 more ments

3 Answers 3

Reset to default 3

Based on your question and code, I think you are trying to access your array object before it is loaded with data. First of all, you will need to remove async:false. You want this to be asynchronous. That's the nature of ajax. Secondly, make sure you "do stuff" with array after the ajax call pletes. For example, this will not work:

var array ={};
var flag = 'true';
$.ajax({
    url: "name.php",
    method: "post",
    data:{flag:JSON.stringify(flag)},
    success: function(data) {
        array = JSON.parse(data);
    },
    error: function(xhr, ajaxOptions, thrownError) {
        console.log(thrownError);
    }
});
//DO STUFF WITH array here.. will not work

But this will work:

var array ={};
var flag = 'true';
$.ajax({
    url: "name.php",
    method: "post",
    data:{flag:JSON.stringify(flag)},
    success: function(data) {
        array = JSON.parse(data);
        //DO STUFF WITH array here..
    },
    error: function(xhr, ajaxOptions, thrownError) {
        console.log(thrownError);
    }
});

One more thing to consider here - It's mon practice to create a function outside your ajax success function to do something with your data (array), and call that function from inside your success function:

var array ={};
var flag = 'true';
$.ajax({
    url: "name.php",
    method: "post",
    data:{flag:JSON.stringify(flag)},
    success: function(data) {
        array = JSON.parse(data);
        doStuffWithArray(array);
    },
    error: function(xhr, ajaxOptions, thrownError) {
        console.log(thrownError);
    }
});

function doStuffWithArray(myArray) {
    //DO STUFF HERE...
}

So lets say you have an ajax call that you are making to and endpoint, whose response you may want to use at a later time, not immediately upon the success of the ajax call, for whatever reason. One way to do that is to pass around the promise/deferred that the $.ajax method returns. With this object you can attach any of the promise/deferred methods for handling the resolution or rejection of the promise. For instance:

//first we'll create a dummy deferred.  we will pretend that this is our ajax call.  in actual code this would look something like
//var dummyDeferred = $.ajax(...);
var dummyDeferred = $.Deferred();

//lets say, maybe you do want something to happen immediately upon the request success.  you can do that.
dummyDeferred.then(function(data){
  console.log("immediate then", data);
});

//now lets say that the ajax finishes, you should see the console log as you'd expect from the above then()
dummyDeferred.resolve("hello!");

//now lets say that some time later, you want to use that result inside another method to do something.  to do that you can simply attach another then() to the promise/deferred
//we'll use a timeout to simulate later usage of the promise/deferred
setTimeout(function(){
  doOtherStuff(dummyDeferred);
}, 5000);

function doOtherStuff(promise) {
  //maybe you want to take the data response and put it on the page some how.  you can!
  promise.then(function(data){
    $(document.body).append(data);
  });
}
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>

var array;
var flag = 'true';
        $.ajax({
            url: "name.php",
            method: "post",
            data:{flag:JSON.stringify(flag)},
            success: function(data) {
                array = JSON.parse(data);
                function_ThatNeeds_Thearray();

            },
             async: false,
            error: function(xhr, ajaxOptions, thrownError) {
            console.log(thrownError);
            }
        });
发布评论

评论列表(0)

  1. 暂无评论