skip to Main Content

I am working on developing a script that triggers the submit button at the end of a form at a specified time on client side. The goal of this test is to simulate a scenario where multiple users submit the same form simultaneously but with different details. Imagine 20 people in a room, all connected to the same network and each with their own device. They’ve all completed the application, and when someone says ‘1, 2, 3, go,’ they all press the submit button at the exact same time.

I created the following script with the help of AI, but the problem is that it only refreshes the page instead of actually triggering the submit button.

let me tell you in advance that I am a beginner.

// Function to schedule a submit request
function scheduleSubmit() {
    // Set the specific time to submit
    const timeInput = "10:30 PM"; // Change this to your desired time

    // Validate the time input format
    const timePattern = /^(0?[1-9]|1[0-2]):[0-5][0-9] (AM|PM)$/;
    if (!timePattern.test(timeInput)) {
        console.error("Invalid time format. Please use HH:MM AM/PM format.");
        return;
    }

    const [time, period] = timeInput.split(' ');
    let [hours, minutes] = time.split(':').map(Number);

    // Convert hours to 24-hour format
    if (period === 'PM' && hours < 12) {
        hours += 12;
    } else if (period === 'AM' && hours === 12) {
        hours = 0;
    }

    const now = new Date();
    const submitTime = new Date();

    // Set the submit time to today at the specified hours and minutes
    submitTime.setHours(hours, minutes, 0, 0);

    // If the specified time is in the past, set it for tomorrow
    if (submitTime < now) {
        submitTime.setDate(submitTime.getDate() + 1);
    }

    // Schedule the submit button click
    const delay = submitTime - now;
    setTimeout(() => {
        const submitButton = document.querySelector('.btn.btn-danger.btn-block.mt-3');
        if (submitButton) {
            submitButton.click();
            console.log(`Submit triggered at ${submitTime.toLocaleTimeString()}`);
        } else {
            console.error("Submit button not found.");
        }
    }, delay);

    console.log(`Submit scheduled for ${submitTime.toLocaleTimeString()}`);
}

// Call the scheduleSubmit function to start the process
scheduleSubmit();

trying to learn the script in multiple request scenario.

2

Answers


  1. The default behaviour of form in the browser is to trigger a page refresh after the form is submitted. If you want to disable the browser default for form submission, you should call event.preventDefault() in your scheduleSubmit() function and this will prevent your page from refreshing after the button is clicked.

    function scheduleSubmit(event) {
         event.preventDefault()
        // Set the specific time to submit
        const timeInput = "10:30 PM"; // Change this to your desired time
    
        // Validate the time input format
        const timePattern = /^(0?[1-9]|1[0-2]):[0-5][0-9] (AM|PM)$/;
        if (!timePattern.test(timeInput)) {
            console.error("Invalid time format. Please use HH:MM AM/PM format.");
            return;
        }
    
        const [time, period] = timeInput.split(' ');
        let [hours, minutes] = time.split(':').map(Number);
    
        // Convert hours to 24-hour format
        if (period === 'PM' && hours < 12) {
            hours += 12;
        } else if (period === 'AM' && hours === 12) {
            hours = 0;
        }
    
        const now = new Date();
        const submitTime = new Date();
    
        // Set the submit time to today at the specified hours and minutes
        submitTime.setHours(hours, minutes, 0, 0);
    
        // If the specified time is in the past, set it for tomorrow
        if (submitTime < now) {
            submitTime.setDate(submitTime.getDate() + 1);
        }
    
        // Schedule the submit button click
        const delay = submitTime - now;
        setTimeout(() => {
            const submitButton = document.querySelector('.btn.btn-danger.btn-block.mt-3');
            if (submitButton) {
                submitButton.click();
                console.log(`Submit triggered at ${submitTime.toLocaleTimeString()}`);
            } else {
                console.error("Submit button not found.");
            }
        }, delay);
    
        console.log(`Submit scheduled for ${submitTime.toLocaleTimeString()}`);
    }
    
    // Call the scheduleSubmit function to start the process
    scheduleSubmit();
    

    It would have been very helpful if you posted your HTML document too but I hope this solves the refresh issue you’re experiencing.

    Login or Signup to reply.
  2. As the HTML to the question wasn’t provided I took the liberty of inventing my own. In the snippet below the data of the page’s first <form> element will be evaluated (shown in a console.log() and sent to a remote server: https://dummyjson.com) at a given time (here: 19:45h local time):

    // Function to schedule a submit request
    function scheduleSubmit() {
    const now=new Date(),
          submitTime=new Date();
    submitTime.setHours(19);
    submitTime.setMinutes(45);
    submitTime.setSeconds(0);
    
    // ======================
    // temporary modification to demonstrate the delay on Stackoverflow:
    // set target time to be 10 seconds in the future 
    submitTime.setTime(now.getTime()+10000);
    // ======================
    if (submitTime < now) {
        submitTime.setDate(submitTime.getDate() + 1);
    }
    
    // Schedule the submit button click
    const delay = submitTime - now;
    setTimeout(() => {
      // extract all available input information 
      // from elements in the first user form of the page: 
      const d=Object.fromEntries(new FormData(document.forms[0]));
    
      // do something with the entered form data, 
      // without actually submitting the form ... 
      fetch("https://dummyjson.com/products/add",{method:"POST",headers: {"Content-Type": "application/json"},body: JSON.stringify({title:d})})
         .then(r=>r.json()).then(resp=>console.log("the server replied with:",resp));
      console.log(`Submit triggered at ${submitTime.toLocaleTimeString()}`);
     }, delay);
    console.log(`Submit scheduled for ${submitTime.toLocaleTimeString()}`);
    }
    
    // Call the scheduleSubmit function to start the process
    scheduleSubmit();
    <form>
     <input type="text" name="name" value="Carsten"><br>
     <input type="text" name="favLang" value="JavaScript">
    </form>

    I modified OP’s script to not operate on a particular <button> but instead to work with the <form> and its input elements. This way the form will not be submitted as such and a page reload is avoided. If you want to transfer the data to a server at the targeted time, you could use a fetch() call to establish this AJAX communication in the background. I used the publicly available API https://dummyjson.com to send the data to.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search