jEditable is taking only one id - php

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.

Related

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

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

using ajax to get further mysql data using data already retrieved fro database

I'm trying to build a product catalog where clients can select a product and be presented with product specifications and price. now the first thing i do is query all the products in the database omnicon_prod. from there i build an unordered list of items like such
$query = "SELECT name, id, price, image, cost_per FROM products";
$result = mysqli_query($db_connect,$query);
while($row = mysqli_fetch_assoc($result)) {
echo '<li class="product" style="list-style:none;margin-left:10px;margin-right:10px; width:150px;float:left;" id="'.$row['id'].'">
<img class="productImage" style="background-color:#f2f2f2;width:150px;padding:10px;float:left;" src="'.$row['image'].'main-image.jpg">
<div class="productText" style="width:100%;text-align:center;">
<div class="price" style="color:#fca204;font-weight:500;font-size:20px;font-family: "Conv_Geogtq-Th", sans-serif;">'.$row['price'].' <span style="color:#959595; font-size:14px; font-weight:100;">/'.$row['cost_per'].'</span>
</div>
<div class="name" style="color:#959595;font-weight:100;font-size:14px;font-family: "Conv_Geogtq-Th", sans-serif;">'.$row['name'].'
</div>
</div>
</li>';
}
What i would like to do now is attach an anchor to each list item and should the client select an item that comes from the database they would be presented with further information such as the description etc. now i know this should be done with ajax but i'm not sure how as i am relatively new to it. I would like to trigger the ajax possibly by using the onClick even on an ancho tag. this is what i have tried thus far.
the ajax
function ajaxfunction(productID)
{
$.ajax({
url: 'php-includes/products.php?productID=' + productID,
success: function(data) {
$("#productSpec").html(data);
}
});
}
the products.php page
<?php
include_once "connect.php";
$query = "SELECT name, price, image, cost_per FROM products WHERE `id` = ". mysqli_real_escape_string($_GET["ProductID"]);
$result = mysqli_query($db_connect,$query);
while($row = mysqli_fetch_assoc($result)) {
//the content from the database that matches the id of the selected item
}
?>
please can someone help me with regards to where i'm going wrong and if it's wise to use an anchor tag to trigger this event. I basically adopted and tried to incorporate the dynamic multi-level select form option into one that uses a list to grab data...
For the ajax call you can check out these pages here and here
Basically you add the data you want to send (object or string) as a parameter.
Thanks Ruben i managed to figure it out hehe. i'd like to share the final result. if there are any errors or security risks please advise me as to how i could improve the code...
The Quote.php exerpt
<?php
include_once "php_includes/connect.php";
$query = "SELECT name, id, price, image, cost_per FROM products";
$result = mysqli_query($db_connect,$query);
while($row = mysqli_fetch_assoc($result)) {
echo '<li class="product" style="list-style:none;margin-left:10px;margin-right:10px; width:150px;float:left;" id="'.$row['id'].'">
<img class="productImage" style="background-color:#f2f2f2;width:150px;padding:10px;float:left;" src="'.$row['image'].'main-image.jpg">
<div class="productText" style="width:100%;text-align:center;">
<div class="price" style="color:#fca204;font-weight:500;font-size:20px;font-family: "Conv_Geogtq-Th", sans-serif;">'.$row['price'].' <span style="color:#959595; font-size:14px; font-weight:100;">/'.$row['cost_per'].'</span>
</div>
<div class="name" style="color:#959595;font-weight:100;font-size:14px;font-family: "Conv_Geogtq-Th", sans-serif;">'.$row['name'].'
</div>
</div>
</li>';
}
?>
THE AJAX SCRIPT
<script>
$(".product").on('click',function(){
the_id = $(this).attr('id');
$.ajax({
type: "POST",
url: "php_includes/productspec.php?id=" + the_id,
success: function(data){
$("#productSpec").html(data);
}
});
});
</script>
THE productspec.php PAGE
<?php
include_once "connect.php";
$productid = mysqli_real_escape_string($db_connect, $_GET['id']);
$query = "SELECT * FROM products WHERE `id` = " . $productid;
$result = mysqli_query($db_connect,$query);
while($row = mysqli_fetch_assoc($result)) {
echo '<p>'.$row['id'].'</p>'; //just a test result i'd like to receive
echo '<p>'.$row['name'].'</p>'; //just a test result i'd like to receive
echo '<p>'.$row['price'].'</p>'; //just a test result i'd like to receive
}
?>
thanks so much Ruben. I really appreciate the help you've given me and that you provided the tools to help me figure it out myself. I don't think i'll ever forget how to do this again hahaha. i'll mark your previous post as the answer!

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

$.post() in jQuery not working

