How can I fix the script below so that it will work EVERY TIME! Sometimes it works and sometimes it doesn\'t. Pro JQuery explains what causes this, but it doesn\'t
Here's your issue: You've got a script tag in the body, which is asking for the AJAX data. Even if you were asking it to write the data to your shell, and not just spout it... ...that's your #1 issue.
Here's why:
AJAX is asynchronous. Okay, we know that already, but what does that mean?
Well, it means that it's going to go to the server and ask for the file. The server is going to go looking, and send it back. Then your computer is going to download the contents. When the contents are 100% downloaded, they'll be available to use.
...thing is...
Your program isn't waiting for that to happen. It's telling the server to take its time, and in the meantime it's going to keep doing what it's doing, and it's not going to think about the contents again, until it gets a call from the server.
Well, browsers are really freakin' fast when it comes to rendering HTML. Servers are really freakin' fast at serving static (plain-text/img/css/js) files, too.
So now you're in a race. Which will happen first? Will the server call back with the text, or will the browser hit the script tag that asks for the file contents?
Whichever one wins on that refresh is the one that will happen.
So how do you get around that? Callbacks.
Callbacks are a different way of thinking. In JavaScript, you perform a callback by giving the AJAX call a function to use, when the download is complete.
It'd be like calling somebody from a work-line, and saying: dial THIS extension to reach me, when you have an answer for me.
In jQuery, you'll use a parameter called "success" in the AJAX call.
Make success : function (data) { doSomething(data); } a part of that object that you're passing into the AJAX call.
When the file downloads, as soon as it downloads, jQuery will pass the results into the success function you gave it, which will do whatever it's made to do, or call whatever functions it was made to call.
Give it a try. It sure beats racing to see which downloads first.