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

270
Visualizações
How to wait until ajax function is done in javascript

I have two functions. one function call for the ajax function. My problem is it is not waiting until the ajax function is complete. it is executing my other code before. How to wait for ajax is complete?

function getdata(){
 var imgPath = getImgPath();
 const img2 = document.getElementById("backimg");
 img.src = imgPath;
}

function getImgPath(){

$.ajax({
    url:spath,
    type:'HEAD',
    dataType: "jsonp",
    crossDomain: true,
    secure: true,
    // async:false,
    headers: {
      "accept": "application/json",
      "Access-Control-Allow-Origin":"*"
          },
    success: function()
    {
        //file exists do something here
        console.log("exist ");
        path = spath;
    },
    error: function()
    {
        //file does not exist
        console.log("doesnt exist");
        path = lpath;
    }
});
}

This is what I tried. This ajax function executes well but when I run my code before finish the getImgPath() function it is executing other code lines. How can I wait until the ajax function is finished?

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