Kurt Bourbaki
Kurt Bourbaki

Reputation: 12596

Access jQuery variable outside its function

I need to use a variable outside its function. I already read older questions, but I still can't find a proper solution.

Here's the code:

<script>

var warehouseAddress;

$(document).ready(function(){

$.ajax({
    type:"POST",
    url:"${pageContext.request.contextPath}/users/findWarehouseAddress",  
    success:function(data){
        warehouseAddress = data;
    }
}); 

alert(warehouseAddress);

});

var warehouse = warehouseAddress;

</script>

The alert gives me "undefined". I need to get that variable not only inside the alert, but also inside the other "warehouse" value that is outside the ready function.

Sorry if it's a duplicate, but as I said I couldn't make it with the answers I read.

EDIT: For the sake of completeness I describe the details, replacing the alerts with the read functions I have to call.

As I said in comments, I'm actually using Google Maps APIs and their functions. What I have to do is passing the variable outside the $(document).ready function, because I need to use it in an external script.

The problem is that the external js function that I have to call is a Google Maps function (initialize()) that loads as the window loads, so I have to find a way to call that function after the $ready function.

Upvotes: 0

Views: 2363

Answers (3)

Kurt Bourbaki
Kurt Bourbaki

Reputation: 12596

Here's the solution I found thanks to @milkshake and other kind users comments.

First of all, I put all my Google Maps scripts in an external .js file. I needed to do so for code readability.

In that file, I simply used the Google Api's addDomListener function to load what I needed at the right time, to avoid timing errors between ajax calls and methods executions.

google.maps.event.addDomListener(window, 'load', function(){

    $.ajax({
        type:"POST",
        url:contextPath+"/products/findWarehouseAddress",  
        success:function(data){
                    warehouseAddress = data;
                    geocoder.geocode({'address': warehouseAddress }, function(results) {
                        warehouse = results[0].geometry.location;
                        initialize();
                    });
        }
    });
});

So the timing is something like this:

  1. Google Listener;
  2. Ajax call returns the warehouse address;
  3. When I get the warehouse address, I store it in warehouseAddress variable and I geocode it (extracting coordinates from the address String);
  4. I call Google Maps initialize function, so that my variables can be used by it.

It works. But there could be better ways to do that, so I'll be glad to read your comments if you've got better solutions :)

Upvotes: 0

Jake Aitchison
Jake Aitchison

Reputation: 1099

as @putvande already said ajax is asynchronous, so the best thing to do here is take advantage of callbacks ( event based :D )

$.ajax({
    type:"POST",
    url:"${pageContext.request.contextPath}/users/findWarehouseLat",  
    success: myDataHandler(data)
}); 

function myDataHandler(data){
    warehouseLat = data;
    //do something with the data here :D as it now exists
    alert(warehouseLat);
}

Have a look at this: custom events in jquery

Upvotes: 2

Suresh Atta
Suresh Atta

Reputation: 121998

That is what asynchronous means.

Before completing the ajax request,you are alerting your warehouseLat.

You should do it after the request completed successfully !!

   $.ajax({
        type:"POST",
        url:"${pageContext.request.contextPath}/users/findWarehouseLat",  
        success:function(data){
            warehouseLat = data;
           alert(warehouseLat);
        }
    }); 

Upvotes: 1

Related Questions