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

84
Visualizações
Cannot Return Result from jQuery AJAX from a Function

I have a function using jQuery AJAX to return data from a data file. However, I cannot get the function to return the value. Any ideas?

    $(document).ready(function () {
        function getdata() {
            var result = 'default value';

            $.ajax({
                url: 'data/json/load.json',
                method: 'GET',
                dataType: 'json',
                success: function (response) {
                    result = response.data;
                    console.log('this is working and the result is: ' + result);
                    return result;
                }
            });

            return result;
        }

        var returndata = getdata();

        //I'm trying to return the results from my AJAX call here:
        console.log(returndata)
    });     
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

$(document).ready(function () {
    async function getdata() {
        await $.ajax({
            url: 'https://api.publicapis.org/entries',
            method: 'GET',
            dataType: 'json',
            success: function (response) {
                result = response;
            }
        });
        return result
    }

    getdata().then((result) => console.log(result));
    
 });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

about 4 years ago · Juan Pablo Isaza Relatório

0

You should get familiar with how Promises work, they're very convenient.

That's how You could use them in your code:

   $(document).ready(function () {
async function getdata() {
    var result = 'default value'


    await $.ajax({
        url: 'https://api.publicapis.org/entries',
        method: 'GET',
        dataType: 'json',
        success: function (response) {
            result = response
            console.log('this is working and the result is: ' + result)
        }
    })

    return result;
}

getdata().then(function(result) {
    returndata = result
    console.log(returndata)
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

about 4 years ago · Juan Pablo Isaza 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