get contents with ajax and display them directly without refreshing the page - php

I have created a blog in php. For each comment the user can press a Favorite/Unfavorite button (if want) to Favorite/Unfavorite a post. My button works perfect. The only problem I got is that when user press Favorite/Unfavorite... I dont get the number of Favorites/Unfavorites for this post. In order to get this, each time I have to refressh the page. Some people told me that I need to use Ajax in order to do this.
I use table likes, to hold favorites for each post: likes(like_id, user, the_comment_id)
I use table comments for aeach post: comments(comments_id, comment, user)
This is my php code:
<?php
$comment_id = $row['comments_id'];
// ... code above
//button for favorite and unfavorite
$get_button = mysql_query(" SELECT * FROM `likes` WHERE `user`='$session_user_id' AND `the_comment_id`='{$row['comments_id']}' ");
$get = mysql_fetch_assoc($get_button);
if($get==""){
$comments .= "<a role='button' class='button' id='like$comment_id' style='color:grey;'>Favorite</a>";
}else if($get!=""){
$comments .= "<a role='button' class='button' id='unlike$comment_id' style='color:grey;'>Unfavorite</a>";
}
// place favorites for this comment here
$comments .= " $total_favorites ";
?>
This is my jquery:
<script>
$(document).ready(function(){
$("#like<?php echo $comment_id; ?>").click(function() {
var id = "<?php echo $comment_id; ?>";
$.post("parse.php",{like:id}, function(data){
$("#like<?php echo $comment_id; ?>");
$(".button<?php echo $comment_id; ?>").html(data);
});
$(this).hide().attr("Disabled", "True").text("Favorite done!").show();
});
$("#unlike<?php echo $comment_id; ?>").click(function() {
var id = "<?php echo $comment_id; ?>";
$.post("parse.php",{unlike:id}, function(data){
$("#unlike<?php echo $comment_id; ?>");
$(".button<?php echo $comment_id; ?>").html(data);
});
$(this).hide().attr("Disabled", "True").text("Unfavorite done!").show();
});
});
</script>
This is my parse.php code:
<?php
if(isset($_POST['like'])){
$id = $_POST['like'];
mysql_query("INSERT INTO likes VALUES ('', '$session_user_id', '$id') ");
}
if(isset($_POST['unlike'])){
$id = $_POST['unlike'];
mysql_query(" DELETE FROM likes WHERE `user`='$session_user_id' AND `the_comment_id`='$id' ");
}
$favorites = mysql_query(" SELECT * FROM `likes` WHERE `the_comment_id`='{$row['comments_id']}' ");
$total_favorites = mysql_num_rows($favorites);
?>

You would need to return something from the parse.php script. The data variable will not contain the count unless you either echo it out directly or return JSON and parse in your jQuery function prior to setting the .html(data) values.

You are right, AJAX is the way to go. Note that AJAX is known by multiple names:
XMLHttpRequest -- javascript
AJAX
$.ajax() -- the jQuery superset
$.get() -- a shortcut to $.ajax() with TYPE: "GET"
$.post() -- a shortcut to $.ajax() with TYPE: "POST"
$.load() -- see Difference between $("#id").load and $.ajax?
Here are some examples that will get you started on AJAX:
A simple example
More complicated example
Populate dropdown 2 based on selection in dropdown 1

Further to what Lucas said, change your code to look like this:
<?php
if(isset($_POST['like'])){
$id = $_POST['like'];
mysql_query("INSERT INTO likes VALUES ('', '$session_user_id', '$id') ");
}
if(isset($_POST['unlike'])){
$id = $_POST['unlike'];
mysql_query(" DELETE FROM likes WHERE `user`='$session_user_id' AND `the_comment_id`='$id' ");
}
$favorites = mysql_query(" SELECT * FROM `likes` WHERE `the_comment_id`='{$row['comments_id']}' ");
$total_favorites = mysql_num_rows($favorites);
$out = '<h1>Found In Database</h1>';
$out .= '<p>You received ' .$total_favorites. ' favorites.';
echo $out;
?>

