locked
$.ajax How to make it async? RRS feed

  • Question

  • User-1104215994 posted

    Hi there,

    Is there a way to convert this ajax call into async?

    <script>
        
        (function () {
            'use strict';
            window.addEventListener('load', function () {
            
                var forms = document.getElementsByClassName('needs-validation');
    
                var validation = Array.prototype.filter.call(forms, function (form) {
    
                    form.addEventListener('submit', function (event) {
                        if (form.checkValidity() === false) {
                            event.preventDefault();
                            event.stopPropagation();
                        } else {
                            event.preventDefault();
                            $("#btn_add").html(
                                '<span class="spinner-border spinner-border-sm" role="status" id="spinner" aria-hidden="true"></span> Loading...'
                            );
                            var selText = $("#validationCustom04").val();
                            var gameName = $("#validationCustom04 option:selected").text();
                            var quantity = $("#quantity").val();
                           
                           
    
                            var serviceUrl = '/StockSales/StockAsyncTask?quantity=' + quantity + '&game=' + selText + '&gameName=' + gameName;
    
                            $.ajax({
                                type: "POST",
                                url: serviceUrl,
                                error: function (xhr) {
                                    $("#spinner").remove();
                                    $("#btn_add").html('Purchase');
                                    var msg = JSON.parse(xhr.responseText);
                                    //alert(msg['errorMessage']);
                                    alert(msg.errorMessage);
                                }
                            }).done(function (data) {
                                //alert(data.newUrl);
                                window.location.replace(data.newUrl);
                            });
                        }
                        form.classList.add('was-validated');
                    }, false);
                });
            }, false);
    
        })();
        
        $("#btn_clear").click(function () {
            $("#quantity").val(1);
            $("#validationCustom04").val("");
           
        });  
       
    </script>

    Thursday, May 27, 2021 6:21 PM

All replies

  • User475983607 posted

    Is there a way to convert this ajax call into async?

    AJAX (Asynchronous JavaScript And XML) is already asynchronous.  

    Maybe you are interested in learning the async functions in JavaScript?

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

    Maybe convert to the fetch API?

    https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

    Thursday, May 27, 2021 6:45 PM
  • User-474980206 posted

    not clear how it makes the code simpler. also as a successful ajax call replaces the page, why use ajax and an extra network call? why a post when data passed via url (poor - and data not encoded).

    anyway (as your code requires async support, you should use const instead of var):

        
        (function () {
            'use strict';
            window.addEventListener('load', function () {
                const forms = document.getElementsByClassName('needs-validation');
                const validation = Array.prototype.filter.call(forms, function (form) {
                    form.addEventListener('submit', async function (event) {
                        if (form.checkValidity() === false) {
                            event.preventDefault();
                            event.stopPropagation();
                        } else {
                            event.preventDefault();
                            $("#btn_add").html(
                                '<span class="spinner-border spinner-border-sm" role="status" id="spinner" aria-hidden="true"></span> Loading...'
                            );
                            const selText = $("#validationCustom04").val();
                            const gameName = $("#validationCustom04 option:selected").text();
                            const quantity = $("#quantity").val();
                            const serviceUrl = '/StockSales/StockAsyncTask?quantity=' + quantity + '&game=' + selText + '&gameName=' + gameName;
    
                            try {
                              const data = await $.ajax({
                                  type: "POST",
                                  url: serviceUrl,
                                  error: function (xhr) {
                                      $("#spinner").remove();
                                      $("#btn_add").html('Purchase');
                                      var msg = JSON.parse(xhr.responseText);
                                      //alert(msg['errorMessage']);
                                      alert(msg.errorMessage);
                                  }
                              });
                              window.location.replace(data.newUrl);
                            } catch (err) {/* error code in handler*/} 
                        }
                        form.classList.add('was-validated');
                    }, false);
                });
            }, false);
        })();
        
        $("#btn_clear").click(function () {
            $("#quantity").val(1);
            $("#validationCustom04").val("");
        });  
    

    Thursday, May 27, 2021 7:50 PM
  • User753101303 posted

    Hi,

    To me this Ajax call is already async. It's best to always tell which problem you are trying to solve rather than to ask about how to apply a solution you chose already to an unknown problem. For now my guess is that your fomr.classList.add('was-validated'); line is perhaps unintentionaly misplaced?

    Also cancelling a submit button to then just do a full refresh following ana Ajax call ids perhaps confusing? Which behavior do you see that you don"t like ?

    Thursday, May 27, 2021 11:07 PM