I am trying to do a commenting system with Jquery, AJAX and PHP. I am able to store the comments on the database, but I am having problems when I want to show them from the database. I believe I am doing something wrong when reading the data that is send from the .php file in JSON format.
Here is the code I am using.
index.html
<form id="form" method="post">
Name: <input type="text" name="name" id="name">
Comment: <textarea rows="5" cols="115" id="text"></textarea>
<input type="submit" id="submit" value="submit">
</form>
events.js
$('#form').on("click",'#submit',function(){
var name = $("#name").val();
var text = $("#text").val();
var dataString = 'name='+ name + '&text=' + text;
$.ajax({
url:'comments.php',
type:'POST',
cache: false,
data: dataString,
success: function(data){
alert("success");
$(".comment-block").append(data);
},
error:function(){
alert("failure");
}
});
comments.php
<?php
$name=$_POST['name'];
$text=$_POST['text'];
$conexion=mysql_connect("localhost","user","pass");
mysql_select_db("db_1",$conexion);
mysql_query("insert into comments (name,text) values ('$name','$text')");
$sql=mysql_query("SELECT * FROM comments");
$data=array();
$i=0;
while ($row=mysql_fetch_array($sql))
{
$data[$i]["name"]=$row[name];
$data[$i]["texr"]=$row[text];
$i++;
}
echo json_encode($data)
?>