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)

My HTML

<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">
  </form>
  <div class="tweet-container">
    <p id="tweet-value">I want to show my data here</p>
  </div>
</div>
document.getElementById("submitTweet").addEventListener("click", postTweet);
function postTweet(e) {
  e.preventDefault();
  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) => {
      console.log("u");
    });
}

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);
    $query->execute([
      "ID_user" => $id_user,
      "tweet" => $tweet,
    ]);
  }
}

Controller

$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 ?

thanks

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

Leave a Comment