0

I want to get data from another page using AJAX. I also want to wrap this AJAX call into my "user defined function".

But I can not write like this:

 function func(){
      var tmp;
      $.ajax({
          url: 'url',
          type: "POST",
          dataType: "json",

          success: function (data) {
            tmp=data;
          }
     });

     return tmp;
}

because AJAX is asynchronous and this code returns - "undefined".

When AJAX async param set to false

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

possible do the trick.

I also can create some global variables and write like this:

function setMyVariable(){
        $.ajax({
          ...
          success: function (data) {
            myGlobalVariable=data;
          }
        });
}

The question is - Is it good practice to use global variables in this case?
Or it is completely wrong and I need search something else

Dmitry Novice
  • 155
  • 2
  • 12
  • Well, as you can see in your first example, it sometimes won't work and yield `undefined`. So it's definitely a **bad practice**. – Bergi Mar 14 '15 at 22:53
  • have you read [how to return the response from an asynchronous call?](http://stackoverflow.com/q/14220321/1048572) already? – Bergi Mar 14 '15 at 22:55
  • you should not use globals or sync ajax, use callbacks and async techniques. – dandavis Mar 14 '15 at 23:30

1 Answers1

0

The best practice would be to return the promise from $.ajax:

function func(){
      var tmp;
      return $.ajax({
          url: 'url',
          type: "POST",
          dataType: "json",
     });
}

Then you can do function().done(function(result) { ... } );

TheDude
  • 3,796
  • 2
  • 28
  • 51