1

I need to fill my array with info when I drag item to cart zone sow in drag even ti put this function

var ProductInfo=new Array();
myGlobalArray=GetProductById(iProductId);

that call this Ajax function

function GetProductById(iProductId)
{   
var ProductInfo=new Array();
        console.log("2");
    $.ajax({
                    type: 'POST',
                    url: 'services/ManageCategoriesServices.asmx/GetProductById',
                    dataType: 'xml',
                    'data': {'iProductId': iProductId },
                    success: function(data) {

                                        source = null;
                                        try 
                                        {    
                                            console.log("source product-> ",data.activeElement.childNodes);
                                            myGlobalArray=TestProduct(data.activeElement.childNodes);

console.log("In Ajax myGlobalArray-> ",myGlobalArray);                                          return myGlobalArray;
                                         }
                                        catch(e) {
                                            $('#m_lblStatus').text('failed to read json');
                                        }
                                },

                    fail: function() { $('#m_lblStatus').text('fail');}     

            });

                return myGlobalArray;

}

I checked that my myGlobalArray get the full info that I need but when I go back to my first function when I trying to copy arrays

myGlobalArray=GetProductById(iProductId);

it empty and it says

There are no child objects

I used global array because the usual won't work so I thought the global will work but no in ajax I see it full but in the first function it comes empty.

In Ajax myGlobalArray-> ["medium_101-01-004-02.jpg", "303", "101-01-004-02", "44.95"]


After Ajax  myGlobalArray-->[] There are no child objects

Where is the problem?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Vladimir Potapov
  • 2,347
  • 7
  • 44
  • 71

1 Answers1

2

AJAX is means "Asynchronous Javascript and XML". Asynchronous is the key word in this situation. The problem is: return runs before your request is finished. Solution: you can use myGlobalArray variable in onSuccess event handler or use ajax with async == false option, like this:

$.ajax({
  ...,
  async: false,
  ...,
});
Valdemar_Rudolfovich
  • 3,021
  • 2
  • 18
  • 17
  • Note that setting `async: false` is *not* a recommended solution because it will inevitably [lead to other problems](http://stackoverflow.com/questions/17146392/function-in-javascript-take-to-maucu-time-and-this-stop-the-scipt). – JJJ Jun 17 '13 at 11:36
  • Hmm... I used it a few times, but do not get this troubles, but I be careful in future, thanks for advice. – Valdemar_Rudolfovich Jun 17 '13 at 16:37