1

I have one submit button for a function and for validation purposes, I need to have two ajax functions run when the submit is clicked.

 <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); } }); } } 

If the first ajax call returns an error, I need the form to stay on the page. Currently, if the first call returns an error, it moves to the next page.

9
  • var hasError = false; if (hasError == false) totally redundant, since hasError is guaranteed to always be false on the line of code after setting it false Commented Apr 23, 2019 at 2:23
  • 2
    You should do the second call inside the success function of the first call. Commented Apr 23, 2019 at 2:30
  • 1
    And it should be in the if (response == "success") block. Commented Apr 23, 2019 at 2:32
  • Thanks, Barmar. I will give that a try. Commented Apr 23, 2019 at 2:33
  • 1
    im pretty sure your if (hasError == false) will not work... to make this work that way you must create one Observable to "watch" your hasError variable, and then execute some action when this is trigger, you can do that using inputs hidden in your form and binding the event "on change" but this is not very safe, since everyone can inspect the page and change the value, or just run some JS in console, the simple way to do that is just call one ajax after another, and after the both ajax is sucessed you submit your form, i hope this helped you Commented Apr 23, 2019 at 17:27

1 Answer 1

2

Since ajax is async call... you page will not wait you do your validations if you using regular submit button and form, one way to do that is use preventDefault() to prevent the form be submitted.

Next step you can call your second ajax after the first is done or completed, and only after the second ajax call you submit or form or dont.

window.addEventListener("load", function(){ /* Declaring Functions */ const Validations = () => { $.ajax({ type: "POST", url: "...", dataType: "json", data: { "somedata": "..." }, success: function (response) { /* Passed in first validation */ /* Call the second validation */ Validation2(); }, error: function(XMLHttpRequest, textStatus, errorThrown){ /* Throw Error */ } }); } /* Declaring Functions */ const Validation2 = () => { $.ajax({ type: "POST", url: "...", dataType: "json", data: { "somedata": "..." }, success: function (response) { /* Passed in second validation */ /* Submit the form */ $("#MyForm").unbind('submit').submit(); }, error: function(XMLHttpRequest, textStatus, errorThrown){ /* Throw Error */ } }); } /* Declaring Events */ // If you place your JS inside CFM page you will have to place 2 # or will prompt a error $("#MyForm").submit(function(e){ e.preventDefault(); Validations(); }); }); 

Or... if you want to keep 2 ajax separated, you could just bind the both ajax on click event in your button, but you cant capture the answer of each one to make both work together.

In javascript you can bind same events to same elements, they stack 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) { /* Passed in first validation */ /* Call the second validation */ Validation2(); }, error: function(XMLHttpRequest, textStatus, errorThrown){ /* Throw Error */ } }); }); $("#MyButton").click(function(e){ e.preventDefault(); /* Call Ajax 2 */ $.ajax({ type: "POST", url: "...2", dataType: "json", data: { "somedata2": "...2" }, success: function (response) { /* Passed in first validation */ /* Call the second validation */ Validation2(); }, error: function(XMLHttpRequest, textStatus, errorThrown){ /* Throw Error */ } }); }); }); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.