If this doesn't work, then please post the relevant HTML so that we can accurately target your DOM elements:
$(document).ready(function(){
$("[id^=like]").click(function() {
var window.id = $(this).attr('id').split['e'][1];
$.post("parse.php",{like:id}, function(data){
$("#like"+id).find(".button").html(data);
}); //END .post
$(this).hide().attr("Disabled", "True").text("Favorite done!").show();
}); //END like.click
$("[id^=unlike]").click(function() {
var window.id = $(this).attr('id').split['e'][1];
$.post("parse.php",{unlike:id}, function(data){
$("#unlike"+id).find(".button").html(data);
}); //END .post
$(this).hide().attr("Disabled", "True").text("Unfavorite done!").show();
}); //END #unlike.click
});
Notes:
We use $("[id^=unlike]") as the selector - this means: get the DOM element with an ID that starts with "unlike"
$(this).attr('id').split['e'][1] means:
a. Get the ID attribute ("like5" or "unlike123")
b. Break it into an array at teh 'e' char: lik and 5 -or- unlik and 123
c. Grab the 2nd array element (the number: 5 or 123)
d. Stick it in a global variable called id

Related

Select from mysql is not working in jQuery fancybox

Fancybox script POST my form data to go.php page then open go.php in fancybox iframe
<script>
$(document).ready(function() {
$("#fancybox-manual-b").click(function() {
$.post('go.php', $(this).parent().serialize())
.done(function() {
$.fancybox.open({
href : 'go.php',
type : 'iframe',
padding : 5
});
});
});
});
</script>
<select name="country">
<option value="US">US</option>
<option value="EU">EU</option>
</select>
<input type="button" value="Calculate" id="fancybox-manual-b"/>
in go.php, I receive the POST data from the form correctly and when I try to insert this data into DB, it's been inserted correctly too!
But now I want to select * from my DB table to echo all the data in the table where column = POST data, but this query doesn't work!
<?php
$country = $_POST[country];
mysql_query("INSERT INTO calculator (country) VALUES ('$country')"); //Works Correctly
$result = mysql_query("SELECT * FROM calculator WHERE country='$country' ORDER BY ID ASC");
while($row = mysql_fetch_array($result)){
echo $row['ID']." ".$row['country'];
} //Nothing appear
?>
Please checkout this method,
$country = $_POST[country];
if(mysql_query("INSERT INTO calculator (country) VALUES ('$country')"));
{
$result = mysql_query("SELECT * FROM calculator WHERE country='$country' ORDER BY ID ASC");
while($row = mysql_fetch_array($result)){
echo $row['ID']." ".$row['country'];
}
}
I used the same code you shared. But added an additional if loop on mysql_query part. It will make sure your select works after data being inserted.
We have to use jquery ajax to send form data to the php page with POST method then receive back any printed data from the php page in the ajax instead of the console.
We will open the fancybox iframe into ajax success instead of the console.
<script type="text/javascript">
$(document).ready(function() {
$("#fancybox-manual-b").click(function() {
$.ajax({
type: 'POST',
url: 'go.php',
data: $(this).parent().serialize(),
success: function(data){
$.fancybox(data);
},
fail:function(data){console.info(data)}
});
});
});
</script>

Show more result from database with jQuery and AJAX

I'm trying to create news block with AJAX in my template. so i wrote a simple code, in HTML Part:
Show Posts
<div id="result"></div>
jQuery Part:
function ShowPost(){
$.post(dir + 'engine/ajax/posts.php', {action:"showpost"},
function(data) {
$("#result").html(data);
});
};
PHP Part:
if ($_POST['action'] == "showpost") {
$db->query( "SELECT title FROM post LIMIT 0,5 " );
while ( $row = $db->get_row() ) {
echo $row['title']."<br>";
}
}
Question is, how i can get more result after first click? for example, after first click on Show Posts link, i can show the 5 news from database. after second click on Show Posts link i need to show 6 to 10 news, in third click get result from 11 to 15 and continue ...
i hope you understand my question.
Based on your implementation you need to keep track how many items you have shown and pass the page number in. For example:
jQuery Part:
var pageNumber = 0;
function ShowPost() {
pageNumber++;
$.post(dir+ 'engine/ajax/posts.php', {action:"showpost", pageNum: pageNumber},
function(data) {
$("#result").html(data);
});
};
Disclaimer: I m not a PHP developer so please treat teh code below as pseudo-code.
PHP Part:
if ($_POST['action'] == "showpost") {
var pageSize = 5;
var pageNumber = $_POST['pageNumber'];
var from = (pageNumber - 1) * pageSize;
var to = pageNumber * pageSize;
$db->query( "SELECT title FROM post LIMIT " + from + "," + pageSize);
while ( $row = $db->get_row()) { echo $row['title']."<br>"; }
}
Just implement the pagination limit in ur query
var offset = -5;
function ShowPost(){
offset = offset + 5;
$.post(dir + 'engine/ajax/posts.php', {action:"showpost",offset:offset},
function(data) {
$("#result").html(data);
});
};
PHP part
if ($_POST['action'] == "showpost") {
$vOffset = $_POST['offset'];
$db->query( "SELECT title FROM post LIMIT $vOffset,5 " );
while ( $row = $db->get_row() ) {
echo $row['title']."<br>";
}
}
Take a hidden field in html and update it's value after every success call and when next time you call for next record send that value in post.
<input type="hidden" name="limit" value="5">
Show Posts
<div id="result"></div>

