• 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

    • "Elon Musk says a kid-friendly 'Baby Grok' is on the way" No kid wants to be a baby anymore. "Kid friendly" I would have named it "Kid Grok"
    • TP-Link Tri-Band AXE5400 Wi-Fi 6E Gaming Router Archer GXE75 is just $135 by Sayan Sen If you’re juggling gaming consoles, 4K streams and a growing roster of smart devices, the TP-Link Archer GXE75 Tri-Band AXE5400 Wi-Fi 6E Gaming Router is a good option to look at right now, considering the device is currently on sale at just $135 (purchase link under the specs table below). The Archer GXE75 promises up to 5.4 Gbps of throughput across three bands: 574 Mbps on 2.4 GHz, 2402 Mbps on 5 GHz and 2402 Mbps on 6 GHz (HE160 channels enabled). A 2.5 Gbps WAN/LAN port pairs with three 1 Gbps LAN ports and a USB 3.0 port for fast file sharing or printer access (purchase link down below). The quad-core CPU and 512 MB of RAM should help to handle multiple streams without bogging down, while MU-MIMO, OFDMA and 1024-QAM improve efficiency when several devices connect simultaneously. The router’s built-in Game Accelerator engine is said to automatically prioritize gaming packets (both wired and wireless), and TP-Link’s GPN (Gamers Private Network) acceleration can reduce packet loss for supported titles. HomeShield security brings firewall protection, device quarantining and parental controls. The technical specifications of the router are given below: Specification Details Wireless Standards IEEE 802.11ax 6 GHz; IEEE 802.11ax/ac/n/a 5 GHz; IEEE 802.11ax/n/g/b 2.4 GHz Wi-Fi Speeds 6 GHz: 2402 Mbps (802.11ax); 5 GHz: 2402 Mbps (802.11ax); 2.4 GHz: 574 Mbps (802.11ax) Spatial Streams 6 streams (tri-band OFDMA/MU-MIMO) Processor 1.7 GHz 64-bit Quad-Core CPU Memory 512 MB high-speed RAM Ethernet Ports 1× 2.5 Gbps WAN/LAN; 1× 1 Gbps WAN/LAN; 3× 1 Gbps LAN USB 1× USB 3.0 SuperSpeed port (up to 10× faster than USB 2.0) Antennas 4× high-performance external antennas with Beamforming Buttons Power On/Off; Reset; WPS/Wi-Fi; LED On/Off Working Modes Router Mode; Access Point Mode Security WPA, WPA2, WPA3, WPA/WPA2-Enterprise; SPI firewall; Access Control; IP/MAC binding; Application-layer gateway; HomeShield security suite VPN OpenVPN, PPTP, L2TP (server & client); WireGuard (server & client) Software & Services IPv4/IPv6; TP-Link HomeShield; EasyMesh; Parental controls; QoS by device; WAN types (Dynamic IP, Static IP, PPPoE, PPTP, L2TP); DDNS (TP-Link, NO-IP, DynDNS); auto firmware updates Gaming Features Game QoS boost; gaming-port priority; Gamers Private Network acceleration; game-port forwarding; real-time game panel with stats & RGB control Operating Environment 0 °C – 40 °C; 10 %– 90 % non-condensing humidity Get the TP-Link Tri-Band AXE5400 Wi-Fi 6E Gaming Router Archer GXE75 at the link below: TP-Link Tri-Band AXE5400 Wi-Fi 6E Gaming Router Archer GXE75 | EasyMesh, HomeShield: $159.99 + $25 off with coupon => $134.99 (Sold and Shipped by Amazon US This Amazon deal is US-specific and not available in other regions unless specified. If you don't like it or want to look at more options, check out the Amazon US deals page here. Get Prime (SNAP), Prime Video, Audible Plus or Kindle / Music Unlimited. Free for 30 days. As an Amazon Associate, we earn from qualifying purchases.
    • Oh no... here we go again. Tha same sh*t that happaned to Mail & Calendar...
    • I too have worked with pro gear for decades and so I found the interface to be unintuitive from both the pro and casual side (a rare "accomplishment" by what are obviously otherwise skilled coders, hehe). I eventually got it to work, thanks for offering, but I found other compatibility issues with my own use case, so I just dropped it entirely. Right now, I just use an analog line out/line in approach which works as expected across all usage scenarios. With both machines on the same power block/outlet, I'm not getting any analog hum or hiss. My next step will be to try the updated Multiplicity 4 when a bug, addressing this very issue unfortunately, is resolved. Knowing Stardock, that could be tomorrow or five years from now, so I check back every few months to see it it's fixed and I want to upgrade. Again, thanks for offering to help.
  • Recent Achievements

    • Rookie
      Snake Doc went up a rank
      Rookie
    • 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
  • Popular Contributors

    1. 1
      +primortal
      495
    2. 2
      Michael Scrip
      203
    3. 3
      ATLien_0
      197
    4. 4
      Xenon
      137
    5. 5
      +FloatingFatMan
      116
  • Tell a friend

    Love Neowin? Tell a friend!