jquery sortable update can work only one time? - php

Need a way to make element show in the div,but when i use ajax send data to list.php.it can not work?
PHP:
<?php
mysql_connect('localhost','user','password');
mysql_select_db('fruit');
$days = 3;
for($i=1;$i<=$days;$i++)
{
?>
<ul id="sortable">
<?php
$sql = "select * from menu where columnNo = '$i' order by orderNo ASC";
$result= mysql_query($sql);
//$row=mysql_fetch_assoc($result);
//print_r($row);
while($row=mysql_fetch_assoc($result))
{
echo '<li id="list_' . $row['id'] . '">' . $row['title'] . "</li>\n";//
}
?>
</ul>
<?php
}
?>
jquery:
$(function(){
$("ul").sortable({
connectWith:"ul",
update:function()
{
serial = $("ul").sortable("serialize");
$.ajax({
data: serial,
url:"list.php",
type:"post",
error:function(){
alert("Error!");
},
success:function(data){
$("#serverResponse").html(data);
}
});
//alert(serial);
}
});
$("#sortable").disableSelection();
});
list.php
<?php
mysql_connect('localhost','root','xingxing');
mysql_select_db('fruit');
$list = $_POST['id'];
for($i=0;$i<count($menu);$i++)
{
$sql = "update menu set orderNo= '$i' where id = '$menu[$i]'";
mysql_query($sql);
}
?>
but,the list.php did't work. i don't know why.could anyone can help me ? THX!

Not sure if this will help, but your trying to update on every single reorder event (is this really necessary?).
It might be wise to use a javascript timeout to update after a couple seconds idle time after an update. I personally use this method and it makes things run a lot smoother.
In your jQuery .sortable() setup add the following:
start: function(event, ui){
clearTimeout(allow_update);
},
update: function(event, ui){
allow_update = window.setTimeout(UpdateOrdering, 3000);
}
And then add var allow_update = null; somewhere and an UpdateOrdering function which is called when the timeout expires (in my case 3000 ms), with your update functionality in there.
Hope this helps :)

Related

How to pass php array to ajax function

