0

I am using this code to create an array using an Ajax Post request.

$('#accountholderEmail').on('keyup',function() {
        $.ajax({
            type: "POST",
            url: "/section/get_data?getCustomer=1", 
            cache: false, 
            success: function(data){
                var email_array = data;
            }
        });
        console.log(email_array);
});

data from the Ajax request is returning an array but its telling me that email_array is not defined in the console.log(email_array);

How can i get this variable populated with the returned data from the ajax request

charlie
  • 415
  • 4
  • 35
  • 83
  • Put the `console.log()` inside the `success` function, where the value actually is. – David Jan 07 '18 at 12:19
  • email_array would have data. Its an asynchronous call and so before your POST request is completed, console logs email_array. (before you get response from your post request, email_array doesnt have any value.) Check by printing your email_array in success callback – G_S Jan 07 '18 at 12:21

1 Answers1

1

You initialize email_array in function success so want console.log it you have to push it into funciton success

$('#accountholderEmail').on('keyup',function() {
        $.ajax({
            type: "POST",
            url: "/section/get_data?getCustomer=1", 
            cache: false, 
            success: function(data){
                var email_array = data;
                console.log(email_array);
            }
        });

});
LegoBoy
  • 140
  • 5