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
Related
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
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>
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.
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);
Alright. I'm new to jEditable. Let me explain the issue i'm having with jEditable.
I have this simple table in my database -
id car make
1 panamera porsche
2 italia ferraris
3 avantador lamborghini
4 slk mercedes
And i'm gonna echo this table in a while loop and below is the code -
<script type="text/javascript">
<?php
$query2 = "SELECT * FROM inplace LIMIT 0, 6";
$result2 = mysql_query($query2) or die ('Query couldn\'t be executed');
$row2 = mysql_fetch_assoc($result2);
?>
$(function() {
$(".items").editable("handler.php", {
submitdata : {userid: "<?php echo $row2['id']; ?>"},
indicator : "<img src='img/indicator.gif'>",
tooltip : "Doubleclick to edit...",
event : "click",
onblur : "submit",
name : 'newvalue',
id : 'elementid',
});
});
</script>
</head>
<body>
<ul>
<?php
$query = "SELECT * FROM inplace LIMIT 0, 6";
$result = mysql_query($query) or die ('Query couldn\'t be executed');
while ($row = mysql_fetch_assoc($result)) {
echo '<li class="items" id="car">'.$row['car'].'</li>';
echo '<li class="items" id="make">'.$row['make'].'</li>';
}
?>
</ul>
In the above code, i'm passing newvalue(user edited) and elementid(car or make) in the jeditable script. And i also need one more identifier which helps identify the correct database id to update. So i'm trying to pass the database id in submitdata : {userid: "<?php echo $row2['id']; ?>"}. I'm not sure if that method is correct.
And below is the update query in "handler.php" file -
require("db.php");
function fail($msg) {
header('HTTP/1.0 404 Not Found');
die($msg);
}
$id = (int)#$_POST['userid'];
$field = #$_POST['elementid'];
$allowed_fields = array('car','make');
if (!in_array($field, $allowed_fields)) fail('Invalid or missing field.', 404);
$newvalue = $_POST['newvalue'];
$query = "UPDATE inplace SET `$field`='$newvalue' WHERE id=$id";
$result = mysql_query($query);
echo $newvalue;
So the issue here is, this submitdata : {userid: "<?php echo $row2['id']; ?>"} is passing only 1st id. That means its passing only one id. So even if you edit italia or avantador which belongs to ids 2 and 3 respectively, it updates 1st id. When i echo the query, whichever car you edit, it always reads as UPDATE inplace SETcar='volante' WHERE id=1. When i directly write 2 or 3 or 4 in the submitdata, it updates correctly. Its passing only one id. Someone suggested me to use like id="car-'.$row['id'].'" and then explode it and then use foo and stuff. I tried using it but didnt work for me. Looking for a solution for this.
You can make a custom attribute in your <li> tags containing the id number. Then in your jQuery, you just grab that value.
<script type="text/javascript">
$(function() {
$("li.items").each(function(index) {
$(this).editable("handler.php", {
submitdata : {userid: $(this).attr('carid')},
indicator : "<img src='img/indicator.gif'>",
tooltip : "Doubleclick to edit...",
event : "click",
onblur : "submit",
name : 'newvalue',
id : 'elementid',
});
});
});
</script>
</head>
<body>
<ul>
<?php
$query = "SELECT * FROM inplace LIMIT 0, 6";
$result = mysql_query($query) or die ('Query couldn\'t be executed');
while ($row = mysql_fetch_assoc($result)) {
echo '<li class="items" carid="'.$row['id'].'" id="car">'.$row['car'].'</li>';
echo '<li class="items" carid="'.$row['id'].'" id="make">'.$row['make'].'</li>';
}
?>
</ul>
Disclaimer: I didn't test this and i'm not 100% sure on the jQuery syntax.
[EDIT] I just changed it around to hopefully work using the $(this) selector to reference each specific <li>.
Your PHP code that is writing out the id
submitdata : {userid: "<?php echo $row2['id']; ?>"},
will only run on the server, and only run once, so all submits will only use that one value.
cillosis has one solution to your problem.