Anticipating the arrival of various ajax outcomes within the onsubmit function

I'm struggling to grasp how I can effectively wait for the results of multiple functions that involve ajax requests.

I experimented with using Promise.all() and $.when().done();, but found them complicating my code rather than simplifying it. I also want to steer clear of using async: false within the ajax calls.

The structure of my main function doesn't necessarily have to be like that. I simply need a method that allows me to call one or more functions containing ajax requests, then pause the execution until all results are received without branching off into other functions.

function main(){
  //some functions

  UploadFile('input_1');
  UploadFile('input_2');
  .
  .
  .
  UploadFile('input_n');
 
  //Here is where I need to consolidate the results from the UploadFile functions 

  //some other functions
  //return true or false based 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 serves as the form validation function. It appears that setting it as async might not trigger at all; it won't wait for the UploadFile calls.

Answer №1

The await prefix can be used to make any asynchronous function or result resolved synchronously by pausing the function until the promise is either fulfilled or rejected.

To utilize the await prefix, the function containing it must be declared with the keyword async, allowing the runtime to handle the potential need to await a promise.

For more detailed information, refer to the MDN Documentation: Await Documentation

// To use await inside the Function, we must define it as an asynchronous function
async function main(e){
  // Prevents the form from submitting and executing its action
  e.preventDefault();
  e.stopPropagation();

  // Since UploadFile now uses synchronous Ajax call, we can directly use the returned result
  let res = UploadFile('input_1');
  console.log(res);
  
  // .. Other code
}


// Setting async: false for Jquery Ajax Call ensures response handling
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",
  });
  
  // Check if Request was successful based on status code range
  if(res.status >= 300 || res.status < 200) {
    console.error("Request Error:", res.statusText)
    return false;
  }
  
  // Assuming successful request to check response validity
  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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implementing Entity addition to a Data Source post initialization in TypeORM

The original entity is defined as shown below: import { Entity, PrimaryGeneratedColumn} from "typeorm" @Entity() export class Product { @PrimaryGeneratedColumn() id: number The DataSource is initialized with the following code: import ...

Mastering Promises, Async/Await for managing the flow of execution

Exploring the concepts of promises, await, and async functions has been a fascinating journey for me. As I delved into promises, I discovered an interesting aspect - the unpredictable order in which requests were resolved when multiple requests were sent o ...

Having trouble retrieving the value from the input field with Angular.js

I am having trouble retrieving the value from an input field using Angular.js. Below is the code explanation. Here is my controller code: $scope.shipping=0; $scope.addProductInfoData=function(billdata){ console.log('valid',$scope.shippi ...

Add numerous submit buttons within a form. Upon clicking on a button, the form should be submitted to a specific URL using AJAX

I have a form with two submit buttons: one labeled as "SUBMIT" and the other as "SCHEDULE NEXT ROUND". When a user clicks on the "SUBMIT" button, the form values should be stored in the database and redirect to the view page. If they click on the "SCHEDULE ...

JavaScript For Each loops are really starting to frustrate me

My issue seems to be straightforward. I am attempting to update a list of objects called localData with another list of objects that I received after making an AJAX request (referred to as data). The process involves using two loops, however, when I atte ...

An error occurred: The function get_posts() in WordPress is not defined

I am encountering an issue with registering my own ajax to WordPress. I have already reviewed this and also followed the tutorial at this link, but it seems that an error is occurring. Error Description: A fatal error has been encountered: Uncaught Err ...

Cannot access Nextjs Query Parameters props within the componentDidMount() lifecycle method

I have been facing a challenge with my Next.js and React setup for quite some time now. In my Next.js pages, I have dynamic page [postid].js structured as shown below: import Layout from "../../components/layout"; import { useRouter } from "next/router"; ...

Employing VAutocomplete component from vuetify in combination with a render function (scoped slot)

Trying to implement the Autocomplete component within a render function but encountering issues with the scopedSlots feature. Here is my code snippet: import { VAutocomplete } from 'vuetify/lib' export default { render (h) { return ...

How to programmatically update one input value in AngularJS and trigger validation as if it was manually entered by the user?

I'm currently using Angular 1.3.0rc2 and facing an issue with setting one input field based on another input field after the blur event. When I try to set the value of an input field that only has a synchronous validator, everything works fine by usi ...

Combining arrays from $_POST and storing them in a single column

I am facing an issue with my form that is supposed to post data to a PHP handler for saving in a database. The problem seems to be related to how the $_POST is merging the form's data. Even though the data is being saved in the SQL table, all values a ...

A versatile jQuery function for extracting values from a :input selector

Is there a universal method in jQuery to retrieve the value of any :input element? I pose this question because I have a webpage containing select and checkbox inputs, as seen in the code below: for (var i = 0; i < arguments.length; i++) { ...

Exploring and extracting values from nested arrays of objects in JavaScript and React

Hey there, I am having trouble getting the data from the backend server to display on a chart library. Can you please take a look at my code and help me out? const data = [ { id: "americano", data: [{x: "10",y: 10,}, {x: &quo ...

Within an Angular test scenario, execute a static method from a service that triggers an HTTP get request to fetch stored JSON data. This data is then retrieved and returned back to the service

Currently, I am facing a challenge in my Angular test case where I am trying to load JSON data via an HTTP call. The issue arises when a static method is called from a service spec file named "url-service.spec" to another service named "load-json.service. ...

Checking for valid zip code using a regular expression in JavaScript

Thank you for the suggestions, everyone. I have made some modifications to the script based on your advice and it appears to be functioning correctly now. <script src="jquery-1.4.2.min.js" type="text/javascript"></script> <script> $ ...

Unable to resize images in Firefox

Why is it that resizing doesn't seem to work in Firefox but functions fine in Internet Explorer? I'm struggling to find a way to make it consistent across all browsers. My goal is to resize the width to 800 and height to 475, disable maximizing t ...

The outcome of my function designed to calculate the highest possible profit using k transactions is a null array

I have developed a custom function to calculate the maximum profit from a series of stock transactions given a specific number of transactions allowed. Each transaction involves buying at a low price and selling at a higher price, with the rule that you ...

Which one is better: JSON in PHP or JSON in Javascript?

In my current project, I am working on a website that utilizes a PHP function to retrieve JSON data and present it on the webpage. However, I have noticed that when the page loads, it freezes until the response is successfully fetched, creating a visual di ...

PyScript <script type="py-editor"> Issue: SharedArrayBuffer cannot be used in an insecure environment

I am currently using PyScript to execute a basic Python script within my HTML file in order to show a pandas DataFrame. However, upon loading the page in the browser and attempting to run the code block by clicking the run button, I encounter an error rela ...

JWT authentication for restricted routes

I'm currently developing an application that requires users to log in and allows them to join private groups. I have successfully implemented the login part using JWT, but I'm struggling with how to prevent users from joining private groups until ...

Modifying attribute values in Angular through custom directives

Struggling to figure out the most efficient way to monitor attribute changes, preferably triggered by a keypress event and linked to the scope in the parent controller I want each individual instance of the directive to have its own 'hasFocus' p ...