Saving sortable to mysql with ajax jquery and php - 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.

Related

Using Select Box to Update Display Query

I am just learning Ajax and am trying to update a mysql select query to filter results. I think the query is working fine, but not sure that I have the event working correctly.
Here is my HTML with the selection;
<div class="volunteers">
<h1>Volunteers</h1>
<div class="volunteerSelection">
<select id="vtSelect" name="volunteerS">
<option value="1">Comittee</option>
<option value="2">Day of Event</option>
</select>
</div>
<div id="volunteers">
</div>
</div>
This is the script that displays the data;
I have updated this to the suggestion and it works fine. Then I started working on my PHP and mysql query. See below;
$(document).ready(function(){
$('#vtSelect').change(function (e) {
e.preventDefault();
var selectedOption = $(this).find('option:selected');
$('#vtSelect option').removeAttr('selected');
$(selectedOption).attr('selected', 'selected');
var selectedOptionValue = $(selectedOption).val();
$.ajax({
type: "POST",
url: "includes/backDataProcess.php",
data: {
data: selectedOptionValue
},
success: function (data) {
$("#volunteers").html(data);
}
});
});
});
This is the PHP with the select query; I have update this and am getting data. I updated the name in the select tag, but I am not getting the select tag value in the query. When I comment out the post data and just fill in a value it posts fine. I am not getting any errors, it is just displaying 0 results.
<?php
include('readerConnect.php');
$sql = "SELECT * FROM contacts prc
JOIN states as st
ON (prc.stateId = st.idStates)
INNER JOIN volunteers as v
ON (prc.idContacts = v.contactId)
INNER JOIN volunteerType as vt
ON (v.volunteerTypeId = vt.idVolunteerType)
WHERE (volunteerTypeId = 1 /*`mysql_real_escape_string('$_POST[volunteerS]')`*/)";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo
"<div class='contacts'>
<div class='contactName'>" . $row["firstName"] ." " . $row["lastName"] ."</div>"
."<div class='contactAddress'>" .$row["address1"] ." " .$row["address2"] ."<br>"
.$row["city"] ." " .$row["state"] ." " .$row["zip"] ."</div>"
."<div class='contactVolunteer'>" .$row["volunteerTypeId"]
."</div>";
}
} else {
echo "0 results";
}
$conn->close();
?>
I am not sure exactly where the issue is, I have tried both change and onchange to update, do I need an update button? I thought jquery would be able to do this with no update. Any help is greatly appreciated.
There are several obvious problems in your jQuery code. If you open your browser console you should see error onChange is not a function since there is no such jQuery method. You want change() or on()
Also you create a function showVolunteers() but it never gets called.
try:
$('#vtSelect').change(function (e) {
e.preventDefault();
var selectedOption = $(this).find('option:selected');
$('#vtSelect option').removeAttr('selected');
$(selectedOption).attr('selected', 'selected');
var selectedOptionValue = $(selectedOption).val();
$.ajax({
type: "POST",
url: "includes/backDataProcess.php",
data: {
data: selectedOptionValue
},
success: function (data) {
$("#volunteers").html(data);
}
});
});
Should you encounter more problems, use browser console network tab to inspect ajax request, and always use console to check for errors

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

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>

Limit Number of Results for Autocomplete Based on Dropdown Selection

