Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

variable scope not working

Posted on 2013-12-03
11
Medium Priority
?
198 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:Hiran Desai
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 44

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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 44

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 44

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:Hiran Desai
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 44

Accepted Solution

by:
Chris Stanyon earned 2000 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:Hiran Desai
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 44

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

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

Question has a verified solution.

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

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.
Originally, this post was published on Monitis Blog, you can check it here . In business circles, we sometimes hear that today is the “age of the customer.” And so it is. Thanks to the enormous advances over the past few years in consumer techno…
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)
Suggested Courses

927 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