Saving sortable to mysql with ajax jquery and php

I have a page with multiple drag&drop boxes, that works great, the thing that does not work are the links in the boxes. I would appreciate if someone could help me :). So I have a page where people can drag&drop boxes (it works fine, as I said before), the links inside the boxes are sortable aswell, but I can't seem to get them to save the values to mysql. I think there is a conflict between the two drag&drops, maybe I am doing it wrong, 'cause I haven't used ajax and jquery before.
//here is the jquery where I need to add some ajax
$(function() {
$('.dragbox-content').sortable({
connectWith: '.dragbox-content',
update: function(event, ui) {
var order=$(this).attr('id');
alert(order); // I get the order alert and it has one value that I need, but I need the sort order aswell
}
});
});
//this is the <div> that has the links in them and mysql query that gets the values
//from two different databases, one is for the boxes and the other for links.
//boxes db id = links title_id
echo '<div class="dragbox-content" id="order'.$widget['id'].'"';'>''</div>';
$sql10 = "SELECT u.*, w.id, w.link_address, w.link_name FROM db_boxes u LEFT
JOIN db_links w ON u.link_id = w.id WHERE
(u.username = '$username' AND u.link_id !='0' AND w.title_id = '".$widget['id']."'
AND w.link_name !='pilt' AND w.rights = '0') OR
(u.username = '$username' AND u.link_id !='0' AND w.title_id = '".$widget['id']."'
AND w.link_name !='pilt' AND w.rights LIKE '%26%') ORDER BY w.id ASC";
$result10 = mysql_query($sql10) or die (mysql_error());
while ($row = mysql_fetch_array($result10)) {
$link_id = $row['id'];
$link_address = $row['link_address'];
$link_name = $row['link_name'];
$title_id = $row['title_id'];
?>
<div class="move" id="<?php echo $link_id;?>">
<span class="link_style">
<div><?php echo $link_name;?> </div</span></div>
I just need somebody to tell me how can I save tile_id and sort_order to boxes database with ajax on every click a user makes on that page
See my example below:
http://jsfiddle.net/gRoberts/vMy7r/
$(function () {
$('ul').sortable({
update : function(e, ui) {
var ul = $(ui.item).closest('ul');
var index = 0;
var toPost = {};
ul.find('> li').each(function() {
index++;
$(this).find('input').val(index);
toPost[$(this).find('input').attr('name')] = index;
});
$.ajax({
url : '/echo/json/',
data : toPost,
type : 'POST',
dataType : 'json',
success : function(resp) {
alert(resp);
},
error : function() {
alert('There was a problem');
}
});
}
});
});
​
The above example can be used in two ways, if you remove the $.ajax it will update hidden form fields which you can then post normally.

Re-aligning return value from php function in the html

I have am trying to create a simple voting page. There are a few links on each side and when the user click the up arrow the vote is counted and the vote count value is increased. Everything works right now except that when the vote is increased the new value appears on top of the upvote arrow (which makes sense since I am echoing the new value). I have not been able to figure out how to set the updated vote count into the SPAN which should show the vote count.
Here is the code:
HTML
<?php
$sql=mysql_query("SELECT * FROM discussion_links WHERE link_side = 'Michigan'");
while($row = mysql_fetch_array($sql)) {
$link_id=$row['link_id'];
$url=$row['link_url'];
$title=$row['link_title'];
$source=$row['link_source'];
$votes=$row['vote_count'];
?>
<div class="top-links-wrapper">
<div class="link-info">
<a class="link-title" href="http://<?php echo $url ?>"><?php echo $title . "</a>"; ?>
<p class="link-source"><?php echo $source . "</p>" ?>
</div>
<div class="link-vote-wrapper">
<div class="link-votes">
<span><?php echo $votes; ?></span>
</div>
</div>
</div>
<?php
}
?>
I would like to replace the value returned from the PHP function below into the SPAN in the code above.
PHP
<?php
$ip=$_SERVER['REMOTE_ADDR'];
if($_POST['id']) {
$id=$_POST['id'];
$id = mysql_escape_String($id);
//Verify IP address in Voting_IP table
$ip_sql=mysql_query("select ip_add from Voting_IP where link_id_fk='$id' and ip_add='$ip'");
$count=mysql_num_rows($ip_sql);
if($count==0) {
// Update Vote.
$sql = "update discussion_links set vote_count=vote_count+1 where link_id='$id'";
mysql_query( $sql);
// Insert IP address and Message Id in Voting_IP table.
$sql_in = "insert into Voting_IP (link_id_fk,ip_add) values ('$id','$ip')";
mysql_query( $sql_in);
}
else {
echo "<script>alert('You have already voted');</script>";
}
$result=mysql_query("select vote_count from discussion_links where link_id='$id'");
$row=mysql_fetch_array($result);
$up_value=$row['vote_count'];
echo $up_value;
}
?>
This $up_value is the one I would like to replace the current vote count in the HTML.
jQuery
<script type="text/javascript">
//<![CDATA[
var $j = jQuery.noConflict();
$j(function() {
$j(".vote").click(function() {
var id = $j(this).attr("id");
var name = $j(this).attr("name");
var dataString = 'id='+ id ;
var parent = $j(this);
if (name=='up') {
$j(this).fadeIn(200).html('<img src="dot.gif" />');
$j.ajax({
type: "POST",
url: "up_vote.php",
data: dataString,
cache: false,
success: function(html) {
parent.html(html);
}
});
}
return false;
});
});
//]]>
</script>
Thanks and any help would be greatly appreciated.
Assuming that you are returning the appropriate (int) total back in the success function,
then you should just set the InnerHTML of the span element to that value
It would be convenient if you were to give each link-votes element a unique ID and use that id to change the InnerHTML of the span element. on ajax success
Since you are already associating the vote_id with the event handler, then you
could simply add a prefix to the span id element, and then in the success function,
call something like this:
$("#myPrefix"+id).html(html);

reform Jquery serialize li with php

i'm having trouble with the serialize Jquery fonction.
Fist, i create my li element with a php script, my data are written in my database (with "id", "contenu", "position") and catch it in my html :
<article>
<ul id="columns">
<?php
$req01=mysql_query("SELECT * FROM mytable ORDER BY id DESC");
$i=0;
while ($res01=mysql_fetch_array($req01)){
$i++;
echo '
<li class="column" id="listItem_'.$res01["position"].'" draggable="true">
<p>'.$res01["contenu"].'</p>
</li>';
}
?>
</ul>
</article>
And here's my script
$(document).ready(function() {
$("#columns").sortable({
column : '.column',
update : function () {
var order = $('#columns').sortable('serialize');
$("#info").load('structure-reform.php?'+order);
//alert("Data Loaded: " + order);
}
});
});
</script>
And here the way i update my DB when my li order is changing
foreach ($_GET['listItem'] as $position => $item) :
$list[] = "$position, $item";
$req03=mysql_query("UPDATE mytable SET position='".$position."' WHERE id='".$item."'");
$result = mysql_query($req03);
endforeach;
The thing is that, when i reload my page, my list isn't sorted the right way...How can i do in order to keep my list in the last order ?
Thanks !
Your logic wasn't correct.
replace your javascript with this:
$("#columns").sortable({ update: function() {
var order = $(this).sortable("serialize");
$.post("structure-reform.php", order);
}
});
replace your list html with this
<li class="column" id="listItem_'.$res01['id'].'" draggable="true" rel="'.$perso.'">
<p>'.$res01["contenu"].'</p>
</li>';
replace your while loop with this
$listingCounter = 1;
foreach ($_POST['listItem'] as $recordIDValue) {
$query = "UPDATE structure SET position = " . $listingCounter . " WHERE id = " . $recordIDValue;
mysql_query($query) or die('Error, insert query failed');
$listingCounter = $listingCounter + 1;
}
echo 'If you refresh the page, you will see that records will stay just as you modified.';
You'll either want to save the order parameter in PHP - store it in $_SESSION, or, set a cookie on the user's computer and retrieve that to sort.
why you don't use jquery ajax using $.ajax() ? may be there is problem with serialize(), have you tried this one ?
$("#columns").sortable({
column : '.column',
update : function () {
var order = $(this).sortable('serialize');
$.ajax({
url : 'structure-reform.php',
type: 'GET',
data: order,
success:function(res){
alert('Data Loaded '+res);
}
});
}
});
and fot the first time, you should debug your parameter from ajax request, using php it quite simple
<?php
print_r($_GET);
?>
then you can do the rest when you have know what paramter are given there

Categories