简体   繁体   中英

How to run a function that a on form submit ajax with automatic click button

I am trying to submit a form with just automatic click button.

so I have a timer which is if the timer is already 0, it should submit the form automatically.

here is the code that I have.

function tick() {
    var timeDisplay = document.getElementById('question_timer');
    var isTimeLimit = true;
    var min = Math.floor(secondsRemaining / 60);
    var sec = secondsRemaining - (min * 60);

    if (sec < 10) {
        sec = '0' + sec;
    }

    var message = min.toString() + ':' + sec;
    timeDisplay.innerHTML = message;

    //stop if down to zero
    if (secondsRemaining === 0 && isTimeLimit == true) {
        clearInterval(intervalHandle);
        displayQuestion();
    } else {
        //boolean is false
        if (secondsRemaining === 0) {
            submitAnswer();
            clearInterval(intervalHandle);
        }

    }

    secondsRemaining--;
}

function startCountdown() {

    clearInterval(intervalHandle);

    secondsRemaining = 5;

    intervalHandle = setInterval(tick, 1000);
}

function submitAnswer() {
    $('#form_question_scenario').on('submit', function(e) {
        $.ajax({
            method: "post",
            url: url,
            data: new FormData(this),
            dataType: "json",
            contentType: false,
            cache: false,
            processData: false,
            success: function(data) {

            },
            error: function(jqXHR, textStatus, errorThrown) {
                alert('Error adding / update data');
            }
        });
    });
}

How can I run the submitAnswer function if the timer is already 0. any help would be really appreciated.

The submitAnswer() function just attaches the event handler, it doesn't actually submit the form.

To achieve what you require attach the submit event handler when the page loads, then when you want to submit the form trigger that event on it. Try this:

// attach submit event handler when the page loads
$('#form_question_scenario').on('submit', function(e) {
  $.ajax({
    // ajax settings here...
  });
});

function tick() {
  var timeDisplay = document.getElementById('question_timer');
  var isTimeLimit = true;
  var min = Math.floor(secondsRemaining / 60);
  var sec = ('00' + (secondsRemaining - (min * 60))).slice(-2); // note tidied the logic here
  var message = min.toString() + ':' + sec;
  timeDisplay.innerHTML = message;

  // stop if down to zero
  if (secondsRemaining === 0 && isTimeLimit == true) {
    clearInterval(intervalHandle);
    displayQuestion();
  } else {
    if (secondsRemaining === 0) {
      $('#form_question_scenario').trigger('submit'); // submit the form here
      clearInterval(intervalHandle);
    }
  }

  secondsRemaining--;
}

function startCountdown() {
  clearInterval(intervalHandle);
  secondsRemaining = 5;
  intervalHandle = setInterval(tick, 1000);
}

You don't need submit event at all, just call the function like you did when 0 sec is left, get id of form and create new form data, and do Ajax request...

function submitAnswer() {
let myForm = document.getElementById('form_question_scenario');
        $.ajax({
            method: "post",
            url: url,
            data: new FormData(myForm),
            dataType: "json",
            contentType: false,
            cache: false,
            processData: false,
            success: function(data) {

            },
            error: function(jqXHR, textStatus, errorThrown) {
                alert('Error adding / update data');
            }
        });

}

EXAMPLE:

Form data is populated without submit event just by calling the function:

 function submitAnswer() { let myForm = document.getElementById('form_question_scenario'); let data = new FormData(myForm) formObj = {}; for (var pair of data.entries()) { formObj[pair[0]] = pair[1] } console.log(formObj) } submitAnswer()
 <form id="form_question_scenario"> <input type="text" value="test" name="test"> </form>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM