Home > Mobile >  Waiting for multiple ajax results on the onsubmit function
Waiting for multiple ajax results on the onsubmit function

Time:08-09

I am having problems understanding how I can wait for the results of multiple functions that have ajax in them.

I tried using Promise.all() or $.when().done(); These functions only call another function when they are done and I would like to avoid this method because it will infinitely complicate may code. I also don't want to use async: false in the ajax call.

The main function doesn't even have too look like that. I only need to know if there is a method that can call 1 or more function that have ajax then wait for the results without continuing in another function.

function main(){
  //some functions

  UploadFile('input_1');
  UploadFile('input_2');
  .
  .
  .
  UploadFile('input_n');
 
  //Here is where  I want to know all the results of the UploadFile functions 

  //some other functions
  //return true or false dependig on //some functions, UploadFile AND //some other functions
}

function UploadFile(inputId){
  return $.ajax({
    //ajax parameters
    success: function(IDUpload) {
      if (IDUpload > 0) {  
        return true;
      }
      return false;
    },
    error: function(error) {
      return false;
    }
  });
}

Edit: The main() function is the validation function for the form. It seems that if I make it async, it wil not fire at all it will not wait for then UploadFile calls.

CodePudding user response:

You can use the await prefix, to make any asynchronous function or result to be resolved synchronously, by halting the function until the promise resolved to either success or an error.

To use the await prefix, you need to declare the function containing the await prefixes with async, for the runtime to prepare for the possible situation to await for a promise.

Further Information can be read in the MDN Documentation: Await Documentation

// We need to define the Function as an asynchronous function, to apply await inside
async function main(e){
  // Added for preventing the submit to propagate to the action-URL
  e.preventDefault();
  e.stopPropagation();

  // As the UploadFile now only uses the synchronous Ajax-Call we can just use the returning 
  // result of the Function.
  let res = UploadFile('input_1');
  console.log(res);
  
  // ... Other code
}


// We use the async: false Property of the Jquery Ajax Call, thous getting the response as a 
// result.
function UploadFile(inputId){
  let res = $.ajax({
    method: "GET",
    async: false,
    url:"https://www.random.org/integers/?num=1&min=-10&max=10&col=1&base=10&format=plain&rnd=new",
  });
  
  // As the Ajax Call is now synchronous we have to check if the Request was successfull 
  // ourself. For this, we check for the Response status. Any status between 200 - 299 is 
  // successfull and any other has any error depending on the status code. But we wont bother 
  // much which error was thrown.
  if(res.status >= 300 || res.status < 200) {
    console.error("Request Error:", res.statusText)
    return false;
  }
  
  // With the guarding If-Check before we can surely assume, the Request was successfull and 
  // can check now with the same logic as in the success-Method before. I've inverted the 
  // checks to keep consitent with the guarding If-statements.
  // Same as: if(IDUpload < 0)
  if(res.responseText < 0) {
    console.log("The Response is not 'valid'");
    return false;
  }
  
  console.log("The Response is 'valid'");
  return true;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form onsubmit="main(event)">
  <button type="submit">Submit Form</button>
</form>

  • Related