Solved

variable scope not working

Posted on 2013-12-03
11
193 Views
Last Modified: 2013-12-04
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
Comment
Question by:stargateatlantis
  • 5
  • 3
  • 3
11 Comments
 
LVL 4

Expert Comment

by:ItWorked
ID: 39694623
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
 
LVL 43

Expert Comment

by:Chris Stanyon
ID: 39694977
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
 

Author Comment

by:stargateatlantis
ID: 39695214
this is exactly what is happening.  How do I make it so that the function will return the data when called
0
Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

 
LVL 43

Expert Comment

by:Chris Stanyon
ID: 39695250
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
 

Author Comment

by:stargateatlantis
ID: 39695328
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
 
LVL 43

Expert Comment

by:Chris Stanyon
ID: 39695352
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
 
LVL 4

Expert Comment

by:ItWorked
ID: 39695359
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
 

Author Comment

by:stargateatlantis
ID: 39695367
Sure but put  var datar='success'; in the success after the Ajax will not return that
0
 
LVL 43

Accepted Solution

by:
Chris Stanyon earned 500 total points
ID: 39695378
@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
 
LVL 4

Expert Comment

by:ItWorked
ID: 39695658
@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
 
LVL 43

Expert Comment

by:Chris Stanyon
ID: 39695693
@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

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

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

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
jQuery - Add confirm message to button? 2 20
jQuery on Submit 4 43
jQuery Toggle & Anchor Links 5 43
ASP.NET Content Page 3 30
PROBLEM: The other day I was working on adding an ajax request to a webpage that already had a dialog box on the page.  The dialog box was using relative positioning to be positioned next to a form field I had on the page.  Everything was working…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

829 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question