-1

functions.js

function clients(id){
    var result = '';
    $.ajax({
        type: "GET",
        url: "classes/response.php?type=clients",
        data: {id: id},
        success: function(data){
            result = data;
            console.log(result); // retrieves 'John'
            console.log(data);   // retrieves 'John'
        }
    });
    return result;
}

And in my other file main.js

$("#client_check").on('click', function(){

     var input = $("#client_id");
     var name  = clients(input.val());

     console.log(name); // retrieves empty

     $("#client_id").val('');

});

Shouldn't this work? The function output the value perfectly, but when I call the function to a variable it retrieves empty.

What am I doing wrong?

user3243925
  • 271
  • 2
  • 4
  • 12

2 Answers2

0

Try this, My changes only callback function rest is as per OP

function clients(id,callBack){
    $.ajax({
        type: "GET",
        url: "classes/response.php?type=clients",
        data: {id: id},
        success: function(data){
            result = data;
            console.log(result); // retrieves 'John'
            console.log(data);   // retrieves 'John'
            callBack(data);
        }
    });
}


$("#client_check").on('click', function(){

     var input = $("#client_id");
     clients(input.val(),function(name){
        console.log(name);
     });
     $("#client_id").val('');

});
Amit
  • 15,217
  • 8
  • 46
  • 68
-1

Solved according to: How do I return the response from an asynchronous call?

function clients(id){
    return 
      $.ajax({
          type: "GET",
          url: "classes/response.php?type=clients",
          data: {id: id},
      });
}
// And to call it:
clients(input.val()).done(function(r){
    console.log(r);
});
Community
  • 1
  • 1
user3243925
  • 271
  • 2
  • 4
  • 12