I'm making a rating system, and I have the following jQuery code on my index.php page:
<script type="text/javascript">
$(document).ready(function() {
$("[id^=rating_]").hover(function() {
var rid = $(this).attr("id").split("_")[1];
$("#rating_"+rid).children("[class^=star_]").children('img').hover(function() {
$("#rating_"+rid).children("[class^=star_]").children('img').removeClass("hover");
/* The hovered item number */
var hovered = $(this).parent().attr("class").split("_")[1];
var hovered2 = $(this).parent().attr("class").split("_")[1];
while(hovered > 0) {
$("#rating_"+rid).children(".star_"+hovered).children('img').addClass("hover");
hovered--;
}
$("#rating_"+rid).children("[class^=star_]").click(function() {
var current_star = $(this).attr("class").split("_")[1];
$.post("send.php", {rating: current_star, id: rid});
});
});
});
});
</script>
Basically theres a hover effect and then when you click on the star, it'll send a post request to send.php, with the info on the rating clicked and the id of the element. Below this script I have some PHP that looks like this:
<?php
$query = mysql_query("SELECT * FROM test");
while($row = mysql_fetch_array($query)) {
$rating = (int)$row[rating];
?>
<div id="rating_<?php echo $row[id]; ?>">
<span class="star_1"><img src="star_blank.png" alt="" <?php if($rating > 0) { echo"class='hover'"; } ?> /></span>
<span class="star_2"><img src="star_blank.png" alt="" <?php if($rating > 1.5) { echo"class='hover'"; } ?> /></span>
<span class="star_3"><img src="star_blank.png" alt="" <?php if($rating > 2.5) { echo"class='hover'"; } ?> /></span>
<span class="star_4"><img src="star_blank.png" alt="" <?php if($rating > 3.5) { echo"class='hover'"; } ?> /></span>
<span class="star_5"><img src="star_blank.png" alt="" <?php if($rating > 4.5) { echo"class='hover'"; } ?> /></span>
<div class="clearleft"> </div>
</div>
<br />
<?php
}
?>
And then of course I have some CSS to make it look nice.
The send.php file looks like this:
<?php
mysql_connect("localhost", "admin", "") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
$rating = (int)$_POST['rating'];
$id = (int)$_POST['rid'];
$query = mysql_query("SELECT * FROM test WHERE id = '".$id."'") or die(mysql_error());
while($row = mysql_fetch_array($query)) {
if($rating > 5 || $rating < 1) {
echo"Rating can't be below 1 or more than 5";
}
else {
$total_ratings = $row['total_ratings'];
$total_rating = $row['total_rating'];
$current_rating = $row['rating'];
$new_total_rating = $total_rating + $rating;
$new_total_ratings = $total_ratings + 1;
$new_rating = $new_total_rating / $new_total_ratings;
// Lets run the queries.
mysql_query("UPDATE test SET total_rating = '".$new_total_rating."' WHERE id = '".$id."'") or die(mysql_error());
mysql_query("UPDATE test SET rating = '".$new_rating."' WHERE id = '".$id."'") or die(mysql_error());
mysql_query("UPDATE test SET total_ratings = '".$new_total_ratings."' WHERE id = '".$id."'") or die(mysql_error());
}
}
?>
There are 3 rating columns in the database table;
total_rating: total ratings (all the ratings added together).
rating: the current rating
total_ratings: the amount of ratings.
The problem is, if I change the $_POST['rating'] and $_POST['rid'] to $_GET and put the information int he url, for instance, send.php?id=1&rating=4, it works, and the database gets updated. However, when I press the stars, the database isn't updated. After messing around with the script I realised that the post must be working, however the id returns as 0.
To test this further I put this in the click function:
document.write(current_star+rid);
To see what was returned. The problem seems to be that the number that is returned is multiplied by the amount of times I hover over elements. So if I hover over maybe, 6 of the stars, then the current_star and ID will be repeated 6 times.
I feel like I'm so close to getting this to work, has anyone got any idea what's up with it? Thanks in advance.
And important thing to realize about jQuery's event handling is that it is registry-based, meaning that jQuery allows you to register multiple callbacks for any particular event, and it will invoke them in the order in which they were bound.
The reason you're seeing repeated current_star and id values is because you keep binding more and more events on every hover. This is because have your click() call inside your hover() call, therefore every time you hover, you will bind another click() event.
Try binding your click() event outside your hover event, using something like this:
$("[id^=rating_]").children("[class^=star_]").click(function() {
var rid = $(this).parent().attr("id").split("_")[1];
var current_star = $(this).attr("class").split("_")[1];
$.post("send.php", {rating: current_star, id: rid});
});
You also probably don't want to bind one hover() call inside the other, for the same reason.
I noticed you have used $_POST['rid'] instead of $_POST['id']. May be that's your problem.

Categories