-1

Ajax get data normal, but i dont know how return varname from if statement, with inside loop, with inside function ;). How can return var username from this statement? Thanks.

    $.ajax({
         dataType: 'json',
         url: 'example.com',
         type: 'POST',
         success: function (data) {
           for (var i = 0; i < data.users.length; i++) {
             if (user_id == data.users[i].id) {

                var username = data.users[i].username;
                return username; // !!!How can return this

                    };
                };
            }
        })

console.log(username) // error: username is not defined
Shijin TR
  • 7,516
  • 10
  • 55
  • 122
McG
  • 3
  • 1

3 Answers3

1

By default, ajax will be executed asynchronously. This means that the result returned has to be handled in the callback:

$.ajax({
  dataType: 'json',
  url: 'example.com',
  type: 'POST',
  success: function (data) {
    for (var i = 0; i < data.users.length; i++) {
      if (user_id == data.users[i].id) {
        var username = data.users[i].username;
        console.log(username);
      }
    }
  }
});

ajax could be executed with the async set to false but this is usually not recommended as it will lock the UI until you get the response from the server.

The_Black_Smurf
  • 5,178
  • 14
  • 52
  • 78
0

Ajax is asynchronous. You should use a callback instead.

var callback = function(username) {
     // Do something with username here
     console.log(username);
}

 $.ajax({
         dataType: 'json',
         url: 'example.com',
         type: 'POST',
         success: function (data) {
           for (var i = 0; i < data.users.length; i++) {
             if (user_id == data.users[i].id) {

                    var username = data.users[i].username;
                    // call the callback
                    callback(username);

                    };
                };
            }
        });
Jeroen Vervaeke
  • 1,040
  • 9
  • 20
-1

Declare it as a global variable.

var username;
$.ajax({
     dataType: 'json',
     url: 'example.com',
     type: 'POST',
     success: function (data) {
       for (var i = 0; i < data.users.length; i++) {
         if (user_id == data.users[i].id) {

            username = data.users[i].username;
            return username; // !!!How can return this

                };
            };
        }
    })

 console.log(username);

Or directly send it to a function in ajax success.

Varun
  • 1,946
  • 2
  • 11
  • 17