0

This code snippet gets a Json data from a API hosted in my localhost. I can get the json objects into their own css id(selector?) but I want to use value somewhere else in my javascript. For example, I want to use '#long' in my javascript. I tried using global variable but it says that 'long' is undefined. What do I have to do so that I can use uid, lat or long elsewhere in my script?

   $(document).ready(function(){

    $.get("http://localhost:4567/get/233307/loc", function(data){
        $('#uid').append("UID: " + data.uid);
        $('#lat').append("Latitute: " + data.lat);
        $('#long').append("Longitude: " + data.long);

        var long = data.long;
        alert(long);
        }, "json");

});

Thanks.

3 Answers 3

1
var myApp = {};
$(document).ready(function(){

    $.get("http://localhost:4567/get/233307/loc", function(data) {
       myApp.data = data; // Can be stored here.
       orPassItToAnotherFunction(data);
    });
});
0
1

Declare the variables in the global scope, and assign them in the ajax callback.

var long;
var lat;
var uid;

$(document).ready(function(){

 $.get("http://localhost:4567/get/233307/loc", function(data){
    $('#uid').append("UID: " + data.uid);
    $('#lat').append("Latitute: " + data.lat);
    $('#long').append("Longitude: " + data.long);

    long = data.long;
    lat = data.lat;
    uid = data.uid;
    alert(long);
 }, "json");

});
2
  • you should prob enclose them in namespace though. Commented Apr 22, 2011 at 19:36
  • I have tried doing this but, if I try to use long, lat or uid in another function it has 'undefined' value. Commented Apr 22, 2011 at 19:57
0

Try declaring var long; previously, outside $(document).ready(function(){

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.