Adam Bausy
Adam Bausy

Reputation: 35

$.get and get value

 function get(){
      $.get('/get.php', function(data) {
          alert('one: ' + data)
          return data;
      });
  }

  var test = get();
  alert('two:' + test);

In get.php is:

<?php echo "number"; ?>

why one alert show me one: number

but two alert show me two: undefined

How can i get this value outside function?

Upvotes: 1

Views: 172

Answers (3)

Didier Ghys
Didier Ghys

Reputation: 30666

This is because when this statement is called, the function get() has already returned before the callback of $.get() has been executed. Keep in mind that ajax requests are asynchronous.

What are the execution steps:

  1. Call get()
  2. Ajax request with $.get() is initiated
  3. get() returns
  4. ajax request ends and callback of $.get() is executed

To handle this case, you would typically pass the callback to execute as a parameter:

function get(callback) {
    $.get('/get.php', function(data) {
        if ($.isFunction(callback)) {
            callback(data);
        }
    });
}

Upvotes: 1

psx
psx

Reputation: 4048

Your return data is returning from the ajax anonymous function, not from the get() function.

Upvotes: 1

Linus Thiel
Linus Thiel

Reputation: 39223

The $.get call is asynchronous. That means that you pass it a callback (your function(data) { ... }, which gets executed with the result from the call. You can't return from inside that callback - when it is executed, your outer function (doing the $.get) has already returned. Instead, try something like this:

// callback will be executed with the response from your GET request
function get(callback){
    $.get('/get.php', callback);
}

// Call get with a callback receiving the response
get(function(data) {
    alert('two:' + data);
});

This is a pattern you will have to get used to when writing javascript code.

Upvotes: 7

Related Questions