I'm trying to set value of variable inside if
, but my code doesn't work and ouside if console.log(area_id);
print undefined
var area_id;
if (area.length > 1) {
$.ajax({
method: 'GET',
url: 'https://example.com/suggests/areas/?text=' + area
})
.done(function (response) {
area_id = response.items[0].id;
console.log(area_id);
});
}
console.log(area_id);
I guess it's some problem with scopes, but I don't understand how to solve it ?
UPD Full script
$(document).ready(function () {
"use strict";
var $body = $('body');
$('#search-form').submit(function (e) {
$(' #form-button ').attr("disabled", true);
var position = $(' #position ').val();
var area = $(' #area ').val();
var experience = $(' #experience ').val();
var period = $(' #period ').val();
var area_id;
if (area.length > 1) {
$.ajax({
method: 'GET',
url: 'https://example.com/suggests/areas/?text=' + area
})
.done(function (response) {
area_id = response.items[0].id;
console.log(area_id);
});
}
console.log(area_id);
/*console.log(position);
console.log(area_id);
console.log(experience);
console.log(period);*/
if (position && (position.length > 1) && experience && period && area_id) {
$.ajax({
method: 'GET',
url: 'https://example.com/vacancies/?text=' + position + '&area=' + area_id + '&experience=' + experience + '&period=' + period,
success: function (response) {
console.log(response);
}
});
} else {
$('#result').html('').append('<p class="text-danger">Error</p>');
}
$(' #form-button ').attr("disabled", false);
e.preventDefault();
});
});