3

I have the following in my js file:

var highestNumb;
$.ajax({
          url: 'https://api.m.hostelworld.com/1.5/properties/'+propID+'/?update-cache=true', 
          dataType: 'json', 
          headers: {
            "Accept-Language": lang 
          },
          success: function(json) { 
            var numb = 0;
            for (var key in json.rating) {
                numb = Math.max(numb, json.rating[key]);
            }
            highestNumb = numb;
            return highestNumb;

          }, cache: false
});
var enH3 = 'Fellow travellers have rated this property ' + highestNumb + ' out of 100.',
    deH3 = 'Gäste haben das Hostel mit ' + highestNumb + ' von 100 Punkten bewertet. ',
    frH3 = 'Les autres voyageurs ont classé cette propriété ' + highestNumb + ' sur 100',
    esH3 = 'Otros viajeros han puntuado este alojamiento con u ' + highestNumb + ' sobre 100.',
    itH3 = "I tuoi compagni di viaggio hanno recensito questa struttura " + highestNumb + " su 100",
    brH3 = 'Hóspedes anteriores avaliaram esta propriedade em ' + highestNumb + ' de 100.',
    ptH3 = 'Hóspedes anteriores avaliaram esta propriedade em ' + highestNumb + ' de 100.',
    koH3 = '직접 여행한 숙박객들은 이 호스텔을 10점 만점 중 XX점 주셨습니다. ';

I am getting undefined every time I pass "highestNumber" in the variables translation below.

Am I accessing the variable in the wrong way?

Aessandro
  • 5,517
  • 21
  • 66
  • 139
  • Are you doing it `async:false` way ? OR you did not consider that `AJAX` is asynchronous ? – Rayon Apr 13 '16 at 10:53

2 Answers2

3

You should in your success function call another function, eg. setVars(highestNumb) and put your code that sets enH3, deH3 etc. variables in that function.

success: function(json) { 
   //your code
   setVars(numb);
}

function setVars(highestNumb)
{
    enH3 = 'Fellow travellers have rated this property ' + highestNumb + ' out of 100.';
    //....
}
Nemanja Todorovic
  • 2,521
  • 2
  • 19
  • 30
-1

Please put async:false

var highestNumb; $.ajax({ url: 'https://api.m.hostelworld.com/1.5/properties/'+propID+'/?update-cache=true', dataType: 'json', async:false, headers: { "Accept-Language": lang }, success: function(json) { var numb = 0; for (var key in json.rating) { numb = Math.max(numb, json.rating[key]); } highestNumb = numb; return highestNumb;

      }, cache: false

});

Brijal Savaliya
  • 1,101
  • 9
  • 19