Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

269
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda