A
A
Artem Shchurin2015-10-22 11:58:20
JavaScript
Artem Shchurin, 2015-10-22 11:58:20

How to return ajax request response to a variable?

Good afternoon!

I implement the method, it takes the path in the directory, makes a request to the server, passing the path, the server returns the id.

The received response is in a different scope and I cannot put it in a variable that is waiting for a response from a function call.

After all, at the time of assigning the value to the variable, the answer has not yet arrived.

Can you tell me how to deal with such a situation?

var id = getId(relativePath);

function getId(relativePath) {

  var jqxhr = $.get("http://192.168.1.1:8080/ContentFileId", {
    "relativePath": relativePath
  }, null, "text");

  return jqxhr.always(function(response) {

    if (typeof response == 'string') {

      return response;

    } else {

      console.log(response.responseText);

    }

  })
}


the method call and its implementation will come from different places

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Ineshin, 2015-10-22
@IonDen

getId(relativePath); - that's not possible. Ajax request is not synchronous, to get its result you have to do like this:

// вместо
console.log(response.responseText);
// присвоить значение
id = response.responseText;
// продолжить выполнение своего кода.

The code can be organized better to be clearer:
function step1 () {
    // some code
    
    $.ajax({
        // параметры запроса
        success: function (data) {
            step2(data);
        }
    });
}

function step2 (data) {
    // some other code
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question