post text on same page without refresh using FETCH and send the data to the database

I’m a beginner in php / javascript, so please be indulgent with me ahah

I want to be able to post text and show the the result on the same page without reload the page. I also need to send the data to the database (this part should be fine as I’ve done it few times in the past)


<div class="container">
  <form method="POST" action="" class="d-flex flex-wrap justify-content-end">
    <input class="form-group add-tweet" type="text" placeholder="What's happening ?"      id="postTweet">
    <input type="submit" value="envoyer" id="submitTweet">
  <div class="tweet-container">
    <p id="tweet-value">I want to show my data here</p>
document.getElementById("submitTweet").addEventListener("click", postTweet);
function postTweet(e) {
  const inputTweet = document.getElementById("postTweet").value;
  const containerTweet = document.getElementById("tweet-value");
  //const tweet = (containerTweet.innerHTML = inputTweet);

  const myTweet = {
    body: inputTweet,

  fetch("index.php?action=home", {
    method: "POST",
    headers: {
      Accept: "application/json",
    body: JSON.stringify(myTweet),
    .then((res) => res.json())
    .then((data) => {
      data = containerTweet.innerHTML = myTweet;
    .catch((err) => {

My repository

  public function postTweet($id_user, $tweet)
    $sql = "INSERT INTO tweet (ID_user, text, date) VALUES (:ID_user, :tweet, NOW())"; 
    $query = $this->connect()->prepare($sql);
      "ID_user" => $id_user,
      "tweet" => $tweet,


$postTweet = $TweetRepository->postTweet($userId, "this is a test");

my method is working fine and I can send the data to the database, but now I’ve just have no idea how can I make my js and php "working" together. I watched many tutorial on youtube but still can’t make it works. Anyone can help me or give me some advices please ?


88 thoughts on “post text on same page without refresh using FETCH and send the data to the database”

Leave a Comment