locked
Handling Ajax calls on two or more events on client side. RRS feed

  • Question

  • User-1549556126 posted

    I have two components a textbox & a button. On both of the components, I have an ajax calls say for example, on textbox.onblur (using javascript) I am using ajax call to perform server side validation & on button.onclick I am performing ajax call for submitting the updated data. The issue I am facing is that when I am clicking the button while the textbox is focused the the click event is firing before the on blur. This is leading to submit the data before the validation task in blur ajax fires. Is it a javascript issue?  Here's a sample code that I have:

    $(document).on('blur', '#myTextbox', function () {
                if ($.trim($(this).val()) != '') {
                   
                    $.ajax({
                        async: true,
                        type: "POST",
                        url: "/Index/ValidateUser",
                        data: {
                            inputData: $('#myTextbox').val()
                        },
                        success: function (response) {
                            $("#myTextbox").val(response.message);
                    });
                } else { $("#myTextbox").val(''); }
    $('#btnSubmit').on('click', function () {
             $.ajax({
                        url: '@Url.Action("UpdateData", "Submit")',
                        type: 'POST',
                        data: '{ submittedData:' + $("#myTextbox").val(),
                        success: function (response) {
                            console.log(response.ResultValue);
                            
                        }
                    });
    });

    Tuesday, April 28, 2020 8:18 PM

All replies

  • User475983607 posted

    Shouldn't both HTTP request validate the data since there is no way to guarantee the user presses tab or clicks somewhere else before attempting a submit?

    Tuesday, April 28, 2020 9:48 PM
  • User-1549556126 posted

    Yeah, however there is some specific requirement that one validation need to happen on blur even but the button click is executing before on blur of textbox when we click on the button while the focus is in the textbox. 

    Tuesday, April 28, 2020 9:51 PM
  • User475983607 posted

    vyasnikul

    Yeah, however there is some specific requirement that one validation need to happen on blur even but the button click is executing before on blue of textbox when we click on the button while the focus is in the textbox. 

    Correct.  Validate the text input in the click event too.  Do not submit the update if the validation fails.  

    Tuesday, April 28, 2020 9:55 PM