I want to post data from my website to my database every few seconds using the setInterval function. I don't get any error messages, the page just refreshes removing any entered data but no data is posted to the database

 <div class="container">
   <div class="row">
     <form onclick="startPost()" method='POST' enctype='multipart/form-data'>
     <textarea name="field1" id="field1"></textarea>
     <input type="submit" id="post">

function startPost(){
    }, 4000)


include "connection.php";

$post1 = $connection->real_escape_string($_POST['field1']);

$insert = "INSERT INTO DBtable (WebText) VALUES ($post1)";

$resultinsert = $connection->query($insert);


  echo $connection->error;
  echo "<p> Text is posting </p>";


I want the data to be posted to the DB every four seconds but the page just refreshes on hitting submit. The connection.php connects to the database

1 Answers

Community On

HTML form submissions have a default behavior to refresh at the end of the submit.

<form onclick="startPost(event)" method='POST' enctype='multipart/form-data'>

Pass the event to your function like above

function startPost(event){
    }, 4000)

Add preventDefault to stop this default behavior. Different browsers sometimes react differently and sometimes it's necessary to also perform event.stopPropagation() This prevents the event from triggering onclicks to its parent elements as well. Not needed in your exact case.


In order to stop reload on submission exactly you would need to catch the event onsubmit as follows:

<form onsubmit="preventReload(event)" method='POST' enctype='multipart/form-data'>
function preventReload(event) { event.preventDefault(); }