jQuery UI Sortable and updating a mysql database - php

I am doing something wrong and it's driving me nuts because I can't figure it out.
Using jQuery ui sortable to sort the divs on my page. The sorting part works kinda but it does not update the database.
The only thing I can think of is the clear within page, but if I put this on the div it acts not as fluent.
PHP
<div id="page">
<div id="listItem_'.$id.'" class="a bunch of random classes">
<div class="handle"></div>
</div>
<div id="listItem_'.$id.'" class="this one has some other classes">
<div class="handle"></div>
</div>
<div class="clear"></div>
<div id="listItem_'.$id.'" class="a bunch of some other">
<div class="handle"></div>
</div>
</div>
Javascript
$(document).ready(function(){
$("#page").sortable({
handle : '.handle',
update : function () {
var order = $('#page').sortable('serialize');
$(document).load("sort.php?"+order);
}
});
});
sort.php
<?php
session_start();
require('connect.php');
if($_SERVER['REQUEST_METHOD'] == 'GET' && isset($_SESSION['USERNAME'])){
$i=1;
foreach ($_GET['listItem'] as $position => $item){
$sql = "UPDATE table SET position = ".$i." WHERE id = ".$item;
$res = mysql_query($sql);
$i++;
}
}
?>

Start debugging by placing var_dump('got here'); (or one of the variables) in your PHP script. Use the console in Firebug (which is an add-on) in Firefox to view the output. Step through until you find the spot where it's failing.

should $i be replaced with $position:
$sql = "UPDATE table SET position = ".$i." WHERE id = ".$item;
$sql = "UPDATE table SET position = ".$position." WHERE id = ".$item;
in any case ... if it doesnt update the database presumably you get an error?
and, i assume your table isnt actually called 'table' otherwise you should probably backtick it..

Related

How do I implement a like counter using PHP, jQuery and AJAX?

