• 0

Populate JS Variable With Data from AJAX Request


Question

Is it possible to put some data from an AJAX Post request into a JavaScript variable?

Consider the following example:

var
myVar
= "Hello World";

alert(
myVar
);

Modifying the example above, I'd like to retrieve the text "Hello World" from a page on my server (http://localhost/text.txt).

Can I do something like, assuming I'm using jQuery:

var
myVar
;

$.post(
"/text.txt"
, function(data){

myVar
= data;

},"html");

alert(
myVar
);

15 answers to this question

Recommended Posts

  • 0

The callback you made is correct, the var'll be populated at the end of the call. If you need to process the var after it's been populated you must assure the order of execution of your code. Making the ajax request synchronous is "ugly", the best way is to make proper use of the callback functions.

But if you really want you must simply put:


$.ajaxSetup({
async:false})
[/CODE]

before the $.post.

  • 0

Try running this bit of code.

<script src="http://code.jquery.com/jquery-1.7.1.js"></script>

<script>

$(function(){

var
myVar
=
"
xxx
"
;

$.ajaxSetup({async:false});

$.post(
"./text.txt"
, function(data){

myVar
= data},
"html"

);

alert(
myVar
);

});

</script>

I see the "XXX" text in the alert, and not the content from my "text.txt" file.

The content of my "text.txt" file is as follows:

Hello World

  • 0

Yeah because the alert is shown before the $.post completed. Try this:


$.post("text.txt", function(data) {
myVar = data;
alert(myVar);
});
[/CODE]

And you'll have the alert with "Hello World" (or a connection/timeout error).

Edit:

I tried the syncronous version (with a get method and jquery 1.6.2) and it works. My simple hfs http server doesn't like post :)

  • 0
  On 30/11/2011 at 10:38, Brian Miller said:

But how do I populate that global var with the Ajax data? That's all I want.

I'm only using alert() to show the variable is populated.

Like I (and AdamLC) said your code is fine to populate the value. At the very end of the ajax request you'll have your value ("Hello World") in the global variable. I just wanted to add that IF you must do something with your value you must assure that you wait for the ajax post to complete. Your alert doesn't wait, that's why it shows "xxx"

  • 0
  On 30/11/2011 at 10:43, Killer_Z said:

Like I (and AdamLC) said your code is fine to populate the value. At the very end of the ajax request you'll have your value ("Hello World") in the global variable. I just wanted to add that IF you must do something with your value you must assure that you wait for the ajax post to complete. Your alert doesn't wait, that's why it shows "xxx"

That will only happen with Asynchronous calls correct? Meaning, it behaves that way because the processing of the rest of your code continues while it grabs the data in the background right? :)

  • 0

Yes :) , quoting from: http://api.jquery.com/jQuery.ajax/

  Quote

The first letter in Ajax stands for "asynchronous," meaning that the operation occurs in parallel and the order of completion is not guaranteed. The async option to $.ajax() defaults to true, indicating that code execution can continue after the request is made. Setting this option to false (and thus making the call no longer asynchronous) is strongly discouraged, as it can cause the browser to become unresponsive.

  • 0
  On 30/11/2011 at 10:53, winlonghorn said:

Thank you. Just checking. It is never safe to make assumptions. lol. :)

You're welcome. Javascript is quite tricky :) it is supposed to be single threaded but often there're some fun situations, that's one of the reason jquery use callback for everything (like the immediate events).

  • 0

Thanks guys. I think I see the problem. The Global Var does get populated, but in FireFox only. It doesn't on Chrome.

Here's some new code:


<script src="https://code.jquery.com/jquery-1.7.1.js"></script>
<script>
var globalVar = "xxx";

alert(
"STARTING:\n\n" +
"Global Var: " + globalVar
);

$(document).ready(function(){
$.ajaxSetup({async:false});

$.post(
'./text.txt',
function(data){
showVar(data)
},
"html"
);

function showVar(localVar){
alert(
"AFTER AJAX REQUEST:\n\n" +
"Global Var: " + globalVar + "\n" +
"Local Var: " + localVar
);
}
});
</script>
[/CODE]

Anyone want to hazard a guess why Chrome is not wanting to play nice?

  • 0

Where exactly are you assigning the results of the AJAX request to "globalVar"? I don't see such an assignment in your snippet. Also, this is not a browser issue: you're just doing it wrong.

