Solved

variable scope not working

Posted on 2013-12-03
11
189 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
 
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
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Requirements JQuery 1.6+ HTML CSS Introduction This article was inspired by an EE question (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Q_28372511.html) on how to make a page show some balloons animate up a page…
In this article you'll learn how to use Ajax calls within your CodeIgniter application. To explain this, I'll illustrate how to implement a simple contact form to allow visitors to send you an email through your web site.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. 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.: (CODE)

896 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

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now