-3

I have a question about $.ajax in javascript:

If I have a function like this:

var jQueryFunction = function()
{
   var array = new Array();       
   ...

   $.ajax ({
       type: "GET",
       async: false,
       url: TPS_URL_1,
       dataType: "jsonp",
       jsonp: "callback",
       jsonpCallback: "tpsHandler",
       success: function(json)
       {
          array[0] = 1;
          array[1] = 2;
       }
   });

}

After that when I check array value, it isn't set by anything and still null.

However I do like this:

var jQueryFunction = function()
{
   var array = new Array(); 
       array[0] = 1;
       array[1] = 2;      
   ...

   $.ajax ({
       ...

   });

}

It works fine.

So why I cannot set value for array inside $.ajax?

user2597504
  • 1,503
  • 3
  • 23
  • 32
  • 2
    ajax is asynchronous, maybe when you check the array the callback hasn't been called yet – pNre Oct 02 '13 at 18:20
  • 1
    Show your complete `ajax` function, it's not clear what you are trying to do and what is going on. – The Alpha Oct 02 '13 at 18:22
  • You can set your array inside the AJAX call. What's important is when you set the value and when you try to access the value. Which you haven't explicitly shown in your example. Can you provide a complete *working* example which demonstrates the problem? – David Oct 02 '13 at 18:24

2 Answers2

1

The line $.ajax({...}) is the equivalent of

var obj = {...};
$.ajax(obj);

The statement array[0] = 1 is not something that can be placed inside a object declaration like that (ie the code var obj = {array[0]=1} is not valid), thus the code you've posted is invalid (it throws a SyntaxError)

If you want to set these array elements AFTER the ajax returns, you should use the success callback:

$.ajax({url: ...,
    success: function(returnData) {
        array[0] = 1;
    }
});
  • Yes. array[0] = 1 is in success:function(returnData){array[0] = 1}, but it doesn't work – user2597504 Oct 02 '13 at 18:27
  • Bear in mind that ajax is asynchronous. Have you verified that the ajax call has actually returned before checking array values? Are you sure your ajax call is actually succeeding? –  Oct 02 '13 at 18:28
-1

Try with:

Simple:

var setup = {
    url         :   'index.php',
    dataType    :   "json",
    type        :   "post",
    data        :   {
        time        :   "now"
    },
    success     :   function(response)
    {
        console.log( response ) ;
    }
};
$.ajax( setup );

API( ajaxSetup ):

$.ajaxSetup({
    url         :   'index.php',
    dataType    :   "json",
    type        :   "post",
    success     :   function(response)
    {
        console.log( response ) ;
    }
});

$.ajax({
    data:{
        time    :   "now"
    }
});
Olaf Erlandsen
  • 5,817
  • 9
  • 41
  • 73