ejx
ejx

Reputation: 489

No refresh comments section with JS, AJAX, PHP

Recently started learning AJAX and I'm trying to make a comments section as seen on for ex. youtube where there is no page refresh necessary to load the submitted comment. Here's what I've got so far:

HTML:

<head><script src="JS/AJAX.js"></script>
<body>
  <form method="post" action="">
    User: <input type="text" id="name" /><br>
    Comment:<br>
    <textarea rows="5" cols="50" wrap="on" id="comment></textarea><br>
    <button id="submit">Submit</button>
  </form>

  <h3>Comments go here:</h3>
  <div id="commentarea"></div>
</body>

I don't know how I can insert comments into a database without refreshing the page. If I use let's say insert.php(inserts the data from the fields into the database) as the action it will refresh the page.

JS/AJAX(for now using XMLHttpRequest(); didn't include the try and catch block to find out the browser):

function ajaxFunction(){
  var ajaxRequest = new XMLHttpRequest();

  ajaxRequest.onreadystatechange = function(){
    if(ajaxRequest.readyState == 4){
      document.getElementById("commentarea").innerHTML = ajaxRequest.responseText;
      }
  }
  ajaxRequest.open("GET","fetch-data.php",true);
  ajaxRequest.send(null);
}

PHP(fetch-data.php):

<?php
$con = mysql_connect("localhost","root","") or die(mysql_error());

$mysql_select_db('localh',$con);

$query = mysql_query("SELECT User, UserComment FROM content");
if(!$query){
  die(mysql_error());
}

while($row = mysql_fetch_array($query)){
  echo "<h3>".$row['User']."</h3>"."<br>";
  echo "<p>".$row['UserComment']."</p>";
}

mysql_free_result($query);
mysql_close($con);
?>

Loaded separately or using "include" shows that the fetching process works.

As I understand this after I press submit, it should insert the comment and user into the database. Then ajax should use the fetch-data script to pull the data and then add it to the div with id "commentarea". I can't figure out how this would work, more precisely how I can make a call to the ajax function from the form.

Upvotes: 1

Views: 653

Answers (1)

Micha Schwab
Micha Schwab

Reputation: 798

you can call the javascript function in the form action="..." property. if that function returns false, the form wont be submitted by usual post request, but you can use the input data for your ajax request.

Upvotes: 1

Related Questions