-3

I'm trying to write a JavaScript function that retrieves surname that corresponds to a supplied email address with no success so far. Here's my code:

function getUsername(){

var username;

$(function(){
    var dataString = 'email=' + EMAIL_ADDRESS;

    $.ajax({
        url: 'user_crud_operations.php',
        data: dataString,
        dataType: 'json',
        success: function(data){
            U = data[1];
            username = data;          
        }
    });  
 });

return username;

}

I need to use the retrieved username in another function elsewhere. Where am I going wrong?

rink.attendant.6
  • 44,500
  • 61
  • 101
  • 156
user2251344
  • 9
  • 1
  • 4
  • AJAX is asynchronous, you'll need to call a callback with your data, or use a Promise. – Interrobang Aug 26 '13 at 21:30
  • Where are you going right is more the question. Ajax will not return the data where you expect it now. You need to turn your code inside out – mplungjan Aug 26 '13 at 21:31
  • 2
    @all this question is asked a dozen times a day; bookmark "http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call" and close these as duplicates with as little fanfare as possible – user229044 Aug 26 '13 at 21:33

1 Answers1

0

Asynchronous functions (as used in AJAX) usually do not return values but instead trigger callback functions.

You must restructure your design so that "getUserName()" passes to a callback instead of returning a value. For example:

function getUsername(handler) {
  // ...
  $.ajax({
    // ...
  }).done(function(username) {
    if (handler && (typeof(handler)==='function')) {
      handler(username);
    }
  });
}

// Sample usage...
getUsername(function(username) {
  alert("OK: username=" + username);
});
maerics
  • 151,642
  • 46
  • 269
  • 291