Please ensure that you only submit an ajax form once

One issue I'm facing with my form is that sometimes when a user sends it, the submission occurs multiple times - 2, 3, 4 times or even more, instead of just once.

Even after setting the button to disabled, the problem persists and multiple submissions continue to happen.

I am completely clueless about what might be going wrong here. If disabling the button doesn't work, then what other steps should I take?

<form class="form-horizontal" id="AjanlatForm" method="post">
  <div class="form-group">
    <label class="col-md-3 control-label ajanlat_label" >Your Name:</label>
    <div class="col-md-8">
      <input id="AjanlatNev" name="AjanlatNev" type="text" class="form-control input-md">
    </div>
  </div>
  <!-- More form fields follow -->
</form>


$(document).ready(function(e) {

    $('.fancybox').fancybox();

    $("#AjanlatKeresBtn").click(function() 

    {
        // JavaScript code handling form submission
    });
});

Answer №1

Consider updating your button to type="submit" and setting up a submit event handler for the form instead of a click event handler for the button.

   <form class="form-horizontal" id="AjanlatForm" method="post">
      <div class="form-group">
        <label class="col-md-3 control-label ajanlat_label" >Your Name:</label>
        <div class="col-md-8">
          <input id="AjanlatNev" name="AjanlatNev" type="text" class="form-control input-md">
        </div>
      </div>
      <div class="form-group">
        <label class="col-md-3 control-label ajanlat_label" >Email Address:</label>
        <div class="col-md-8">
          <input id="AjanlatEmail" name="AjanlatEmail" type="text" class="form-control input-md">
        </div>
      </div>
      ... (Additional form fields)
    </form>



    $(document).ready(function(e) {

        $('.fancybox').fancybox();

        $("#AjanlatKeresBtn").click(function() 

        {

            $('#AjanlatResult').hide();

            $("#AjanlatModal").modal("show");
            $('#AjanlatForm').on('submit', function(e)
            {
                $('#kerdesButton').prop('disabled', true);
                e.preventDefault();
                var FormErros = [];
                var AjanlatNev = $('#AjanlatNev').val();
                var AjanlatEmail = $('#AjanlatEmail').val();
                ... (Validation checks for form fields)
        });
    });

Answer №2

To make the button work as intended, you have to follow these steps:

<button class="submitBtn" type="submit">Submit Here</button>

Then, in the JavaScript code, you would need to do the following:

$(".submitBtn").click(function(){
    $(".formToSubmit").submit(function(event) {
        // Prevents the form from submitting.
        event.preventDefault();
        // Handle form submission here
    })    
})

Answer №3

Upgrade your ajax request with the code below:

        var form = $("form");
        var jqXHR = form.data("jqXHR");
        if (jqXHR) {
            jqXHR.abort();
        }

        form.data("jqXHR", $.ajax({
            type: 'POST',
            cache: false,
            data: $('#AjanlatForm').serialize(),
            url: 'files/uj-ajanlatkeres.php',
            success: function (data) {
                //$('#kerdesButton').prop('disabled', false);
                $('#kerdesButton').hide();
                $('#AjanlatForm')[0].reset();
                location.href = "https://my-domain.com/uzenet/uj-ajanlatkeres";
            },
            complete: function (jqXHR, textStatus) {
                form.removeData('jqXHR');
            }
        }));

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

The tooltip is being truncated

https://i.sstatic.net/o41Qz.png Struggling with a tooltip that keeps getting cut off? I've tried everything and still can't get it right. <th class="fd-table--header-cell" scope="col"> <p class=&q ...

Sending data from a bespoke server to components within NextJS

My custom server in NextJS is set up as outlined here for personalized routing. server.js: app.prepare() .then(() => { createServer((req, res) => { const parsedUrl = parse(req.url, true) const { pathname, query } = parsedUrl ...

The base64 code generated by the toDataURL method on the canvas appears to be incorrect

I am facing an issue with my code while using canvas to draw a cropped image with base 64. The problem is that it works perfectly on Chrome but gives me a blank image on Firefox. async function base64SquareCrop(imgbase64, size = 224) { const img = docume ...

Looking to implement client-side JavaScript validation prior to utilizing jQuery AJAX validation

I'm struggling to make sure that my validate(form) function runs "before" my ajax function. I would appreciate any suggestions on how to connect the two and ensure they run in sequence when the form is submitted. Thank you! <script type="text/ ...

Using CSS and JavaScript to hide a div element

In my one-page website, I have a fixed side navigation bar within a div that is initially hidden using the display:none property. Is there a way to make this side nav appear when the user scrolls to a specific section of the page, like when reaching the # ...

Ways to ensure your Javascript code only runs based on the specific browser

I need a Javascript code to run depending on the browser version. Specifically, if the browser is not IE or is IE 9+, one piece of Javascript should be executed. If the browser is IE8 or lower, another piece of Javascript should be executed. My attempt to ...

Utilizing 'document.execCommand' for handling 'delete' key events in AngularJS

Here is a demo plunkr link that I have created to demonstrate the issue. I am looking to implement the strikeThrough command whenever there is a delete operation. For instance: If the user selects "Text" and presses the delete or backspace key, it should ...

Encountering problems when trying to mock values with Jest

I'm currently integrating Jest into an existing project that is already utilizing enzyme and jasmine. Although I have installed the jest packages and configured them initially, I am facing an issue where the mock data is not being supplied correctly. ...

The order of event capturing and bubbling phases is FLIPPED for the node triggering the event

Note: Using Chrome, works as expected in Safari. In summary, I thought I had a good knowledge of JavaScript. To test my skills, I decided to take a challenge and guess what happened: We have an <input type="button" id="btn"> with two event handlers ...

How to dynamically append a new array to an existing array of objects in React JS

When the button is clicked, I am retrieving the ID and quantity values. My goal is to add a new array inside the object array. See the code snippet below: addData = (d,v) => { const product = []; for (let i = 0; i < 1; i++) { produ ...

How to customize the background of radio buttons in HTML

I want the background color to stay consistent as lightgray for each <ul>. Currently, clicking the radio button causes the ul's background to change incorrectly. I am unsure of how to loop through all available ul elements using jQuery and woul ...

Searching for attributes in a JSON document

Currently, I am dealing with a results API that provides me with a JSON file. My goal is to search for a specific property within this file. To achieve this, I first push the JSON data into an empty array and then iterate over it to retrieve the first obje ...

Displaying a Laravel variable in an Ajax callback to trigger a separate Ajax function

What I am attempting to accomplish here is quite complex. I aim to utilize one Ajax function across my website to manage information updates. Essentially, a universal update script that will trigger upon form submission. The challenge I am facing is that ...

Creating a custom npm package for a specific project

As I work on an npm package named my-library and regularly publish updates to a private npm repository, how can I efficiently test changes without repeatedly releasing new versions? Consider the following scenario: I tweak the code in my-library, but wan ...

Place the controller information into a div element as a paragraph by utilizing the power of jQuery ajax functions

I am facing an issue with my controller where I am trying to retrieve data from a model and insert each piece of data into a div called test. The data should be displayed as paragraphs within the div, but unfortunately, it is not working as expected. Belo ...

Guide to triggering a popover from within another popover using jQuery

Currently, I have a situation where a popover is triggered by clicking on a button. The goal is to trigger another popover from the first popover by clicking on some content within it. If you'd like to see a demonstration, check out this JSFiddle lin ...

Disable the smooth scroll animation when transitioning between pages using the Link component in NextJS

Not sure if this is a new feature of Next.js, as I didn't encounter this issue in my previous Next.js project. When I reach the bottom of a page and try to navigate to another page, a scroll-to-top animation appears on the destination page. I want to ...

What is the method in JavaScript to retrieve the current date with millisecond precision?

Is there a way in JavaScript to obtain the current date and time down to milliseconds? When using the new Date() method, it returns the time up to seconds like this: console.log(new Date()) LOGS - Thu Sep 07 2017 14:47:37 GMT+0530 (India Standard Time) W ...

How can I add information into a nested div element?

I encountered an issue when attempting to insert data into my block. The div structure is as follows: <div class="1"> <div class="2"> <div class="3"> <div class="4"></div> </div> ...

Flask integration with AJAX for a HTML range slider

I'm currently facing a challenge with my HTML control panel that features an array of buttons and sliders. While the buttons are fully functional and trigger post requests that are received and executed by my Python app, I'm encountering issues w ...