• 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

    • Brave... the crypto browser with Brave ad rewards and Leo AI everywhere is not an issue for you and Firefox is? At least in Firefox you can disable everything you don't want easily in about:config and everything you don't want is REALLY removed even from the UI. in Brave the only way to really disable all this stuff and them to completely removed from the UI is to use administrator policies. You can only have them turned off without admin policies.
    • The UK shouldn't copy Trump. If the UK wants its own AI Industry it needs to build one, it also need to sort out the issue of startups flying away to America.
    • Azure Linux 2.0 reaches end of life, requiring AKS Arc users to upgrade by Paul Hill Microsoft has warned that Azure Linux 2.0, used in Azure Kubernetes Service (AKS) enabled by Azure Arc, will reach its end of life on July 31, 2025, necessitating users to upgrade. After this date, Microsoft will no longer provide updates, security patches, or support for Azure Linux 2.0. The longer it is used after this date, the more vulnerable systems will become due to a lack of patches. Azure Linux 3.0 brings significant upgrades to core components that enhance performance, security, and the developer experience. The Linux kernel is upgraded from version 5.15 to 6.6, bringing performance and hardware compatibility improvements. The Containerd package has been updated from version 1.6.26 to 1.7.13, improving container management. The SystemD package has been upgraded from version 250 to 255, streamlining system and service management, and OpenSSL has jumped from version 1.1.1k to 3.3.0, providing enhanced encryption and security. Azure Linux 3.0 also brings more packages and better tooling. Major versions of Azure Linux are typically supported for three years, with Azure Linux 3.0’s EOL projected for Summer 2027. It became generally available in August 2024.Microsoft said that users must migrate to Azure Linux 3.0 by upgrading their Azure Local instances to the 2507 release when it becomes available. After the Azure Local instance has been upgraded, users can then upgrade their Kubernetes clusters. Microsoft gives you the option to remain on the same Kubernetes version during this upgrade by providing the same version number on the aksarc upgrade command. After upgrading, you can verify the kernel version on your Linux nodes by adjusting the file path in this command: kubectl --kubeconfig /path/to/aks-cluster-kubeconfig get nodes -o wide This upgrade is mandatory for continued support. If you want to learn more, check out Microsoft’s announcement which also includes how to reach out to the AKS Arc team if you need to.
    • PDF-XChange Editor 10.6.1.397 by Razvan Serea PDF-XChange Editor is a comprehensive PDF editor that allows you to create, view, edit, annotate, and digitally sign PDF documents with ease. With advanced features like OCR, document security, and PDF optimization, PDF-XChange Editor is a powerful tool for both personal and professional use. Whether you need to edit text, images, or links, or add comments, stamps, or watermarks, PDF-XChange Editor provides all the necessary tools to make your PDFs look perfect. Additionally, it supports a wide range of file formats, including PDF, XPS, and DOCX, making it easy to convert and share your documents. PDF-XChange Editor key features: Edit text and images in PDF documents Add and remove pages from PDF files Annotate and markup PDFs with comments, highlights, and stamps Use OCR to convert scanned documents into searchable text Create and fill out PDF forms Sign and certify PDF documents digitally Add and edit hyperlinks within PDFs Extract text and images from PDF files Batch process multiple PDF files at once Customize the interface to your preferences Work with multiple documents in tabs Convert PDFs to other formats such as Word, Excel, and HTML Use advanced redaction tools to permanently remove sensitive information Add customizable headers and footers to PDFs Merge multiple PDF documents into a single file Split PDF documents into multiple files Add watermarks to PDF documents Use the measurement tools to calculate distances and areas in PDFs ....and much more PDF-XChange Editor 10.6.1.397 changelog: New Features Added offline support for MIP-protected documents. Bug Fixes & Improvements Fixed some security and stability issues. Click here for further information. Fixed an issue with DocuSign when a document name is very long. Fixed a very rare issue when opening password-protected files. (46285) Fixed an issue with moving content items in some cases, where arrow keys became unexpectedly deselected under certain conditions. (T# 7476) (40279) Fixed an issue with disabling the Zoom In/Out tool after using the Snapshot tool. (46330) Fixed an issue with an unintentional button press when the Autoscroll command was executed under specific conditions. (46289) Fixed an issue with resetting object selections when panning with mouse middle button. (46358) Fixed an issue with adding a highlight when starting to drag directly above the comment that is itself above base content text. (46410) Fixed an issue with adding a guideline by dragging from the ruler while a text comment or base content is being edited. (45858) Fix the call to app.clearTimeOut after the timeout handler was executed and the associated timer was unregistered. Improved static XFA support. Fixed an issue when adding Insert/Replace text markup comments to the first word in a text line. (47120) For a complete list of changes and more detailed information, please refer to the official PDF-XChange Editor Version History. Download: PDF-XChange Editor (64-bit) | Portable ~300.0 MB (Shareware) Download: PDF-XChange Editor (32-bit) | Portable ~200.0 MB Download: PDF-XChange ARM64 | 264.0 MB Download: PDF-XChange Portable @PortableApps.com | 97.0 MB View: PDF-XChange Editor Website | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
  • Recent Achievements

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

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

    Love Neowin? Tell a friend!