I am working on creating a like counter for quotes. I am trying to increment the like counter when the user clicks on the like button and display the number of likes.
Problems I encountered:
Like counter gets incremented when I refresh the page (Not because I am actually hit the like button).
I tried implementing jQuery for the updation of the like counter in real time but failed :(
I referred to all the QnA related to this couldn't find the desired solution. I went through this [question]PHP/MySQL Like Button, and made the necessary changes but now there is no updation in the database when I click the button.
This is the code for one quote.
<div class="testimonial text-sm is-revealing">
<div class="testimonial-inner">
<div class="testimonial-main">
<div class="testimonial-body">
<p id="q1">
<?php
$sql = "select quotes from voted where voted.quote_id = 1";
$result = mysqli_query($link,$sql);
$row = mysqli_fetch_array($result);
echo "$row[0]";
?></p>
</div>
</div>
<div class="testimonial-footer">
<div class="testimonial-name">
<button method="POST" action='' name="like" type="submit" class="like"><b>Like</b></button>
<?php
if(isset($_POST['like'])){
$link = mysqli_connect("localhost","root","","success");
$sql = "UPDATE voted SET likes = likes+1 WHERE voted.quote_id = 1";
$result = mysqli_query($link,$sql);
}
?>
<label>
<?php
$link = mysqli_connect("localhost","root","","success");
$sql = "SELECT likes from voted WHERE voted.quote_id = 1";
$result = mysqli_query($link,$sql);
$row = mysqli_fetch_array($result);
echo "$row[0]";
?>
</label>
<button class="btn" id="clipboard" onclick="copyFunction('#q1')"></button>
</div>
</div>
</div>
How do I make the like counter implement when I click on the like button?
How do I implement jQuery and AJAX to this, so that the counter is updated without a page refresh?
Please pardon my poor code structure.
Thanks for any help.
P.S This how a single quote will look like
You need three things for an asynchronous setup like this to work:
Your back-end script to handle ajax requests
Your front-end page
Your JQuery script to send ajax requests and receive data
Your back-end PHP script would look something like this (async.php):
<?php
if(isset($_POST['get_quotes'])) {
$sql = "select quotes from voted where voted.quote_id = 1";
$result = mysqli_query($link,$sql);
$row = mysqli_fetch_array($result);
echo "$row[0]";
}
if(isset($_POST['like'])) {
$link = mysqli_connect("localhost","root","","success");
$sql = "UPDATE voted SET likes = likes+1 WHERE voted.quote_id = 1";
$result = mysqli_query($link,$sql);
}
?>
Your front-end page will include an element with an ID to hook onto with the JQuery, and a button with a class or ID to capture the click event (page.html):
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="core.js"></script>
<body>
<button id="increment-like" value="Like" type="button" />
<p id="like-count">
</p>
</body>
<html>
Finally, your JavaScript file should look something like this, for a basic ajax request using JQuery (core.js):
$(document).ready(function() {
// initially grab the database value and present it to the view
$('#like-count').text(getDatabaseValue());
$('#increment-like').on('click', function() {
incrementDatabaseValue();
});
});
function getDatabaseValue() {
$.post("async.php",
{
get_quotes: true
},
function (data, status) {
// check status here
//return value
return data;
});
}
function incrementDatabaseValue() {
$.post("async.php",
{
like: true
},
function (data, status) {
// check status here
// update view
$('#like-count').text(getDatabaseValue());
});
}
I haven't tested this code but it should be clear and detailed enough to get you on the right track.

MySQL only returning one value

Been trying to figure out what's wrong for nearly two hours now.
I have made a wall post feature for my website, posts should be displayed on the profile wall, however instead of all of the posts being displayed, only 1 is. I have no idea what is wrong with my code, I can't find any issues.
The $profile_username variable has been defined in previous code and works. Even if I just type the name of the profile in it still only returns one post.
//----------submit wall post----------//
$getwallposts = mysql_query("SELECT * FROM `wallposts` WHERE `postedto`='$profile_username' ORDER BY `postid`");
//check if any rows are returned
while($wallposts = mysql_fetch_assoc($getwallposts)) {
$postid = $wallposts['postid'];
$postedby_username = $wallposts['postedby'];
$wallpostdate = $wallposts['dateposted'];
$wallpost = $wallposts['post'];
$querypostedby_info = mysql_query("SELECT * FROM `users` WHERE `username`='$postedby_username'");
//get the info above
if (mysql_num_rows($querypostedby_info) > 0) {
$getpostedby_info = mysql_fetch_assoc($querypostedby_info);
$postedby_id = $getpostedby_info['id'];
$postedby_profilepicture = $getpostedby_info['profilepicture'];
}
//lets keep the line breaks
$wallpost=nl2br($wallpost);
//display the posts
$wallpoststicker =
"
<div id='wallpost-container'>
<div id='wallpost-header'>
<img src='$postedby_profilepicture'><div id='wallpost-header-by'><a href='/profile.php?id=$postedby_id'>$postedby_username</a> said:</div>
<div id='wallpost-date'>• $wallpostdate</div>
</div>
<div id='wallpost-content'>
$wallpost
</div>
</div>
";
}
Also, I know that mysql is deprecated; my version of PHP can handle mysql queries fine though.
Where to do you echo you're output?
If it is after the While you will only get the last result that is stored in the variable.
Output within the while loop.
I can see a couple of issues with that code. First, what it seems to be your problem:
$wallpoststicker =
"
<div id='wallpost-container'>
<div id='wallpost-header'>
<img src='$postedby_profilepicture'><div id='wallpost-header-by'><a href='/profile.php?id=$postedby_id'>$postedby_username</a> said:</div>
<div id='wallpost-date'>• $wallpostdate</div>
</div>
<div id='wallpost-content'>
$wallpost
</div>
</div>
";
This code overrides the $wallpoststicker variable on every loop. That's why you only print one result at the very end.
But secondly, you're doing a query within a loop, which is potentially very inefficient. Have you thought on doing a LEFT JOIN between "wallposts" and "users" so you have all the data you need before you start your loop?

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!

I have a code in which i want to display my data in the content using there ids stored in database

I m developing a website and here is my code, in my code i have two ids sId (section) and ssId (SubSectionId) and i have a page lets say index.php now I am making url like this -- when i click on the left navigation bar where i have links AND when i click on one link it sends an id like localhost/index.php?sId=29&ssId=0
Now i want to show ssId=181 data on the same page index.php using there ids by taping the same leftnav of the subsection which sends an id localhost/index.php?sId=29&ssId=181
The issue here is that the result is showing on the contentarea of sId=29 instead of ssId=181 and both are stored in database..
if(isset($_GET['sId']) && !empty($_GET['sId']))
{
?>
<div>
<br /><br />
<h2 class="heading">
<?php
$sId = intval($_GET['sId']);
$qry = "SELECT `SectionId`,`Title`,`Details` FROM `section` WHERE `SectionId` = $sId";
$records = mysql_query($qry);
while($record= mysql_fetch_array($records))
{
echo $record['Title'];
?>
</h2>
<br />
<p>
<?php
echo $record['Details'];
}
?>
</p>
</div>
</div>
<?php
}
elseif(isset($_GET['sId']) && !empty($_GET['sId']) && isset($_GET['ssId']) && !empty($_GET['ssId']))
{
?>
<div>
<br /><br />
<h2 class="heading">
<?php
$sId = intval($_GET['sId']);
$ssId = intval($_GET['ssId']);
$qry = "SELECT SubSectionId,Title,Details FROM `pages` WHERE `SubSectionId` = $ssId";
$records = mysql_query($qry);
while($record= mysql_fetch_array($records))
{
echo $record['Title'];
?>
</h2>
<br />
<p>
<?php
echo $record['Details'];
}
?>
</p>
</div>
</div>
<?php
}
}
Hope you guys understand. Thanks in advance.
If I understand you correctly, you're saying the following.
Your script expects an sid and/or and ssid as input.
If either is supplied, your script will load the relevant content from the DB and show it
But, currently your script does not show content of the ssid and will only show the content of the sid
Am I right?
Try using two IF blocks rather than an IF/ELSE. This will make sure that all conditions that are met will be run rather than just one.
Also, you can stick to using the just the empty function call.
if ( !empty($_GET['sId']) ) {
//load and show content for section
}
if ( !empty($_GET['ssId']) ) {
//load and show content for sub section
}
UPDATE - To give subsections precedence over sections, you'll need to reverse your IF/ELSE condition.
if ( !empty($_GET['sId']) && !empty($_GET['ssId']) ) {
//load and show content for sub section if availavle
} else if ( !empty($_GET['sId']) ) {
//load and show content for section
}