I'm trying to figure out a couple things here and seem to be pretty close but hit a road block. My issue is, after I select a dropdown option (used to filter a large number of results), the results which should be available when I start typing in the autocomplete box are not available. If I hardcode a value that the dropdown is passing and start typing in the autocomplete box, everything works fine. It's only when I pass in that value that I am having the issue.
I have two PHP pages, one containing the layout which includes a dropdown (SQL for its results) and an autocomplete box and the other which contains the SQL for the autocomplete.
search.php
<select id="loc">
<?php
// sql for dropdown
while ($row = odbc_fetch_array($result)) {
echo "<option value\"".$row['Location']"\">".$row['Description']."</option>";
}
?>
</select>
<label for="search">Search: </label>
<input type="text" id="search" />
<script>
// Send value entered in the autocomplete box to data.php for it to be used in sql statement
$(document).ready(function(){
$('#search').autocomplete({
minLength: 3,
source: function(query, process) {
$.ajax({
url: 'data.php',
type: 'GET',
data: "name=" + $('#search').val(),
dataType: 'JSON',
async: true,
success: function(data) {
process(data);
}
});
}
});
});
// Append selected dropdown value to URL so it can be accessed
$(document).ready(function() {
$('#search').change(function() {
var res = $(this).val();
location.href = "search.php?src="+res;
});
});
</script>
data.php
<?php
if (isset($_GET['src'])) {
$loc = $_GET['src'];
$fullname = explode(" ", $_GET['name']);
$sql = "SELECT p.lastname + ', ' + p.firstname as fullname,
l.city as city
FROM people p
JOIN location l on p.city = l.city
WHERE p.lastname like '".$fullname[1]."%' AND p.firstname like '".$fullname[0]."%'
AND l.city = '$loc'
GROUP BY p.lastname + ', ' + p.firstname, l.city
ORDER BY p.lastname + ', ' + p.firstname";
// DB connection and execute connection here
$array = array();
while ($row = odbc_fetch_array($db)) {
$array[] = $row['fullname'];
}
echo json_encode($array);
}
?>
So when I have my code like this and select an option from the dropdown, it runs through the select statement since the selected value is being passed in. If I echo the results on the search.php page, they are filtered correctly or if I navigate directly to the data.php page and pass in the correct parameters everything is correct. After I make a selection though, and start typing in the autocomplete box, I'm not getting any results. I'm guessing I need to somehow filter the results based on the selection, get those results and run a different query when I start typing?
Thanks in advance for any help and please let me know if I'm not clear on anything.
Well just like it ususally happens, after taking a break from it I've got it working now.
Below is the revised code with comments showing what I changed.
search.php
<select id="loc">
<?php
// sql for dropdown
while ($row = odbc_fetch_array($result)) {
echo "<option value\"".$row['Location']"\">".$row['Description']."</option>";
}
?>
</select>
<label for="search">Search: </label>
<input type="text" id="search" />
<script>
/* Send value entered in the autocomplete box to data.php
* for it to be used in sql statement */
$(document).ready(function(){
$('#search').autocomplete({
minLength: 3,
source: function(query, process) {
// Added the variable below to get the dropdown's selected value
var res = $('#loc').val();
$.ajax({
url: 'data.php',
type: 'GET',
// Edited: included the dropdown value
data: "src="+res + "&name=" + $('#search').val(),
dataType: 'JSON',
async: true,
success: function(data) {
process(data);
}
});
}
});
});
/* This event is not needed since the value is set when a selection
* is made. 'change' passed that value to search.php causing
* the query to run without the search value. This caused a HUGE
* number of results, and usually causing the page to timeout.
* Making sure all variables get passed prior to running the query
* is a must. I knew this but got stuck on how to make it work. */
// Append selected dropdown value to URL so it can be accessed
//$(document).ready(function() {
// $('#search').change(function() {
// var res = $(this).val();
// location.href = "search.php?src="+res;
// });
//});
</script>
data.php
<?php
if (isset($_GET['src'])) {
$loc = $_GET['src'];
}
// Moved the $loc variable into the if statement above
// $loc = $_GET['src'];
$fullname = explode(" ", $_GET['name']);
$sql = "SELECT p.lastname + ', ' + p.firstname as fullname,
l.city as city
FROM people p
JOIN location l on p.city = l.city
WHERE p.lastname like '".$fullname[1]."%'
AND p.firstname like '".$fullname[0]."%'
AND l.city = '$loc'
GROUP BY p.lastname + ', ' + p.firstname, l.city
ORDER BY p.lastname + ', ' + p.firstname";
// DB connection and execute connection here
$array = array();
while ($row = odbc_fetch_array($db)) {
$array[] = $row['fullname'];
}
echo json_encode($array);
?>
I haven't finished a couple pieces on the main page such as disabling/hiding the autocomplete box until a selection is made from the dropdown and adjusting the query for additional filtering but those are next on my list. I'm sure there are a few other things I could clean up as well but my first goal was to get it working correctly and that's accomplished now!
If anyone is using php and has a few hundred thousand + results and would like to use an autocomplete box to filter those without waiting a ridiculous amount of time for the results to display, I hope this may be of some help. Not nearly as complex as I originally made it out to be but over thinking it will do that to you. Also, even though it's working now, feel free to add some suggestions and apologies for any grammatical errors!

Categories