Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

266
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!