Reputation: 13
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)
?>
Upvotes: 0
Views: 174
Reputation: 8504
Try changing
$data[$i]["name"]=$row[name];
$data[$i]["texr"]=$row[text];
for
$data[$i]["name"]=$row['name'];
$data[$i]["text"]=$row['text'];
and as mentioned on other solutions and jQuery API pass the post data as an object better than a properly formatted string:
data Type: PlainObject or String Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).
Also, set
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
or the proper charset on $.ajax parameter if necessary (and urldecode appropriately).
And don't forget to validate and sanitize your data (filter input may be a good starting point).
jQuery will perform an intelligent guess so it's not necessary to set the dataType or json decode the response on success as mentioned, but you can do it anyways for clarity. From jQuery API again:
dataType (default: Intelligent Guess (xml, json, script, or html))
Upvotes: 1
Reputation: 566
you should try to handle json encode data on event.js file as-
success: function(data){
var test = jQuery.parseJSON(data);
var test1=test.data[0]['name'];
},
Upvotes: 0
Reputation: 2488
Use object to pass for data in $.ajax.
var dataString = {'name':name,'text':text};
Also use mysqli_* as mysql_* is depreciated.
Upvotes: 1