Is it possible to include two AJAX requests within a single function that both execute when the same submission occurs?

Having one submit button for a function necessitates the running of two ajax functions when the submit button is clicked for validation purposes.

    <div class="form-group btn-group">
                  <input type="button" class="btn btn-link" value="Back" onclick="history.back()">
                  <input type="button" class="btn btn-primary" class="btn btn-link" value="View results" onclick="validateAndSubmit();">
                </div>

   async function validateAndSubmit() {
            $('.alert-danger').hide();
            $('.alert-text ul').text("");

            var hasError = false;

  <cfif form.output_type eq "cl2stats">

      $('.alert-danger').hide().find('ul').empty();
      var monthYear1 = $("#date1").val();
      var date1 = monthYear1.slice(0, 3) + "01/" + monthYear1.slice(3, 7);
      const monthYear2 = $("#date2").val(),
        splitted = monthYear2.split('/'),
        month = splitted[0],
        year = splitted[1],
        date2 = `${month}/${new Date(year, month, 0).getDate()}/${year}`;

      await makeGetRequest({
        url: "url?method=validateDateRange",
        data: {date1: date1, date2: date2}
      })
              .done(function (response) {
                if (response == "") {
                  document.getElementById("EIMEF_WATER_UTILITY_STATS").submit();
                } else {
                  $('.alert-danger').show().find('ul').html(response);
                  hasError = true;
                }
                $(window).scrollTop(0);
              });

  </cfif>

    if (hasError == false) {
      $.ajax({
        type: "POST",
        url: "url?method=regStatsExceedancesFilter2",
        dataType: "json",
        data: ({
          formString: formData
        }),
        success: function (response) {
          if (response == "success") {
            $('#EIMEF_WATER_UTILITY_STATS').trigger("submit");
          } else {
            $('.alert-danger').show();
            $('.alert-danger .alert-text ul').append(response);
            $(window).scrollTop(0);
          }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          alert("Status: " + textStatus + '\n' + "Error: " + errorThrown);
        }
      });
    }
  }

In case the first ajax call returns an error, it's vital that the form remains on the page instead of proceeding to the next page as it currently does.

Answer №1

When making an asynchronous call with ajax, your page will not wait for validations if you are using a regular submit button and form. One way to handle this is by using preventDefault() to stop the form from being submitted.

After completing the first ajax call, you can then proceed to make the second ajax call. Once the second ajax call is successful, you can choose to submit the form or not.

window.addEventListener("load", function(){
  /* Defining Functions */
  const Validations = () => {
    $.ajax({
      type: "POST",
      url: "...",
      dataType: "json",
      data: {
        "somedata": "..."
      },
      success: function (response) {
        /* First validation passed */
        /* Call the second validation */
        Validation2();
      },
      error: function(XMLHttpRequest, textStatus, errorThrown){
        /* Handle Error */
      }
    });
  }

  /* Defining Functions */
  const Validation2 = () => {
    $.ajax({
      type: "POST",
      url: "...",
      dataType: "json",
      data: {
        "somedata": "..."
      },
      success: function (response) {
        /* Second validation passed */
        /* Submit the form */
        $("#MyForm").unbind('submit').submit();
      },
      error: function(XMLHttpRequest, textStatus, errorThrown){
        /* Handle Error */
      }
    });
  }

  /* Attaching Events */
  // If you include your JS in a CFM page, you need to use 2 # to avoid errors
  $("#MyForm").submit(function(e){
    e.preventDefault();
    Validations();
  });


});

Alternatively, if you prefer to keep the two ajax calls separate, you can bind both ajax calls to the click event of your button. However, you won't be able to synchronize their responses.

In JavaScript, you can attach multiple events to the same element, and they will stack on top of each other.

window.addEventListener("load", function(){
  $("#MyButton").click(function(e){
    e.preventDefault();

    /* Call Ajax 1 */
    $.ajax({
      type: "POST",
      url: "...",
      dataType: "json",
      data: {
        "somedata": "..."
      },
      success: function (response) {
        /* First validation passed */
        /* Call the second validation */
        Validation2();
      },
      error: function(XMLHttpRequest, textStatus, errorThrown){
        /* Handle Error */
      }
    });
  });

  $("#MyButton").click(function(e){
    e.preventDefault();

    /* Call Ajax 2 */
    $.ajax({
      type: "POST",
      url: "...2",
      dataType: "json",
      data: {
        "somedata2": "...2"
      },
      success: function (response) {
        /* First validation passed */
        /* Call the second validation */
        Validation2();
      },
      error: function(XMLHttpRequest, textStatus, errorThrown){
        /* Handle Error */
      }
    });
  });
});

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

Exporting modules in Node.js allows you to use functions

Can you explain why this code snippet is successful: exports.foo = 'foo'; var bar = require('./foo'); console.log(bar); // {foo: 'foo'} While this one fails to produce the desired output: var data = { foo: 'foo' ...

