Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

266
Visualizações
How can I store the result of an AJAX query in a pre-declared variable?
$("#btn").click(function() {
    var data;
    getData();
    // use data...
}

function getData() {
    $.ajax({
        // Usual AJAX key-value pairs...
        success: function(response) {
            // Set data = response
        }
    });
}

How can I store the response to the AJAX request in the data variable declared in the handler function?

I want to use the value returned by the server inside the handler function.

Is there a way I can do this without disabling asynchronous retrieval.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Based on what you are asking, you could do the following, but I would suggest running your logic inside of the callback itself, as Javascript will not wait for the ajax response to complete before moving on within the function.

var getData = function( callback ) {

    $.ajax({
        success: function( response ) {

            callback( response );

        }
    });

};

$('#btn').on('click', function(evt) {

    var data;

    getData(function(response) {
        data = response;

        //you should use data here

    });

});
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda