• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 203
  • Last Modified:

variable scope not working

For some reason this is returning undefined when in fact the data returns properly from the database

datar should return a object but keeps returning undefined.


myData = {

get: function(postData,getURL){

     var datar=[];  

        $.ajax(
            {
                url : '/man/getdata',
                type: "GET",
                data : postData,
                success:function(data, textStatus, jqXHR)
                {
                   datar=data;


                },
                error: function(jqXHR, textStatus, errorThrown)
                {
                    datar=[];
                }


            });

        return datar;


    }

}

Open in new window

0
stargateatlantis
Asked:
stargateatlantis
  • 5
  • 3
  • 3
1 Solution
 
Hiran DesaiSolution ArchitectCommented:
Code looks fine...you need to provide more information with your code where you are consuming or can host it on fiddel so that one can better  understand it.
0
 
Chris StanyonCommented:
Without seeing your calling code it's difficult to know what's going on (are you sure you're passing in the correct arguments to the function), but what I can tell you is that datar will never be populated with your AJAX response. AJAX, by definition is Asynchronous (runs in the background) so your code continues to run while the AJAX part is called. Therefore the return datar; executes before your AJAX call has finished.

You could set you AJAX call to be synchronous!!!

$.ajax({
   async: false,
   url: '/man/getdata',
   ...

Open in new window

but bear in mind, this will lock the browser while the request is made
0
 
stargateatlantisAuthor Commented:
this is exactly what is happening.  How do I make it so that the function will return the data when called
0
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

 
Chris StanyonCommented:
I've already told you - you make the call synchronous!! Re-read my previous comment and it'll show you how to do that.
0
 
stargateatlantisAuthor Commented:
The solution to solve this is this you need to create external callback functions this function example explains it


function load_page(pagename, onSuccess, onFailure) {
        $.ajax({
            url: "/backend/index.php/frontend/pull_page/",
            type: "POST",
            data: {
                page: pagename
            },
            success: onSuccess,
            error: onFailure
        });
    }
    load_page(page, mySuccess, myFailure);

Open in new window

0
 
Chris StanyonCommented:
How is that relevant to your original question. All you're doing is wrapping one function inside another - it won't help you return a value
0
 
Hiran DesaiSolution ArchitectCommented:
As I said it should not return undefined.

Look at your code at fiddleCode of yours

It's running perfectly fine.
I guess it's because of you are trying to access it before dom gets ready
0
 
stargateatlantisAuthor Commented:
Sure but put  var datar='success'; in the success after the Ajax will not return that
0
 
Chris StanyonCommented:
@ItWorked:

It's running perfectly fine

No - it's not. You set datar=hiren at the start and this is what gets returned!!

@stargateatlantis - please listen to me and read my comments, otherwise we'll be here all day - you cannot return a value from an AJAX request - it simply impossible!!!!

You have 2 choices here - if you want to return the AJAX response from your function, then you will HAVE to make it a synchronous request. Alternatively, don't try and return a value - just manipulate the AJAX response within the success handler
0
 
Hiran DesaiSolution ArchitectCommented:
@ChrisStanyon
My first attempt was to get clerity from you that your code is working fine and it should return object or something else but should not be 'Undefined'.

Secondly, Yes the code is executing but it's not as required result.
The reason behind that is Ajax function is asynchronous. so before the response comes back from the server, the function executes and retruns 'Hiren' which i have shown in my example.

If in case you want to get value from asyncronous function then you need to have a call back function such as following.

myData =
{
    get: function(postData,getURL,myResultfunction)
        {
            var datar=[];
            $.ajax(
            {
                url : '/man/getdata',
                type: "GET",
                data : postData,
                success:function(data, textStatus, jqXHR)
                {
                   myResultfunction(data);
                },
                error: function(jqXHR, textStatus, errorThrown)
                {
                    datar=[];
                }
            });
        return datar;
    }
}

function myResultfunction(data)
{
    // some of your code to play with data...
}
0
 
Chris StanyonCommented:
@ItWorked

I said right from the start the problem was because this was an Asynchronous call!

Your code still won't work. The get() function will still return the value that was set at the start of the function - var datar=[];

You've done nothing different - you've simply moved the success handler from being inline to being an external function - it's still an AJAX call, and as I've said repeatedly - you cannot return a value from an AJAX request
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 5
  • 3
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now