0

I'm having issues with the following situation:

leeftijd:function(){
                var testvar = "untouched";

                var d = $('#gebdatumdd').val(),
                    m = $('#gebdatummm').val(),
                    y = $('#gebdatumjjjj').val();

                x = "none!";

                $.get("assets/incl/ageCheck.php", {y:y, m:m, d:d},
                    function(data){                 
                        console.log(data); // returns 'green';      
                        console.log(testvar);    // returns 'untouched';    
                        testvar = data; // write data in testvar;
                        console.log(testvar); // returns 'green';
                });

                console.log('outside: ' + testvar); // returns 'untouched'; 

            }

My 'testvar' just wont return the right value. Any ideas?

1
  • You need to understand the concept of callbacks in javascript and how it is used in jquery. Once you start the $.get() only thing you can be sure to run AFTER getting is the callback. You can call other stuff from there. The code in lines below $.get() is irrelevant Commented Nov 22, 2010 at 14:37

2 Answers 2

3

The ajax call is async. So that last console.log is executed before the request has finished. You have to do all processing requiring the results of the request in the callback function.

Another option would be using $.ajax with the async: false option. However, this may lock up the browser until the request has finished!

Sign up to request clarification or add additional context in comments.

Comments

1

You could either run it synchronously. I think it should be possible to wrap your $.get() call with something like this:

$.ajaxSetup({ async: false });

$.get();

$.ajaxSetup({ async: true });

A better solution would be to actually use the callback method to handle whatever you want to happen when the age check is done.

function ageCheckCallback(data) {
// Update form
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.