skip to Main Content

A form is a really interesting element in javascript or jquery (in this case).

Here’s my problem:

JS:

const themeFolder = object_name.templateUrl;
const urlAjax = themeFolder + '/FormHandler.php';
const form = $('#contact-form');
const outputmessage = $('.output-message');

form.submit(function(e) {
    e.preventDefault();
    $.ajax({
        type: 'post',
        url: urlAjax,
        method: form.attr('method'),
        data: form.serialize() + '&submit=true',
        success: function (result) {
            console.log(result);
            outputmessage.append('<p>A message was sent successfully!</p>');
        }
    });
});

PHP:

if ($ok == true && isset($_POST['submit']) && empty( $honeypot )) {
    $json_tidy = json_encode($_POST);
    echo $json_tidy;
} else {
    echo 'something wrong';
}

Now, what I’m not getting is the fact that I can send the same form multiple times with the same values but I’m not finding a solution to send my form only once and disable the form right after having done that.

Probably I’m overthinking but for example, the json_tidy will post this result:

{"fname":"ma","lname":"ma","email":"[email protected]","message":"ciao","honeypot":"","submit":"true"}</body>

Which doesn’t make a lot of sense for me.

Plus in this case, I’m struggling in finding a value to identify as a counter for how many times I will send a form.

I can use return true and false, right after the form.submit(function(e) {} and at the and of the javascript, but it will only avoid to my js script to run and fire the php script, which is in my form:

<form id="contact-form" name="contact-form" action="{{ theme.link }}/FormHandler.php" method="POST">

I’m wondering if anyone else had the same problem in the past

2

Answers


  1. How about a boolean variable?

        // outer scope
        let hasSubmitted = false;
        //...
        form.submit(function(e) {
        if(hasSubmitted)return;
        hasSubmitted = true;
        //...
    

    or:

    const submitButton = $("#submit-button")
    
    form.submit(function(e) {
        submitButton.disabled = true;
    
    Login or Signup to reply.
  2. You can remove the submit event handler just after sending the form, so the form won’t be sent again.

    Depending on the jQuery version you are using, you can do that with

    $form.submit(false);
    

    Or:

    $form.off('submit');
    $form.on('submit', (e) => e.preventDefault());
    

    Another option is to disable the submit button and, optionally, the input fields:

    const $form = $('#form');
    const $message = $('#message');
    const $submit = $('#submit');
    
    $form.submit((e) => {
        e.preventDefault();
        
        // Option 1: Remove submit event handler:
        $form.off('submit');
        $form.on('submit', (e) => e.preventDefault());
        
        // Option 2: Disable the submit button:
        $submit.prop('disabled', true);
        
        // Disable all input fields (optional):
        $form.find('input, textarea').prop('disabled', true);    
        
        // Add feedback message:
        $message.text('Sending message...');
        
        // Simulate request:
        setTimeout(() => {
          // Update feedback message:
          $message.text('The message was sent successfully!');
        }, 2000)
    });
    body {
      font-family: monospace;
      font-size: 16px;
      margin: 0;
    }
    
    #form {
      width: 50vw;
      margin: 0 auto;
    }
    
    input,
    textarea,
    button {
      display: block;
      width: 100%;
      padding: 8px;
      margin-top: 8px;
      box-sizing: border-box;
      border: 2px solid black;
      background: transparent;
      font-family: monospace;
      font-size: 16px;
    }
    
    #message {
      margin-top: 8px;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <form id="form">
      <input type="text" placeholder="Subject" />
      <textarea placeholder="Message"></textarea>
      
      <div id="message"></div>
      
      <button type="submit" id="submit">Send</button>
    </form>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search