Ajax/jQuery Comment System - php

Building a comment system with Ajax and JQuery and I want the div the comments are in to reload after a comment is added. It posts just fine. This is what I have so far.
The function getComments queries the database and generates the html
$.ajax({
type: "POST",
url: "post_comment.php",
data: dataString,
cache: false,
success: function(html){
????????? What should go here... it is a div with id#commentBody
}
<div id="commentBody">
<ul>
<?php
$q = "SELECT * FROM comment WHERE parent_id = 0 AND idpost = $postID";
$r = mysql_query($q);
while($row = mysql_fetch_assoc($r)):
getComments($row,$postID,$custID);
endwhile;
?>
</ul>
</div>

Since you're regenerating the entire div I would use replaceWith.
$('#commentBody').replaceWith(html);

When you post it, you should return the data you want from your server side script. Then you can use the .html() jQuery function to update your div.
So, like:
$('#commentBody').html(html);
You could also return just the latest comment (optionally as a JSON object) and then just use the .append() method to add it to your #commentBody.
I would create a JSON object which has a status property and a data property. When the status is -1 (or whatever) there was an error adding the comment and you could put a message in the data property. When the status is 0, it was successful and the latest comment information would be available available in the data property.
Example
PHP
//Check postback variables, add comment and retrieve
// comment information (such as ID) if necessary
if (postedsuccessfully) {
$ary = array("status" => 0,
"data" => array("id" => $commentidvar,
"user" => $commentuser,
"text" => $comment)
);
echo json_encode($ary);
} else {
$ary = array("status" => -1,
"data" => "There was a problem adding your comment.");
echo json_encode($ary);
}
JavaScript
success: function(json){
if (json.status == 0) {
$mydiv = $('<div>');//construct your comment div using json.data.id,
//json.data.user, and json.data.text
$('#commentBody').append($mydiv);
} else {
alert(json.data);
}
}

Related

Pass value from JQUERY to PHP ,and return a JSON

When call php from jquery via ajax ,have any response .I changed the dataTypeand put jsoninstead html.I´m thinking the issue is that,for the ajax call never trigger the php code,it seems $_POST['retriveForm'] never carries a value.
PHP:
if(isset($_POST["retriveForm"])) {
$data_json =array();
$id = $_POST['retriveForm'];
$sql = "SELECT * FROM mytable WHERE Id = $id";
while ($row = mysqli_fetch_array($db->consulta($sql)) {
$data_json = array('item1' => $row['item1'],'item2' => $row['item2']) ;
}
$data_json['item_array'] = call_a_function_return_array();//this works
echo json_encode($data_json);
}
and jQuery :
$(document.body).on('click', '.edit', function() {
var id = $(this).data('id');
$.ajax({
type: "POST",
url: "is_the_same_page.php",
data: {
retriveForm: id
},
dataType: "json",
success: function(response) {
$('#myForm').find('input').eq(1).val(response.item1);
}
});
});
Code is all in the same page if that may be important.
Since the AJAX code is in the same script, make sure you don't output any of the normal HTML in this case. Your PHP code should be at the very beginning of the script, before any HTML is output. And you should exit the script after echoing the JSON. Otherwise your JSON will be mixed together with HTML, and jQuery won't be able to parse the response.
Also, you're not correctly adding to $data_json in your loop. You're overwriting the variable each time instead of pushing onto it.
<?php
// code here to set up database connection
if(isset($_POST["retriveForm"])) {
$data_json =array();
$id = $_POST['retriveForm'];
$sql = "SELECT * FROM mytable WHERE Id = $id";
while ($row = mysqli_fetch_array($db->consulta($sql)) {
$data_json[] = array('item1' => $row['item1'],'item2' => $row['item2']) ;
}
$data_json['item_array'] = call_a_function_return_array();//this works
echo json_encode($data_json);
exit();
}
?>
<html>
<head>
...
Then in the success function, you'll need to index the elements of response, since it's an array, not a single object.

Ajax div to refresh on success not working

I have a DIV which contains how many likes fetching from Mysql database.
I click on button which says like and it will go through ajax function like(id1) with parameter.
Ajax use page likes.php and does all job adding to database. And it gives out JSON data as feedback with code zero if successful. And one if fails.
In success section ajax _js.code is one then its already liked. Thus shows us message. But my problem is I cannot refresh DIV likes when code is zero which is success. It either goes to top of the page instead of staying at DIV likes.
For information it also appends hash TAG at the end of URL.
Button line, I want like button which should work as facebook or other major app does. Without moving page on top. And update like button immediately when clicked.
My main page
<input type="checkbox" id="like" onclick="like(<?php echo $_SESSION["id"];?>);"/>
<div id="likes">
<?php
$like = 0;
$conditions = "WHERE id = $_SESSION[id]";
echo $total = $ll->get_likes($conditions); //displaying how many likes
?>
</div>
Ajax
<script>
function like(id1) {
$.ajax ({
type: "POST",
url: "likes.php",
data: {id: id1 },
success: function(feedback) {
var _js = jQuery.parseJSON(feedback);
$("#likes").html(_js.message); //printing message here
$("#likes").attr("class", ""); //resetting class of CSS
if( _js.code == 0) {
/**I want to refresh DIV likes after this **/
} else {
$("#likes").addClass("red"); //This is working fine, i get message when already liked
}
}
});
}
likes.php
<?php
if ( isset($_POST)) {
//All PHP staff goes here and its working
if ( $success) {
$return = array (
'code' = 0,
'message' = ""
);
} else {
$return["code"] = 1;
$return["message"] = "You already liked";
}
echo json_encode($return);//Converting PHP into JSON format
}
?>
change following in HTML and JS
<input type="checkbox" id="like" onclick="return like(<?php echo $_SESSION["id"];?>);"/>
<script>
function like(id1) {
$.ajax ({
type: "POST",
url: "likes.php",
data: {id: id1 },
success: function(feedback) {
var _js = jQuery.parseJSON(feedback);
$("#likes").html(_js.message); //printing message here
$("#likes").attr("class", ""); //resetting class of CSS
if( _js.code == 0) {
/**I want to refresh DIV likes after this **/
} else {
$("#likes").addClass("red"); //This is working fine, i get message when already liked
}
}
});
return false;
}
#tashi,
There is a syntax error in likes.php. Use => operator when declaring arrays. The code should be as follows.
$return = array (
'code' => 0,
'message' => ""
);
if you want to display no of likes on success the change your code as follows
In likes.php
<?php
if ( isset($_POST)) {
//All PHP staff goes here and its working
if ( $success) {
$return = array (
'code' => 0,
'message' => "",
'likes_count' => $likes_count //get updated likes count from db
);
} else {
$return["code"] = 1;
$return["message"] = "You already liked";
//here you do not need to send the like count
}
echo json_encode($return);//Converting PHP into JSON format
}
?>
javascript code
function like(id1) {
$.ajax ({
type: "POST",
url: "likes.php",
data: {id: id1 },
success: function(feedback) {
var _js = jQuery.parseJSON(feedback);
$("#likes").html(_js.message); //printing message here
$("#likes").attr("class", ""); //resetting class of CSS
if( _js.code == 0) {
/**I want to refresh DIV likes after this **/
$('#likes').html(_js.likes_count);//this will update your likes count
} else {
$("#likes").addClass("red"); //This is working fine, i get message when already liked
}
}
});
}

Error with JSON Ajax get method

I am using a jquery ajax get method to fetch information from the server however I am having trouble parsing the information so that I may use it. My website has a gallery of products that will filter its items based on category.
Here is the jQuery ajax function:
$('.category').click(function() {
var category;
if ($(this).hasClass('Shirts')) {
category = 'shirts';
}
if ($(this).hasClass('Hats')) {
category = 'hats';
}
if ($(this).hasClass('Acc')) {
category = 'acc';
}
$.ajax({
type: 'GET',
url: 'galleryfetch.php',
data: { 'category' : category },
dataType: 'json',
success: function(data) {
arr = $.parseJSON(data);
alert(arr);
}
});
});
This is the php script that the information is posted to:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$category = $_GET['category'];
$conn = mysqli_connect('localhost', '*****', '*****', 'clothing');
$rows = mysqli_query($conn, "SELECT * FROM products WHERE category = '".$category."'");
while ($row = mysqli_fetch_array($rows)) {
$arr[] = $row;
}
echo json_encode(array('data' => $arr));
}
I using the alert in the success function to see if the information is passed succesfully but at the moment there is no alert and i get an:
Unexpected token o error.
I'm not sure if I'm parsing the information correctly or if Im not correctly using JSON
tl;dr: $.parseJSON(data); should be removed.
Your server is returning JSON (but claiming it is sending HTML, you should have header("Content-Type: application/json")).
You have told jQuery to ignore the claim that it is HTML and parse it as JSON. (This would be redundant if you fixed the above problem)
dataType: 'json',
The parsed data is passed to your success function.
You then pass that data to JSON.parse so it gets converted to a string (which will look something like [ [Object object], ... and is not valid JSON) and then errors.
Remove:
arr = $.parseJSON(data);
And just work with data.

My ajax JSON object is recognized as "Undefined"

I am having troubles with my ajax call. When I try to alert the result it keeps resulting as Undefined.
Both alerts are resulting to undefined.
I am not too sure if I am coding this correctly, please help me if I am.
Q: If I am accessing it incorrectly, how exactly would I access the skill property/index.
JQUERY/JSCRIPT
$(document).ready(function(){
// Skill sort on change
$('#order_by').on('change', function() {
$.ajax({
type: "POST",
url: "sort_skill_be.php",
dataType: "json",
data: {skill:this.value}
}).done(function(result){
alert(result[0].skill);
})
});
});
PHP FILE: This method receives a statement and places an "object" array to an overall array.
function helpFetchPostInfo($stmt){
$results = $stmt->fetchAll();
$recent_posts = array();
foreach ($results as $row){
$post = array(
'username' => $row['username'],
'steam' => $row['steam'],
'skill' => $row['skill'],
'description' => $row['description'],
'date' => $row['date'],
);
array_push($recent_posts, $post);
}
return json_encode($recent_posts);
}
Thank you for the assistance it is much appreciated
function sortSkill($skill){
// If All skill is selected display posts normally
if ($skill == 'All'){
displayPosts();
exit;
}
$db = connect();
$sql = "SELECT * FROM users LEFT JOIN posts
ON users.idUsers = posts.fkuser
WHERE posts.fkuser IS NOT NULL and users.skill=:skill
ORDER BY date DESC";
$stmt = $db->prepare($sql);
$stmt->execute(array(':skill' => $skill));
if ($stmt->rowCount() == 0){
// Nothing has returned
unset($_SESSION['recent_posts']); // Reset session of posts if no posts appear.
}
else
{
$recent_posts = helpFetchPostInfo($stmt);
return $recent_posts;
}
}
Sort skill is being called in a seperate php file called sort_skill_be.php, which is called from the jquery when a selection is changed.
<?php
session_start();
include 'database.php';
$skill_sort = $_POST['skill'];
sortSkill($skill_sort);
header('Location:index.php');
?>
EDIT: added JSON datatype to jquery
Now my problem is the alert is not being called at all anymore.
Looks like you are not providing the dataType attribute in your ajax method.
dataType: "json",
Either do that or parse your result to JSON before accessing it.
I don't see any issue the way you are trying to access the object.

Cannot populate form with ajax and populate jquery plugin

I'm trying to populate a form with jquery's populate plugin, but using $.ajax
The idea is to retrieve data from my database according to the id in the links (ex of link: get_result_edit.php?id=34), reformulate it to json, return it to my page and fill up the form up with the populate plugin. But somehow i cannot get it to work. Any ideas:
here's the code:
$('a').click(function(){
$('#updatediv').hide('slow');
$.ajax({
type: "GET",
url: "get_result_edit.php",
success: function(data)
{
var $response=$(data);
$('#form1').populate($response);
}
});
$('#updatediv').fadeIn('slow');
return false;
whilst the php file states as follow:
<?php
$conn = new mysqli('localhost', 'XXXX', 'XXXXX', 'XXXXX');
#$query = 'Select * FROM news WHERE id ="'.$_GET['id'].'"';
$stmt = $conn->query($query) or die ($mysql->error());
if ($stmt)
{
$results = $stmt->fetch_object(); // get database data
$json = json_encode($results); // convert to JSON format
echo $json;
}
?>
Now first thing is that the mysql returns a null in this way: is there something wrong with he declaration of the sql statement in the $_GET part? Second is that even if i put a specific record to bring up, populate doesn't populate.
Update:
I changed the populate library with the one called "PHP jQuery helper functions" and the difference is that finally it says something. finally i get an error saying NO SUCH ELEMENT AS
i wen into the library to have a look and up comes the following function
function populateFormElement(form, name, value)
{
// check that the named element exists in the form
var name = name; // handle non-php naming
var element = form[name];
if(element == undefined)
{
debug('No such element as ' + name);
return false;
}
// debug options
if(options.debug)
{
_populate.elements.push(element);
}
}
Now looking at it one can see that it should print out also the name, but its not printing it out. so i'm guessing that retrieving the name form the json is not working correctly.
Link is at http://www.ocdmonline.org/michael/edit_news.php with username: Testing and pass:test123
Any ideas?
First you must set the dataType option for the .ajax call to json:
$.ajax({dataType: 'json', ...
and then in your success function the "data" parameter will already be a object so you just use it, no need to do anything with it (I don't know why you are converting it into a jQuery object in your code).
edit:
$( 'a' ).click ( function () {
$( '#updatediv' ).hide ( 'slow' );
$.ajax ( {
type: "GET",
url: "get_result_edit.php",
success: function ( data ) {
$( '#form1' ).populate ( data );
},
dataType: 'json'
} );
$( '#updatediv' ).fadeIn ( 'slow' );
return false;
}
also consider using $.getJSON instead of $.ajax so you don't have to bother with the dataType
Try imPagePopulate (another jquery plugin). It may be easier to use:
http://grasshopperpebbles.com/ajax/jquery-plugin-impagepopulate/

Categories