Solved

variable scope not working

Posted on 2013-12-03
11
187 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 42

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 42

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
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 
LVL 42

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 42

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 42

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

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

I found this questions asking how to do this in many different forums, so I will describe here how to implement a solution using PHP and AJAX. The logical flow for the problem should be: Write an event handler for the first drop down box to get …
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
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)
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…

707 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

11 Experts available now in Live!

Get 1:1 Help Now