1

I'm trying to get data from a php using jQuery's $.ajax method.

This is my code right now:

var ajaxresult = null;
function myFunc() {
    $.ajax('ajaxtest.php',{
    type: 'get',
    data: '',
    success: function(data) {
        ajaxresult = data;
    }
    });
    console.log(ajaxresult);
}

$('button').click(function(){
myFunc();
})

My problem is this:

The first time I call myFunc() (when I click the button) it logs null to the console, after that if I click again it returns the expected value.

What could cause this and how could I fix it to return the expected value the first time it's called?

fonorobert
  • 197
  • 1
  • 9
  • I'm suprised it returns anything at all, you've got the syntax all wrong, and it's ***asynchronous*** ! – adeneo Apr 16 '14 at 12:48
  • I'm hesitant to even mention it, but you *can* make this synchronous by setting `async: false` in the `$.ajax` options. You should almost never do this, though. – ach Apr 16 '14 at 12:58
  • possible duplicate of [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – Quentin Apr 16 '14 at 13:05

1 Answers1

4

Ajax is asynchronous, so the first time you click, the console log happens before the ajax call has completed, and it logs null.

The second time you click, the same thing happens, but the variable is global, so it now holds the value from the previous ajax call, and that's what's logged, the value from the previous call, not the value from the current call.

It should look more like this, the data is only available inside the callback

function myFunc() {
    $.ajax({
        url  : 'ajaxtest.php',
        type : 'GET',
        data : '',
        success: function(data) {
            var ajaxresult = data;
            console.log(ajaxresult);
        }
    });
}

$('button').click(myFunc);
adeneo
  • 312,895
  • 29
  • 395
  • 388