0

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();
});

});

Heidel
  • 3,174
  • 16
  • 52
  • 84

1 Answers1

3

I don't think this is an issue of scope. Your done callback will be called when your GET request is finished. However, the console.log(area_id) statement will be called before that, because of asynchronous execution. You could just delete the last log statement and only rely on the one in the done callback.

Jerome Reinländer
  • 1,227
  • 1
  • 10
  • 26
  • Oh no! ;-( I need to get `area_id` and then use it to send another `ajax` request, and I think it's bad solution to put one `ajax` request in `done` callback of other `ajax` request. – Heidel Mar 21 '18 at 08:01
  • It must be something like that https://jsfiddle.net/ggLkqsa1/1/ – Heidel Mar 21 '18 at 08:03