I want to create comments with AJAX, I do not know if this is the right way its my first time doing it. I have been searching google for hours and im really stuck.
What I want to achieve is to add a comment right after I click 'comment' button wihtout reloading the page.
I do not know how to create JSON array that will suit my needs.
This is my javascript:
$(function(){
var userComments = $('.userComments');
var commentsUrl="commentsLoad.php";
$.ajax({
type: 'GET',
url: commentsUrl,
dataType: "json",
success: function(komentarji){
//$.each ...
userComments.append("output...");
},
error: function(e){
console.log(e);
}
});
});
This is my PHP:
include('config.php');
$comments=array();
$commentsQuery = "SELECT * FROM komentarji";
$result = $conn->query($commentsQuery);
if($result->num_rows>0){
while($row = $result->fetch_assoc()){
$comments=array(
'id' => $row['id'],
'name' => $row['name'],
'text' => $row['text'],
'date' => $row['date'])
);
header('Content-type: application/json');
echo json_encode($comments);
}
}
-
What is not working ?Rayon– Rayon2015年09月21日 17:09:03 +00:00Commented Sep 21, 2015 at 17:09
-
$.ajax gets into error function if I have more than one comment in databaseTroix– Troix2015年09月21日 17:11:47 +00:00Commented Sep 21, 2015 at 17:11
-
No its because you are trying to return data to the ajax code more than onceRiggsFolly– RiggsFolly2015年09月21日 17:12:54 +00:00Commented Sep 21, 2015 at 17:12
4 Answers 4
The path that you're on is almost perfectly paved. Except the following you need to take note of:
- You should echo the result array in the JSON format outside the
whileloop. - Since you have specified the
dataTypeasjsonin your ajax call (and telling jQuery that you are expectingjsonback from the server),$.ajaxwill handle the headers itself and thereforeheader('Content-type: application/json');is not needed. A little tweak on the assignment that you're doing on
$commentsarray:$comments[] = array( // without [] you'll always end up with ONE comment 'id' => $row['id'], 'name' => $row['name'], 'text' => $row['text'], 'date' => $row['date'] );Just as you have hinted subtly, you need to iterate the returned array and
appendeach comment one-by-one:success: function(komentarji){ var parsedComments = JSON.parse(komentarji); //parse the result to Javascript readable objects $.each(parsedComments, function(){ userComments.append("id =>" + this.id + " name => " + this.name + " text =>" + this.text /* etc. */); //you can access each column key as javascript object key here }); }, //...
Note: There is a typo in the array assignment that you're doing, just remove the ) on the line 'date' => $row['date']) and you'll be fine.
Comments
First of all, move the returning of data back to the javascript code out of the while loop so you only do it once. Then change the script a little so that each comment is added to a new occurrence in the $comments array.
include('config.php');
$comments=array();
$commentsQuery = "SELECT * FROM komentarji";
$result = $conn->query($commentsQuery);
if($result->num_rows>0){
while($row = $result->fetch_assoc()){
$comments[] = array(
'id' => $row['id'],
'name' => $row['name'],
'text' => $row['text'],
'date' => $row['date'])
);
}
}
echo json_encode($comments);
exit;
3 Comments
You can't send more than one json output but you are sending one in each iteration of while loop
Also can't keep adding header
what you will be sending will look like
{"id": 3 , "name": "foo"}
{"id": 4 , "name": "bar"}
Note that there is no outer array wrapping these or comma separating them. Thus they are invalid json when sent together.
Put all the comments into one array and send that instead
1 Comment
Try this:
include('config.php');
$comments = array();
$commentsQuery = "SELECT * FROM komentarji";
$result = $conn->query($commentsQuery);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
array_push($comments, array('id' => $row['id'], 'name' => $row['name'], 'text' => $row['text'], 'date' => $row['date']));
}
return json_encode(array('status' => true, 'data' => $comments));
} else {
return json_encode(array('status' => false));
}
Also return status with response so that it will be easier to manipulate response