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

355
Views
Execute a function after $.ajax success without putting it in a callback directly

I have this function where many parts of my code call it.

function test() {
  $.ajax({
    url : url,
    type : 'GET',
    success : {
      verifyID();
      verifyName();
      verifyBlah();
    }
  });
}

and I have this other function:

addProductCart(productID);

Before I call addProductCart(), I need to call test function, but, other processes call test function.

I'd like to do this:

test() ---> if test ok (success) ----> addProductCart()

But I can't set my function (addProductCart) into success test function because, like I said, many other processes call test function.

How can I do this?

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Use Promises!

Return a promise from the test function like so:

function test() {
  return $.ajax({ // <----- Notice the return statement here
    url : url,
    type : 'GET',
    success : {
      verifyID();
      verifyName();
      verifyBlah();
    }
  });
}

When you need to use this function to test something and execute another piece of code when this passes you can do :

test().then(function(data, textStatus){
  //do thing 1
  addProductCart()
  // you can use data or textStatus returned by your ajax function here too!
});

test(someParam).then(function(data, textStatus){ // <--- You can even pass parameters to test function like here, and make it do different ajax call based on your param
  //do thing 2
});

For more details on how this works see the jQuery docs for $.ajax. function

Here's a great tutorial on concept of JavaScript Promises to get you started if you are unfamiliar with them.

about 4 years ago · Santiago Trujillo Report
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!