Automatically update a <div> part of an HTML if a new database record is added

I have a simple page which contains some products in the database. What I want is to create some sort of an updater, if the user add a product then that specific div in the page will display the latest product added automatically.
I tried to view this link but it doesnt help at all we have different problem.
Anyway heres the function i have in php.
function recentlyAddeditems() {
echo '<h3>Recently Added Products</h3> <hr/>';
echo '<div id="main_section_widget">';
$sql = mysql_query("SELECT * FROM products ORDER BY id DESC LIMIT 20") or die(mysql_error());
if ($sql) {
while ($row = mysql_fetch_array($sql)) {
$name = $row['name'];
$id = $row['id'];
$category = $row['category'];
echo "$name | $category<br/>
<hr/>
";
}
echo '</div>';
echo '
<p><br/>More items...</p>
';
}
}
and the in html page
<div id="main_section_widget_cover" class="dates">
<?php recentlyAddedItems(); ?>
</div>
Is there a simpler way how to do this? I tried to read about ajax in jquery but still having confused without a concrete example.
Please help wizards of stack!!!
IF you want an example of a ajax in jquery here is a really simple example
<div id="main_section_widget_cover" class="dates"><div>
<script>
$('#main_section_widget_cover').load('recentitems.php');
</script>
in recentitems.php
<?php recentlyAddedItems(); ?>
Thats it, thats all you need to do to do a basic ajax call

Categories