Seriously though, you need to grasp the concept of asynchronous programming in JavaScript.

&lt;script type="text/javascript" src="https://code.jquery.com/jquery-1.7.1.js"></script>;script type="text/javascript"&gt;
$(function(){
// 1) Declare the variable
var myVar = "xxx";
// myVar === "xxx"

// 2) Fire up the AJAX request
//   This call returns immediately (hence "asynchronous")
$.post("./text.txt", function(data) {
   // 4) The request has completed and the results are retrieved
   //	 This callback gets called
   // 5) The variable gets overwritten
   myVar = data;
   // myVar === "Hello world"
   // 6) This is the point where you can do stuff
   //	 with the new data in the variable
   doStuff();
}, "html");

// 3) Continue after firing the request
//   The request is still running at this point
alert("Right after firing the request, myVar is still "+myVar);
// myVar === "xxx"
});

function doStuff() {
	alert("Now that the request has completed, the new value of myVar is "+myVar);
}
&lt;/script&gt;

Yes, you can make synchronous AJAX requests by setting "async" to false. I've never come across a need to do this: you can always use callbacks (or the new deferred object in jQuery) as the next part of your program flow.

This topic is now closed to further replies.
  • Posts

    • Chinese? It sounds extremely dangerous. I’ll reconsider buying a Meta Quest 3.
    • - What's your salary? Is it more than $100k a year? - Nah, it's $100 mil a year.
    • Compared to my ear buds which are the size of a matchbox, cover a much broader frequency range, and work everywhere without setup? Yeah, still not buying this as a replacement.
    • Meta's Superintelligence team staffed by 50% Chinese talent, 40% ex-OpenAI by Hamid Ganji Mark Zuckerberg's latest big bet at Meta involves building a team of the best AI superstars in the market to lead the so-called Superintelligence Labs. The goal of this team is to develop AI models that will ultimately lead to Artificial General Intelligence (AGI). AGI refers to an AI model with capabilities comparable to, or even beyond, those of the human brain. Achieving human-level cognitive abilities with an AI model requires substantial investments, as well as hiring the best talent to build such a system. That's why Meta is throwing hundreds of millions of dollars at AI researchers from OpenAI, Apple, and other companies to recruit them for its Superintelligence team. A user on X has now shared a spreadsheet that provides us with some unique insights into Meta's Superintelligence team and the origins of its 44 employees. The leaker claims this information comes from an anonymous Meta employee. The listing claims that 50 percent of the staff at the Superintelligence team are from China, which demonstrates the significant role of Chinese or Chinese-origin researchers in Met's AI efforts. Additionally, 75 percent of these staff hold PhDs, and 70 percent of them work as researchers. Interestingly, 40 percent of the staff are ex-OpenAI employees whom Mark Zuckerberg poached from the maker of ChatGPT. Additionally, 20 percent of Meta's Superintelligence team members come from Google DeepMind, and another 15 percent come from Scale AI, a startup that Meta recently acquired in a $15 billion deal. Another interesting point is that 75 percent of the Superintelligence team are first-generation immigrants. The leaker claims that each of these employees is now earning between $10 million and $100 million per year, although Meta still needs to confirm these substantial figures. However, it has already been reported that Meta is offering up to $100 million in signup bonuses to poach the best AI talent from OpenAI and other rivals. The revelation that half of Meta's Superintelligence team consists of Chinese nationals could trigger concerns within the Trump administration and Congress.
    • From a quick Google it seems 6GHz is optional on 802.11be. Ubiquiti has one, Unifi U7 Lite.
  • Recent Achievements

    • First Post
      nobody9 earned a badge
      First Post
    • One Month Later
      Ricky Chan earned a badge
      One Month Later
    • First Post
      leoniDAM earned a badge
      First Post
    • Reacting Well
      Ian_ earned a badge
      Reacting Well
    • One Month Later
      Ian_ earned a badge
      One Month Later
  • Popular Contributors

    1. 1
      +primortal
      505
    2. 2
      ATLien_0
      207
    3. 3
      Michael Scrip
      206
    4. 4
      Xenon
      138
    5. 5
      +FloatingFatMan
      113
  • Tell a friend

    Love Neowin? Tell a friend!