• 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

    • many people specially intel users stick with 23h2 because for some 24h2 have degraded performance, meanwhile they took 4 years to fix ryzen performance, amd and microsoft put the work to optimize but now crippling intel. for me windows 11 it feels like a beta OS, its not stable or reliable, every patch tuesday you have to pray that they dont break something.
    • Hi all! My motherboard is Gigabyte x570 Gaming X, and believe it or not I just realised it has two M2 slots 😅 So I wanna buy a new SSD, which would mostly be used for gaming. What would you recommend I buy? Is 990 Evo Plus good choice?
    • Windows 7 its the peak of windows desktop experience, it felt polished, it was CONSISTENT, the UI was not something made to ###### people off it was more functional and productive because everything felt like a improvement. Windows 8 was horrible they did fix a little with 8.1 but the thing its that in usability it was the same as 7 you can avoid all the metro stuff, you don't need to use the cripple setting or metro stuff, for me it was bearable because it can be customized and you can make it like 7 (sure you waste time setting stuff) even if you needed a third party app. And there are serious performance improvement over 7 faster startup, Windows 10 was ok too nothing felt out of place and the start menu was usable it was filled with bloat but as usual you can remove it, what i really hated about 10 at that time it have worse windows update, you cant customize what update to install and the privacy and telemetry is horrible again it was bearable even but w11, not only they double down on things that i seriously hate on 10 like the bloat, they force changes that make no sense, make an worse start menu, worse context menu, worse task bar. force microsoft account. When i tried w10 iot enterprise LTSC on a ancient laptop, i felt that it was a throwback of what OLD windows should be a normal desktop OS with only the basics and you put the rest it was fast fluid functional, no nagging, its a productive, spend less time setting up the OS the way i want it. every windows after 7 its making it worse for me because i have to spend more time setting up
    • https://filepilot.tech/ File Pilot is a whole lot faster and offers a lot of the same features. Has a free beta available, but it looks like it's going to be a paid app in the future.
    • 24H2 was absolutely plagued with stability and compatibility problems, many of which are still not solved. You don't have to take my word for that either, given that Microsoft have an official know issues page available. Games using older versions of Easy Anti-Cheat still cause 24H2 to lock up and/or BSOD, and there's still a compatbility hold on upgrades if you have them installed as a result. Maybe 25H2 will be less of a dumpster fire, but I wouldn't count on it given Microsoft's recent track record.
  • Recent Achievements

    • Explorer
      DougQuaid went up a rank
      Explorer
    • Week One Done
      MIghty Haul earned a badge
      Week One Done
    • One Month Later
      MIghty Haul earned a badge
      One Month Later
    • Collaborator
      KD2004 earned a badge
      Collaborator
    • One Month Later
      ataho31016 earned a badge
      One Month Later
  • Popular Contributors

    1. 1
      +primortal
      593
    2. 2
      Michael Scrip
      200
    3. 3
      ATLien_0
      192
    4. 4
      +FloatingFatMan
      140
    5. 5
      Xenon
      127
  • Tell a friend

    Love Neowin? Tell a friend!