1

I have this code

function(config) {
  items=[];
  Ext.Ajax.request({
    url : 'url',
    success : function(resp) {
      items = [a,b]
    }
  });
  console.log(items);
  return items;
},

I want the items array to be available in main function but its coming empty.

Alberto Zaccagni
  • 30,779
  • 11
  • 72
  • 106
user26
  • 3,937
  • 5
  • 22
  • 22

1 Answers1

0

Even though this has been answered countless of times, I'll show you a quick example on what you need to do. In short, you can't access data recieved by an ajax call outside of the success handler. You'll need a callback:

function ajaxStuff(config, cb) {
        Ext.Ajax.request({
            url : 'url',
            success : cb
        });
}

var config = {};

ajaxStuff(config, function(resp){
   //handle the ajax response here
});

http://jsfiddle.net/Yrd7r/

Johan
  • 35,120
  • 54
  • 178
  • 293
  • Please add some explanation. For someone who doesn't understand async, this doesn't explain why it needs to be done this way. – jfriend00 Sep 16 '13 at 07:41
  • @jfriend00 I wasn't finished :) If he want's a more detailed explanation, there are hundreds of other SO threads answering this very question. – Johan Sep 16 '13 at 07:42
  • i cant understand ur example. can u just give example from my mycode. what is cb in ur code and what will be its content – user26 Sep 16 '13 at 07:48
  • @user26 If you want an example with your code you need to give me some more context. Show me more of your code. – Johan Sep 16 '13 at 07:51
  • This is my code http://pastebin.com/VNV4Mk50 – user26 Sep 16 '13 at 07:54
  • @user26 http://jsfiddle.net/Yrd7r/ – Johan Sep 16 '13 at 07:58
  • Thanks for that but in which function do i need to put return in callback or main function get items . i want to return items when i call obj.getitems but how can callback pass items to get_items – user26 Sep 16 '13 at 08:12
  • @user26 You don't use a return statement, you use the callback like in the demo. – Johan Sep 16 '13 at 08:16
  • I need to get the items from that function and then pass somewhere else. is it possible – user26 Sep 16 '13 at 08:17
  • @user26 Sure. Again, handle it withing the callback. – Johan Sep 16 '13 at 08:23