Opting for Fetch API over Ajax for requests that involve Allow-Credentials and require POST methods

In this particular scenario, the utilization of Access-Control-Allow-Credentials accompanied by the POST method is key in managing server-side PHP session variables that need to remain stable. To provide some context, the front-end aspect involves a creat ...

IIS Alert: Missing Images, CSS, and Scripts!

When I tried to publish my website using IIS, I encountered the error message Cannot read configuration file due to insufficient permissions. After attempting to add permissions for IIS_USRS and realizing that this user does not exist on my computer runnin ...

Ajax Syntax Error: Unexpected Token U

I have been struggling all day with an issue while trying to send json data via ajax to Express. Here is how my ajax code looks like: $('#saveClause').click(function () { var username = document.getElementById('postUserName').inne ...

Issue with MVC 4 Asynchronous File Upload: Controller Always Receiving Null Value

I'm encountering an issue while attempting to upload a file asynchronously from ajax to my controller. I am passing 3 variables - PictureId, PictureName, and PictureFile. The problem specifically lies with the "PictureFile" variable as it consistently ...

Nested Ajax request fails and triggers a full page reload

My goal is to search for product information and images using a product code input on index.php. The query runs in open_first.php via an ajax post request, which works perfectly. open_first.php displays images that can be selected by clicking on them. How ...

Uploading videos to YouTube via Ajax

I've been working on implementing resumable video upload functionality for Youtube by following the instructions provided in the Youtube Resumable Upload API. However, I encountered an error message: "NetworkError: 404 Not Found - ". Below is the ...

What is a way to transfer an Object from one Vue.js component to another without relying on vuex?

Using vue-router in app.vue, I defined the two components as shown below: <div class='app'> <div class='nav'> <router-link to='/a'>to A component</router-link> <router-link to= ...

Getting the checked values from an AngularJS Material checkbox

<md-checkbox ng-repeat="program in ctrl.programs" ng-model="ctrl.programsSelected[program.id]"> {{program.name}} </md-checkbox> Checked Items: {{ctrl.programsSelected | json}} Current Output: Checked Items: [null,true,true,true,null,true, ...

Customizing the search functionality in Yii2 gridview to implement asynchronous data retrieval using

Currently, I am using the Yii2.0 search functionality and have encountered a situation where the ajax search works effectively when displaying the grid as is. However, I need to modify the layout (refer to the screenshot below) in order to conduct the sear ...

Tips for automating the click on a link that loads ajax data with selenium and python

I am attempting to extract data from a website that loads data using AJAX, and I am using Selenium with Python for this task. I am trying to click on a link that appears after an AJAX page load. Even after incorporating sleep functions in Python to ensur ...

Troubleshooting jQuery click event listeners and AJAX requests: Issue with second listener not functioning properly

There are two click listeners implemented on a page, one for a sub-navigation menu (which dynamically changes the list items in the menu) and another for a main menu (which dynamically changes the content in another section). <nav class="sub-nav"> ...

The printing function for the window system can cause disruptions to the layout of the table

After creating a page with a simple table that can be filled in and printed, I noticed some issues with the table formatting after printing. The intended table design was supposed to look like this: https://i.stack.imgur.com/aAk89.png However, upon print ...

Ensuring scroll position remains fixed post screen rotation in HTML/Javascript

Is there a foolproof method to retain the scroll position in an HTML document following a screen rotation? While this issue is specifically in a Cocoa Touch UIWebView, it seems to be prevalent across different platforms. The standard practice appears to re ...

Dynamically showing a div using JavaScript and AJAX after changing the window location

After successfully fetching data from the server through AJAX, I am redirecting to the same screen/URL. Is it possible to show/display a div after redirecting using jQuery? $.ajax({ type: "POST", url: action, data: form_data, success: func ...

Utilizing AJAX to showcase individual PHP files

My PHP elements are not being displayed in the code, and I need to figure out why. Below is the HTML code I am currently using: <div class="tablocation"> <ul class="css-tabs"> <li><a class="current" href="/wp-content/themes ...

Variability in Focus Behavior while Opening a URL in a New Tab with window.open()

Here is a code snippet I have been using to open a URL in a new tab: window.open(urlToOpen, '_blank', 'noopener noreferrer'); The issue I am experiencing is that when this code is executed for the first time, it opens the URL in a new ...

Developing the latest version of ngx-charts

I'm currently working on adding a personalized feature to ngx-charts that I would like to include in a release version. I was successful in implementing it using the standard src directory, but now I want to build a release version for potential distr ...

Issue with accessing Scope value in AngularJS directive Scope

FIDDLE I've recently developed a directive that looks like this: return { restrict: 'EAC', scope: { statesActive: '=' }, link: function (scope, element, attrs) { var ...

What is the method for arranging objects in AngularJS using a custom sorting sequence?

I would like to display an array of object's properties in a custom sorted order. Here is the initial array: $scope.weekDays = [ { "day" : "TUESDAY", "count": 10 }, { ...