So I would like to pass the php array values from this form id to my ajax form. Everything works fine except that it will only display the (1) id number.
Here is my form code: I am passing the $row[topic_id'] as a value to get the id for jquery.
public function forumview($query){
$stmt = $this->db->prepare($query);
$stmt->execute();
$results = $stmt->fetchAll();
if($stmt->rowCount()>0){
foreach($results as $row){
echo '<tr>';
echo '<td style="color: #333;"><span class="pull-right">';
//Problem is here with the $row['topic_id'] portion
if(isset($_SESSION['user_session'])){
echo '<a href="#" class="upVoteArrow"
onclick="upVoteIncrementValue('.$row['topic_id'].');">';
}else{
echo '<a href="#" id="loginForm" class="upVoteArrow" data-
toggle="modal" data-target="#loginModal"><i class="fa fa-arrow-up"></i>
</a>';
}
echo '<span id="voteCount">'.$this->cleanNumber($row['topic_likes']).'</span>';
}
Here is my Ajax call to send the info to my php file
function upVoteIncrementValue(postID){
event.preventDefault();
//var upVoteIncrement = $("#upVoteIncrement").val(); //not needed
$.ajax({
type: "POST",
url: "voting.php",
data: {
"upVoteIncrement": postID,
},
dataType: "json",
cache: false,
success: function(response){
if(response){
var response = $.trim(response);
if(response){
$('#voteCount').html(response);
}
else {
return false;
}
}
}
});
Then here is the php file that handles the call.
if(isset($_POST['upVoteIncrement'])){
$upVoteIncrement = $_POST['upVoteIncrement'];
$stmt = $conn->prepare('UPDATE topics SET topic_likes = topic_likes+1 WHERE topic_id = :id LIMIT 1');
$stmt->bindParam(':id', $upVoteIncrement);
$stmt->execute();
$upVote = $conn->prepare('SELECT topic_likes FROM topics WHERE topic_id = :id LIMIT 1');
$upVote->bindParam(':id', $upVoteIncrement);
$upVote->execute();
$upVoteCount = $upVote->fetchAll();
if($upVote->rowCount() > 0){
foreach($upVoteCount as $row){
$up = $row['topic_likes'];
$results[] = $up;
//exit(); //not needed
}
}
echo json_encode($results);
}
Essentially I am just making a simple up vote system that the user clicks on and it updates the database incrementing by 1. It increments the values and everything works except it will only increment it for the last posted item. So even if I upvote on a topic from earlier it will only add 1 vote to the last inserted topic. Any advice is much appreciated, thanks in advance!
If your using a loop to populate the row id, which it looks like you are here are your problems.
The loop is creating a hidden input element on every iteration of the loop and you are not changing the id of the element. So you will have a bunch of elements all with the same id. That will cause you problems a few different ways.
I changed your PHP code so that each element will have it's own id. I also changed the your javascript function so that the id value is passed to the function itself.
See if this helps:
PHP:
if(isset($_SESSION['user_session'])){
echo '<input type="hidden" id="' . $row['topic_id'] . '" name="upVoteIncrement"
value="' . $row['topic_id'] . '"><a href="#" class="upVoteArrow"
onclick="upVoteIncrementValue(' . $row['topic_id'] . ');">';
}
JS:
function upVoteIncrementValue(postID){
event.preventDefault();
//var upVoteIncrement = $("#upVoteIncrement").val(); //Don't need this anymore.
$.ajax({
type: "POST",
url: "voting.php",
data: {
"upVoteIncrement": postID, //Use the passed value id value in the function.
},
dataType: "html",
cache: false,
success: function(response){
if(response){
var response = $.trim(response);
if(response){
$('#voteCount').html(response);
}
else {
return false;
}
}
}
});
Hope it helps!
I also want to point out that in the code below:
if($upVote->rowCount() > 0){
foreach($upVoteCount as $row){
$up = $row['topic_likes'];
echo $up;
exit();
}
}
You are exiting the script on the first iteration of the loop and you will only ever get one result back.
If you need to return an array of data it should look like this:
if($upVote->rowCount() > 0){
foreach($upVoteCount as $row){
$up = $row['topic_likes'];
$results[] = $up;
//exit();
}
}
echo json_encode($results);
You will then need to set your datatype to json instead of html.
The response in your ajax will now be an array. To see the array:
success: function(response){
if(response){
console.log(response); //Look in your console to see your data.
var response = $.trim(response);
if(response){
$('#voteCount').html(response);
}
else {
return false;
}
}
}
The problem is that in the event handler you addressing element by id, and it's not always the same that you click on.
function upVoteIncrementValue(){
event.preventDefault();
// Always will be last inserted element
var upVoteIncrement = $("#upVoteIncrement").val();
You can use event to get valid element. It's default argument that passed to handler, but remember to define it without braces:
<input onclick="upVoteIncrementValue" />
Then your handler:
function upVoteIncrementValue(event){
event.preventDefault();
var upVoteIncrement = $(event.target).val();
Also if you have several elements with the same ID it's invalid HTML, at least it will hit warning at https://validator.w3.org/ .
So you should set id arg for your element only in case if it's unique, and having this mindset will help you to not hit similar issue again.

applying "this" jQuery, to delete an echoed row in php from sql database

This is my current plan:
Clicking on a row selects or gets the id of the row, then this id is passed to a delete script most likely via AJAX or an HTTP request. The problem I have is how to identify the row from the click using "this" this as in show below:
$( this ) {
// get id and send to delete script
}
I have echoed out the rows so that I have the id row
<?php
require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR.'dbconnect.php');
$link = new mysqli("$servername", "$username", "$password", "$dbname");
$query = "SELECT COUNT(*) FROM entries";
if ($result = $link->query($query)) {
/* fetch object array */
while ($row = $result->fetch_row()) {
if($row[0]==0){
echo "There are no entries.";
}else {
$query2 = "SELECT id,saying,date,thumbs_up,comments FROM entries ORDER by ID ASC ";
if (($result = $link->query($query2))) {
/* fetch object array */
while ($row = $result->fetch_row()) {
echo
'<div class="container" align="center"">'.
'<div class="entry-container" align="left">'.
$row[1]." ".
'</div>'.
'<div class="x" align="center">'.
'<button class="red" name="remove" onclick="remove_entry();">remove entry'.
' '.
$row[0].
'</button>'.
'</div>'.
'</div>'.
'<br>'
;
}
}
}
}
/* free result set */
$result->close();
}
?>
remove_entry(); doesn't do anything yet, presumably it will send the id to the delete script which then removes the row using the DELETE command
<script type="text/javascript">
function remove_entry() {
var answer = confirm("Delete this entry?")
if (answer){
//some code
}
else{
//some code
}
}
</script>
What is the most direct and effective / efficient way to do this?
I would even prefer not to show id, just use a simple x for the delete button, I echoed the id so that I had it to use to identify the row to be deleted.
Using jQuery can do :
HTML
<div class="entry-container" align="left" id="'.$row[0].'">
JS
$(function(){
$('button.red').click(function(){
var $row = $(this).closest('.entry-container'),
rowId = $row.attr('id');
$.post('/path/to/server', {id: rowId}, function(resp){
if(resp =='ok'){
$row.slideUp(function(){ $row.remove() });
}
});
});
});
Then remove your inline onclick
In PHP receive the id with $_POST['id'] and validate it before passing to db query
For starters, don't use 2 SQL queries. Just do the one you use to get data and, if it has no rows, give a different output.
Use semantic markup like so:
'<button type="button" class="remover" id="entry-' . $row[0] . '">remove this entry</button>'
Then in your jQuery, use something like this:
$(function() {
$('.entries').on('click', '.remover', function() {
var eId = this.id.replace(/^\D+/, '');//since IDs should not start with a number
$.post(
'/your/delete/endpoint/',
{
id: eId
},
function(data) {
if (data.ok) {//sending JSON responses are easier to debug and you can add to them later without breaking things
//remove row
}
else {
//display error message
}
}
);
});
});
The second parameter to on() makes it a delegated event, which means you can add new items to an existing set, with the same remover markup, and the new remove buttons will also work.

How do I write a JQuery function to populate a div from an html select?

Below is my simple Javascript function.
<html>
<head>
<script>
$(document).ready(function() {
$.get('getImage.php', function(data) {
$('#imageSelector').html("<select>" + data + "</select>");
});
});
</script>
</head>
<body>
<div id="imageSelector">
</div>
<div id="imageArea">
</div>
</body>
</html>
This is the PHP script used to get the data.
<?php
include 'connect.php';
$sql = "SELECT products_id, products_image FROM products";
$query = mysqli_query($dbc, $sql);
while ($Array = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
$imageEcho .= '<option value=' . $Array['products_id'] . '>' . $Array['products_image'] . '</option>';
}
echo $imageEcho;
?>
Below is the function used to complete the URL path to the image.
function getImage(image) {
document.getElementById("imageArea").innerHTML="<img src=../eoas/images/"+image+" alt='' />";
}
Maybe I can't do it this way but I thought I would check to see if anyone knows.
You need smth like this :
$(document).ready( function(){
$.get("getImage.php",
function(data){
$( '#imageSelector' ).attr('src', data);
});
});
Use Chrome developer tools to understand what data is in ajax answer
Here is article about it
And it would be much better to use JSON answers
Example using the jsFiddle API.
$.get('getImage.php',function(data){
// data = '<option value=...>...</option><option ...>...</option>...';
$('<select>').html(data).appendTo('#imageSelector');
});

Can't make autocomplete work with ajax + jQuery

I'm trying to accomplish autocomplete task with the help of ajax (jQuery). Lets have a look at scripts
here is html =>
<input type="text" name="user_key" id="user_key">
here is javascript in the same file =>
<script type="text/javascript">
$(function(){
$("#user_key").autocomplete({
source: function(request,response){
var suggestions = [];
$.ajax({
url: "/ajax/autocomplete.php",
type: "POST",
data: {user_key:$(this).val()},
success: function(result){
$.each(result,function(i,val){
suggestions.push(val.name);
});
},
dataType: "json"
});
response(suggestions);
}
});
});
</script>
and here is php script from autocomplete.php file =>
if (!$connection->connect_errno){
if ($connection->set_charset("utf8")){
if ($r = $connection->query("SELECT name FROM users WHERE name LIKE '" . $_POST['user_key'] . "%'")){
for ($x=0,$numrows = $r->num_rows;$x<$numrows;$x++){
if ($row = $r->fetch_assoc()){
$array[$x] = array("name",$row['name']);
}
}
$r->free();
}
}
}
echo json_encode($array);
PS. It doesn't work. Please help , I've been trying to accomplish this task for the past 2 days,but can't get it to work. Thanks beforehand :)
$array[$x] = array("name",$row['name']);
this is making name and the value from the database both as the elements of the array()
change the code of autocomplete.php to
if (!$connection->connect_errno){
if ($connection->set_charset("utf8")){
if ($r = $connection->query("SELECT name FROM users WHERE name LIKE '" . $_POST['user_key'] . "%'")){
for ($x=0,$numrows = $r->num_rows;$x<$numrows;$x++){
if ($row = $r->fetch_assoc()){
$array[$x] = array("name"=>$row['name']);
}
}
$r->free();
}
}
}
echo json_encode($array);
This will make name as the key for the value fetched from the database
this will help you.
You need to take another look at the autocomplete docs but you will be able to find an answer here: jquery auto-suggestion example doesn't work

jQuery/PHP Hide Div, Update Information from MySQL, Show Div New Information

jQuery:
$(document).ready(function(){
$(".reload").click(function() {
$("div#update").fadeOut("fast")
.load("home.php div#update").fadeIn("fast")
});
});
PHP:
function statusUpdate() {
$service_query = mysql_query("SELECT * FROM service ORDER BY status");
$service_num = mysql_num_rows($service_query);
for ($x=1;$x<=$service_num;$x++) {
$service_row = mysql_fetch_row($service_query);
$second_query = mysql_query("SELECT * FROM service WHERE sid='$service_row[0]'");
$row = mysql_fetch_row($second_query);
$socket = #fsockopen($row[3], $row[4], $errnum, $errstr, 0.01);
if ($errnum >= 1) { $status = 'offline'; } else { $status = 'online'; }
mysql_query("UPDATE service SET status='$status' WHERE sid='$row[0]'")
or die(mysql_error());
?>
<ul><li style="min-width:190px;"><?php echo $row[1]; ?></li>
<li style="min-width: 190px;" title="DNS: <?php echo $row[2]; ?>">
<?php echo $row[3] . ':' . $row[4]; ?></li>
<li class="<?php echo $status; ?>" style="min-width:80px;"><div id="update">
<?php echo $status; ?></div></li></ul>
<?php
}
}
?>
<?php statusUpdate(); ?>
I have a button which I press (refresh) and that will then refresh the #update id to hopefully fadeOut all the results, and then fade in the new results... issue is it fades them out okay, but when it brings them back, it's just div on div and div and looks really messy - does not do what it's meant to do (would have to upload a picture to give further information).
In the short, what I want to happen is when you hit the update, they will all fade and then fade in with updated values from the php... I made the php/mysql into a function so then I could call it when i hit that refresh button, thinking that would work, but I don't know how to do that...
Thank-you in advance,
Phillip.
Javascript
$(document).ready(function(){
$(".reload").click(function() {
$("div#update").fadeOut("fast");
$.ajax({
url:'home.php',
data:{type:'getStatus'},
type;'post',
success:function(data){
$('div#update').html(data).fadeIn('fast');
}
});
});
});
php page format
<?php
$type= $_POST['type'];
if($type=="getStatus")
{
//get statuses from data base and return only formatted statuses in html
}
else
{
//your page codes here
//like tags <html>,<body> etc, all regular tags
//<script> tags etc
}
?>
.load("home.php div#update").fadeIn("fast")
That's wrong. You need to use,
$('div#update').load('home.php', function(data) {
$('div#update').html(data).fadeIn("fast");
});
Make sure your PHP file works properly by calling it directly and confirming that it returns the results properly.
Reference : http://api.jquery.com/load
Try this
var $data = $('div#update');
$data.fadeOut('slow', function() {
$data.load('home.php div#update', function() {
$data.fadeIn('slow');
});
});
Just for the reference, it will be better to add an additional page in the same directory (eg: phpcode.php) and then put your php code also in there! then try this:
var $data = $('div#update');
$data.fadeOut('slow', function() {
$data.load('phpcode.php div#update', function() {
$data.fadeIn('slow');
});
});

Categories