1

I have code like this:

var array = [];
$('#next1').on('click', function(){
    var dataString='company= '+$(this).closest('.inside').find('select').val();
    $.ajax({
        //async: false,
        type:"POST",
        url:"ajax/companyInfo.php",
        data: dataString,
        success: function(response){
            array = response.split("/");
            alert(array);
        }//end success function
    });//end ajax
console.log(array);

it alerts correct array but logs empty array, means that i can't use it after success function.
YES, i have read tons of things regarding this problem (including this: How do I return the response from an asynchronous call?) and making it synchronous solves problem (U see it's commented in code), but everyone say it's very bad to use this method. so I have two questions:

1: why it alerts correct value if case is in sync. I mean it's explained that synchronous waits for response before executing another code and asynchronous doesn't, and that's why it can't catch variables to assign to array. but if it so, how can it alert them?

2:how can i modify code to make it work?

Community
  • 1
  • 1
funny
  • 83
  • 1
  • 14
  • You cannot access your array outside of your success call without a callback. – Russell Bevan Oct 16 '14 at 19:05
  • Everything is explained in the answer you already referred to and that your question is now marked a duplicate of. If you don't understand something specific in that answer, then ask a new question about the particular aspect you don't understand. You either use the result in the success handler or you call another function from the success handler and pass the data to it. Those are your two options. It asynchronous and until you understand what that means, you will just have to believe that those are your two options. – jfriend00 Oct 16 '14 at 19:07

1 Answers1

0

Because it's asynchronous the log line will run before the success function. Anything you want to do after the array is populated must be done within the success function. Or within another function that is called from within the success function.

Andrew Ames
  • 141
  • 2
  • 10