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

<body>
 <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">
   </form>
 </div>

function startPost(){
    setInterval(function(){
        $("field1").load("post.php");
    }, 4000)
}
});

post.php

<?php
include "connection.php";

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

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

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


if(!$resultinsert){

  echo $connection->error;
}else{
  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

0
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){
    event.preventDefault();
    setInterval(function(){
        $("field1").load("post.php");
    }, 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.

EDIT:

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(); }