I have this PHP code:
//This is to retrieve all the posts inside the database, which will then be displayed using Javascript.
function retrieve_post($connection) {
$sql2 = "SELECT * FROM tbl_user_posts";
$result = mysqli_query($connection, $sql2);
echo json_encode($result);
//$data = array();
//while ($row = mysqli_fetch_assoc($result)) {
// $data[] = $row;
// echo json_encode($data);
//}
}
which is used to retrieve information from a database with 3 columns, and I need to retrieve the information from these rows and display them onto a html page using javascript. Here is the javascript I tried:
function displayPosts(){
$.ajax({
type: "POST",
url: "Main_Page.php",
success: function(response) {
JSON.stringify(response);
var data = JSON.parse(response);
for (var i = 0; i < data.length; i++) {
var row = data[i];
var name = row.name;
var user_post = row.user_post;
console.log(name, user_post);
}
}
});
}
$(document).ready(function() {
displayPosts();
});
However i get this error message in the console:
Unexpected end of JSON input
at JSON.parse ()
at Object.success (Main_Page.js:77:23)
with (Main_Page.js:77:23) being var data = JSON.parse(response).
Here is the HTML code that has all of the neccessary information inside of it for the form and where the information will need to go into (though right now my main priority is to display anything at all and will worry about the formating later):
<div class="user-post">
Create post:<br>
<form id="form" method="POST">
<textarea id = "create_post" name="create_post" rows="10" cols = "50"></textarea>
<input type="submit" class="post-button" value="PostButton" onclick = submit_post()>
</form>
</div>
<div class="posts" id="posted">
<div class="post">
<h3 id="existing_posts"><img src="default-pic.png" class="profile-pic" alt="Default Picture" width="50" height="50">Posts</h3>
<p>This is an example of a post. It will need to be boxed and made so that the name of the user goes above
the name of the likes and dislikes of the posts are to the left of the post and that the reply and report
functionalities are at the bottom right of the posts. It will also need a box around it to show where the post starts and ends.</p>
<div class="options">
<a href="">Like</a>
<a href="">Comment</a>
<a href="" class="report">Report</a>
</div>
</div>
2
Answers
I think you don’t need this line of code:
JSON.stringify(response);
in the ajax request
In my experience, this is what I usually do,
and in JavaScript,
Since you already encode the result in JSON, all you have to do in your JS is to parse it to an array/object… this is just in my experience.. I hope it helps