-2

I have a problem with this code I manage to take the values from the json and put them into variables but I can not use them outside the function what am i doing wrong ?

var sensor_name1;
var lat1;
var lng1;
var sensor_name2;
var lat2;
var lng2;
var sensor_name3;
var lat3;
var lng3;



 $(function (){
 var $sensors = $('#sensors');

 $.ajax({
 type:'GET',
 url:'http://127.0.0.1:5000/',
 success: function(sensors){
 $.each(sensors, function(i, sensor) {
 if (i==0){
 $sensors.append(sensor_name1=sensor.name, lat1=sensor.lat, lng1=sensor.lng);
 }
 if(i==1){
 $sensors.append(sensor_name2=sensor.name, lat2=sensor.lat, lng2=sensor.lng);
 }
 if (i==2){
 $sensors.append(sensor_name3=sensor.name, lat3=sensor.lat, lng3=sensor.lng);
 }


 });

console.log('sensor one : ',sensor_name1, lat1, lng1);
console.log('sensor tow : ',sensor_name2, lat2, lng2);
console.log('sensor three : ',sensor_name3, lat3, lng3);

  }
 });

});

1 Answers1

0

Hi and welcome on Stack Overflow :)

JavaScript Ajax is asynchronous and you execute console.log() before these variables receive a value.

But in your case you pass to append() which accepts a htmlString, Element, Text, Array or jQuery parameter a assignment of value expression. You don't append a child, but you declared it using append()

You must have to wait for response from server and after use that.

$(function () {
    var $sensors = $('#sensors');

    $.ajax({
        type: 'GET',
        url: 'http://127.0.0.1:5000/',
        success: function (sensors) {
            $.each(sensors, function (i, sensor) {
                let sensorInfo = 'sensor #'+i+': '+sensor.name+' '+sensor.lat+' '+sensor.lng;

                console.log(sensorInfo);
                $sensors.append('<p>'+sensorInfo+'</p>')
            });

        }
    });

});

Greetings, plum!

Sources:

Asynchronous on MDN: https://developer.mozilla.org/en-US/docs/Glossary/Asynchronous

jQuery Docs: https://api.jquery.com/jQuery.get/#jQuery-get-url-data-success-dataType

plumthedev
  • 70
  • 12
  • I tried it but now it does not read the Jesson at all Before that I received a response from the server and managed to put the value of the jason in variables but only that they are within the function – kfir tevet Apr 26 '19 at 00:16
  • You are trying to get to something that will be in the future, this is response. If you want to access a data outside the function and after assignment you must assign value to global scope. Look at this example (https://jsbin.com/kezolisuqo/edit?html,js,console,output) and read more about [scopes](https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) and [closures](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures). – plumthedev Apr 26 '19 at 07:51