11

As my framework grows i decided to split it into files, instead of leaving it in the main design file. However by doing that the return of a function doesn't return any value.

data isn't empty - if i alert the values in the js file they are there!

The functions:

1st the function in .js file (is included before the execution)

             var lock_get = 0;
             function get_data(data, destination) 
             {

                if (lock_get == 0)
                {
                    lock_get = 1;
                    $.ajax({
                        type: "POST",
                        url: destination,
                        async: true,
                        data: data,
                        success: function(data) 
                        {
                            lock_get = 0;
                            if (data)
                            {
                                return data;
                            }
                        }
                    });
                }
             };

So and here is the execution part:

    var test = get_data(data, destination);
    notice(test);

and test is empty... I already tried different ways for writing but I guess i missunderstood the possibilities of js?

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
Ivan Schrecklich
  • 499
  • 1
  • 4
  • 16
  • 4
    @Tuscan No. [async:false is deprecated and always was a bad idea](http://api.jquery.com/jQuery.ajax/) – Denys Séguret Sep 18 '12 at 11:49
  • possible duplicate of [How to return the response from an Ajax call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – Peter O. Sep 08 '14 at 06:21

2 Answers2

10

You can't do that : as the call is asynchronous, the get_data function can't return the result of the ajax call.

What you should do is provide a callback to the get_data function and handle the result in the callback.

function get_data(data, destination, callback) 
         {

            if (lock_get == 0)
            {
                lock_get = 1;
                $.ajax({
                    type: "POST",
                    url: destination,
                    async: true,
                    data: data,
                    success: function(data) 
                    {
                        lock_get = 0;
                        if (data && callback)
                        {
                            callback(data);
                        }
                    }
                });
            }
         };

And call it like that :

get_data(data, destination, function(test){
   notice(test);
});
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
0

Alternatively you can return from synchronous AJAX call, it's generally BAD idea to use synchronous calls, but it may be useful sometimes:

http://pratyush-chandra.blogspot.com/2012/04/store-ajax-json-response-into.html

djneuron
  • 81
  • 4