0

I have a scrolling text in JavaScript that has some variables in it. I get the variables through a PHP script and then print them on the scrolling text. The problem is (I think) that the script doesn't have the time to get the variables before the page finishes loading so I get my variables become = 'undefined'. But if after the phpscript but before populating the scroller I call an alert();, after I click 'ok' the scroller is populated with the right information on the variables.

How can I make the code wait for the variables to be populated and then load the page?

Code:

var test;

$.ajax({ url: 'getSlaTCO.php', success: function (data) { test = data } });

var memorycontent = test;

function populatescroller() {(...)}

The way it gets correctly populated:

var test;

$.ajax({ url: 'getSlaTCO.php', success: function (data) { test = data } });

alert('hey there!');

var memorycontent = test;

function populatescroller() {(...)}
1
  • AJAX ( Asynchronous JavaScript and XML ) :=) Commented Nov 19, 2013 at 17:00

5 Answers 5

0

Just do all the stuff you need in the ajax success callback, thats why its there :)

$.ajax({ url: 'getSlaTCO.php', success: function (data) { 
    test = data;
    alert('hey there!');

    var memorycontent = test;

    populatescroller();

    } });
0
0

call the scroller function within the success function of the ajax call. that way it doesn't start until a successful ajax call.

0

Call populatescroller in the ajax callback function. You're guaranteed to have your data then.

By inserting the alert statement you're messing with the timing which (incidentally) causes it to work.

0

Your $.ajax call is asynchronous, so everything else is loading around it while it's doing it's thing. You should show the scroller in your success function callback. So start with making sure the div/span/p (whatever the scroller is) is hidden (set to display:none). Then:

$.ajax({ url: 'getSlaTCO.php', success: function (data) {
  populatescroller(data);
  $('#scroller').show();
}});

Without seeing your markup or whats inside the populatescroller function, that's the best example I can give.

0

All your answers worked but I found a better solution. In the ajax code just set the async value to false:

$.ajax({
    url: 'getSlaTCO.php',
    async: false,
    success: function (data) {
        valSlaTco = data;
    }
});

That did it!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.