0

I am attempting to use JSON to return an array that I can manipulate and use later, but, something is going wrong when I use AJAX to return a JSON encoded string. I am currently using alerts as a method of debugging, and my alerts appear to fire in the wrong order.

Scripts:

<script type="text/javascript"> 
    jQuery(document).on('change', '#ProductNumbers', function()
    {
        selectedIndex = $('#ProductNumbers').prop('selectedIndex');

        var productNumber = $('#ProductNumbers').val();

        var jArray = getCategories( productNumber );
        alert( jArray );
    }); 
</script>

<script type="text/javascript">
    function getCategories( productNumber )
    {
        $.ajax({                                                          
              url: '/php/DBManager/GetCategories.php',         
              data: {
                        ProductNumber: productNumber
                    },

              success: function(result) 
              {
                  alert( result );
                  return result;
              }
            });
    }
</script>

The first script calls the second, but the line alert( jArray ); alerts as undefined, and then i get the alert( result ); from the second script, which returns what it should.

Any ideas?

PugsOverDrugs
  • 515
  • 1
  • 4
  • 14

1 Answers1

2

It will be undefined as ajax call is asynchronous and first script code gets executed before the completion of ajax call.

So your alert of first script will get fired before the one in the second script.

You have to use the object returned by ajax call in the success function to do any operation on it.

Anything which requires the data from the ajax call must be done after it's completed. To do this put it in the success function of the call.

For Example:

        $.ajax({                                                          
              url: '/php/DBManager/GetCategories.php',         
              data: {
                        ProductNumber: productNumber
                    },

              success: function(result) 
              {
                  //use returned result data like this
                  SomeFunction(result);
              }
            });


function SomeFunction(data)
{

// do any operation here
}
BenMorel
  • 34,448
  • 50
  • 182
  • 322
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
  • Just to expand anything which requires the data from the ajax call must be done after it's completed. To do this put it in the success function of the call. – Liath May 28 '14 at 14:44