jQuery Sortable Grid into MySQL Database PHP - php

I'm trying to sort images using: http://jqueryui.com/demos/sortable/display-grid.html
And then somehow submit the newly sorted array/results into a MySQL Database using PHP?
I'm having difficulty figuring this out (newby alert), so if anyone can shed some light on this, I'll be dishing out hi-5s like there's no tomorrow.
Cheers

In particular you need to look at attaching an event to the sortable
http://jqueryui.com/demos/sortable/#event-update
and serialize for getting the relevant content http://jqueryui.com/demos/sortable/#method-serialize
EDIT
This is a primitive version of what you need to do.
<script>
$(function() {
var arrayOfIds = [];
$( "#sortable" ).sortable({
update: function(event, ui) {
$.each($(this).sortable('toArray'), function(key, value) {
arrayOfIds.push(value.replace('el-',''))
});
var jqxhr = $.ajax({
url: "order.php?order="+encodeURIComponent(arrayOfIds),
})
.success(function(response) { console.log("success" + response ); })
.error(function() { console.log("error"); })
.complete(function() { console.log("complete "); });
}
});
$( "#sortable" ).disableSelection();
});
</script>
Each li element than needs an id that your DB can understand
<li class="ui-state-default" id="el-1">1</li>
the "1" in id="el-1" should relate to an id in your DB table. When you reorder, the update event fires, goes through the new order, grabs all the ids and passes that to an ajax request which a php file then can pick up. the order.php script then go split the numbers by the "," and update your table one by one.
e.g.
$itemOrders = explode(',',$_POST['order']);
$sizeOfList = sizeof($itemOrders);for($i=0; $i<$sizeOfList; $i++)
{
$itemId = intval($itemOrders[$i]);
$query = "UPDATE your_table_name SET order_no = '".$i."' WHERE id = '".$itemId."' ";
if ($result = $msHandle->query($query))
{
$message = 'success';
}
else
{
$message = 'fail ';
}
}

There will be a callback function on the sorting event which you can use to send an AJAX request to a PHP script which updates a database. Think of it as after you've made a sorting action (i.e. moving one item around), you send the values (i.e. the ordered list) to a PHP script that takes those values and updates the database. I'll assume you have experience in MySQL as you seem to know the fundamentals of the problem.

Related

Refresh table after ajax success with another SQL statement values without DataTable

i would like some guidance as to how to handle things after an ajax call.
I have a table with values showing numbers, those numbers are totals of other values. SQL statements wise, everything works.
But I don't really understand how am I supposed to refresh that table when I click on buttons.
These buttons are supposed to show the same table structure with different values, from another SQL query.
Here is what I have at the moment.
JS/AJAX
$(document).ready(function () {
var currentID;
$('.member_list li a').click(function() {
currentID = $(this).attr('data-key-value');
$.ajax({
type: "POST",
url: "index_report.php",
data: { ID : currentID }
}).done(function(response) {
var table = $('.manage_table').DataTable();
table.remove().draw();
});
});
});
sample of buttons that should be pressed to get the new values:
<li>Henry</li>
<li>Joe</li>
<li>Hector</li>
and the line that launch the DB call for the individual data.
$temp_data_1 = $className>select_number_by_person($date_begin_month[$i],$date_end_month[$i], $_POST['ID']);
I figured out my problem was due to DataTable.
EDIT: Apparently, I can't use it with templates.
I am currently using smarty, and all my table is auto generated with loops.
For some reason, DataTable is only giving me Errors.
Any Idea how to do it without DataTable?
I am probably missing a huge chunk of code for this to work.
Thanks in advance of any advice.
I can see that you're using DataTable couldn't you do something like this?
var currentID;
$('.member_list li a').click(function() {
currentID = $(this).attr('data-key-value');
dataTableUpdate();
});
function dataTableUpdate(id){
var query = $.param({ID : currentID})
var source = "index_report.php?" + query
// Get API instance
var table = $('.manage_table').DataTable();
// Load data using API instance
table.ajax.url(source).load();
};

Store li order in Mysql DB with Jquery sortable

I have a sortable list in my site which saves the order of the list items with an ajax request to a php page.
The problem is when the id of the LI (which is generated by the database) gets above 999 or so it begins to error as the array I'm sending to the PHP page becomes too long.
Is there a better way of doing this?
Currently my Jquery/ ajax is:
$(function() {
$('#sortable').sortable({
update: function(event, ui) {
var order = [];
$('#sortable li').each( function(e) {
order[ $(this).attr('id') ] = $(this).index() + 1;
});
var request = $.ajax({
url: "ajax/save_order.php",
type: "POST",
data: {positions : order},
dataType: "json"
});
}
});
});
My PHP page is:
$positions = $_POST['positions'];
foreach ($positions as $id_section => $order)
{
$sql = sprintf("
UPDATE section_order
SET id_order = %d
WHERE id_section = %d
",
$order,
$id_section
);
$result = mysql_query($sql);
}
I've been trying to work out how to get the data from the sortable into a multidimensional array in jquery, but currently am drawing a blank.
OK I see. Seems a bit unwieldy for a user to manually drag and drop items in a list of over 1000 items. But I don't know how/why you are doing this so will assume it works for your application.
The below solution is actually from this SO question jQuery UI Sortable, then write order into a database
jQuery Sortable has a serialize function that takes care getting the order for you. Use it like below:
$('#sortable').sortable({
axis: 'y',
stop: function (event, ui) {
var data = $(this).sortable('serialize');
// POST to server using $.post or $.ajax
$.ajax({
data: data,
type: 'POST',
url: 'save_order.php'
});
}
});
And in the save_order.php file, just check what the posted data looks like and loop though it, should be able to do something like:
<?php
foreach ($_POST['each_item_whatever...'] as $value) {
// Database stuff
}
?>

How do I get the values and id's of multiple select lists and pass it to AJAX?

I am trying to iterate through a number of selects in a cell of a table (they are not in a form). I have a submit button when pressed is supposed to retrieve the values and id of each select list which I will pass to the server via AJAX and PHP. My table is a table of students of a course. The table contains the students name and their attendance for a lesson in the course.
This is my table on Pastebin and jsFiddle. http://pastebin.com/NvRAbC7m and http://jsfiddle.net/4UheA/
Please note that this table is entirely dynamic. The no. of rows and the info in them is dynamically driven.
This is what I'm trying to do right now with jQuery. Please excuse the logic or the complete nonsense that is my JavaScript skills. I don't actually know what I'm doing. I'm just doing trial and error.
$('#saveAttendances').live('click', function()
{
var attendSelect = $('.attendSelect');
var students = new Array();
//get select list values and id.
for(var i in attendSelect)
{
students['student_id'] += attendSelect[i].id;
students['student_id']['attedance'] += attendSelect[i].value;
console.log(students['student_id']);
}
//after retrieving values, post them through ajax
// and update the attendances of students in PHP
$.post("",{ data: array }, function(msg)
{
alert(msg);
});
});
How do I get the values and id's of each select list and pass it to AJAX?
Edit
If you insist on going against jQuery's grain and using invalid HTML, here's a suitable solution for you:
$(function() {
$('button').click(function(){
var data = $(".attendSelect").wrap('<form/>').serialize();
$.post('process.php', data, function(response){ ... });
return false;
});
});​
Worth mentioning, this example does not rely on fanciful .on() or .live() calls. However, this requires you to have the proper name attribute set on your <select> elements as described below. This also resolves your invalid numeric id attributes issue.
See it working here on jsFiddle
Original Answer
First off, some minor changes to your HTML. You need to wrap your <select> elements in a <form> tag. Using the form tag will give you access to jQuery's .serialize() method which is the exact functionality you're looking for. Personally, I'd recommend doing things the jQuery Way™ instead of implementing your own form a serialization. Why reinvent the wheel?
Next, your td have non-unique IDs. Let's update those to use a class attribute instead of an id. E.g.,
<td class="studentName">Aaron Colman</td>
Secondly, your <select> elements could benefit from a name attribute to make form processing way easier.
<select class="attendSelect" name="students[241]">
...
<select class="attendSelect" name="students[270]">
...
<select class="attendSelect" name="students[317]">
...
Lastly, jQuery's .serialize() is going to be your winning ticket.
​$(function() {
$('form').submit(function(){
$.post('process.php', $(this).serialize(), function(response){ ... });
return false;
});
});​
Upon submit, the serialized string will look something like
students[241]=Late&students[270]=Absent&students[317]=default
See it working here on jsFiddle
live() is deprecated as of jQuery 1.7, use on() instead
http://api.jquery.com/on/
students is an array, so I don't think you can do students['student_id'], if you would like to push an array of student, you can:
$('#saveAttendances').on('click', function() {
var students = [];
// iterate through <select>'s and grab key => values
$('.attendSelect').function() {
students.push({'id':$(this).attr('id'), 'val':$(this).val()});
});
$.post('/url.php', {data: students}, function() { // do stuff });
});
in your php:
var_dump($_POST); // see what's inside :)
As #nathan mentioned in comment, avoid using number as the first character of an ID, you can use 'student_<?php echo $id ?>' instead and in your .each() loop:
students.push({'id':$(this).attr('id').replace('student_', ''), 'val':$(this).val()});
Here's jQuery that will build an object you can pass to your script:
$('button').click(function() {
var attendance = new Object;
$('select').each(function() {
attendance[$(this).attr('id')] = $(':selected', this).text();
})
});​
jsFiddle example.
This results in: {241:"Late",270:"Absent",317:"Late"}
Edit: Updated to iterate over select instead of tr.
Perhaps you want something like below,
DEMO
var $attendSelect = $('#tutorTable tbody tr select');
var students = {};
$attendSelect.each (function () { //each row corresponds to a student
students[$(this).attr('id')] = $(this).val();
});
This would give you an object like below,
students = { '241': 'Late', '270': 'Absent', '317': 'default' };
If the above is not the desired structure then modify the .each function in the code.
For ex: For a structure like below,
students = [{ '241': 'Late'}, {'270': 'Absent'}, {'317': 'default'}];
You need to change the code a little,
var students = [];
...
...
students.push({$dd.attr('id'): $dd.val()});
var $select = $('.attendSelect'),
students = [];
$('body').on('click', '#saveAttendances', function() {
$select.each(function(k, v) {
students[k] = {
student_id : $(this).attr('id'),
attedance : $(this).val()
};
});
console.log(students);
});

How to get the textarea ID using jQuery

Ive got textarea area on each table row with unique ID .
How to retrieve that unique id with javascript?
PHP:
$query = $db->query("SELECT * FROM bs_events WHERE eventDate = '".$date."'");
while($row = $query->fetch_array(MYSQLI_ASSOC)){
echo '<textarea id=\"att_name_" . $row['id'] . "\" style=\"width:300px\"></textarea>";'
}
PHP OUTPUT:
<textarea id="att_name_1" style="width:300px">
<textarea id="att_name_2" style="width:300px">
<textarea id="att_name_3" style="width:300px">
jQuery:
$(document).ready(function(){
$("#book_event").submit(function(){
id = event.target.id.replace('att_name_','');
$.post("Scripts/book_event.php", {
att_name: $("att_name_"+id).val(),
}, function(data){
if(data.success) {
$("#err").text(data.message).fadeIn("slow");
}
}, "json");
});
});
It looks to me like you're naming your textareas to correlate to the database entries, then trying to make updates and pass those values back. Assuming the textareas are in the form you're submitting, you can use:
$('#myform').submit(function(e){
// find each of those text areas
$(this).find('textarea[id^=att_name]').each(function(i,e){
//
// from here-in, e now represents one of those textareas
//
// now submit the update
$.post('Scripts/book_event.php',{
att_name: $(e).val()
},function(data){
if (!data.success)
$("#err").text(data.message).fadeIn("slow");
},'json');
});
e.preventDefault();
});
Ideally though, if you're looking to use AJAX to push updates/changes back to the server, you may look in to .serialize() and push all forms back. Then, on the server-side you'll get the standard $_POST['att_name_1'] values that you can use for your actual updating. e.g.
// .serialize() example
$('#myform').submit(function(e){
$.post('Scripts/book_event.php',$(this).serialize(),function(data){
if (!data.success)
$("#err").text(data.message).fadeIn("slow");
});
e.preventDefault();
});
To solve your problem, you can use each()
$(function()
{
$("textarea").each(function()
{
var textarea_id = $(this).attr('id');
});
});
I don't fully understand the question.
If you want a list of the ids, how about something like:
$(document).ready( function ( ) {
var textareas = new Array();
// Run through each textbox and add the id to an array
$("textarea").each( function( ) {
textareas.push( $(this).attr("id") );
});
// Print out each id in the array
textareas.forEach( function(i) { alert(i); });
});
(that's untested and probably not the quickest way - I'm a bit out of practice)

Updating the contents of a dropdown list Javascript/PHP

I'm new to Javascript/Jquery and struggling with a certain issue.
In the process of adding a job to a database, the users have an option to update the contents of dropdown lists with new options. Adding the new options is handled through a greybox which posts data with PHP through to the database.
After adding the new option it does not display in the dropdown list. As such they need to be able to click a button to refresh the contents of the dropdown list. Has anyone accomplished this before, and can show me some sample source code? Or is there a more elegant solution fo this issue?
I've been researching pretty much non-stop and cannot find a solution, any help is appreciated. n.n
Edit:
<script type="text/javascript">
function getbrands(){
new Ajax.Request('ajax/brand.php',{
method: 'get',
onSuccess: function(transport){
var response = transport.responseText;
$("brand").update(response);
}
});
}
It works... sometimes. Highly unstable. Also has a bad habit of conflicting with other scripts on the page. (mainly the greybox)
Any suggestions will be taken on board at this stage. :X
Use ajax to post the data to your php file, echo the html for the new dropdown back to the javascript, and then use jquery to put in the new contents. http://api.jquery.com/jQuery.ajax/
Assuming your using jQuery, you could do the following..
//in a php file that your gonna use to fetch new dropdown values
<?php //pathToPhpFile.php
header("Content-Type: application/json");
//here you'd perform a database query
//heres a dummy dataset
$data = array(
array( "id" => "dropdown1", "label" => "Dropdown #1"),
array( "id" => "dropdown2", "label" => "Dropdown #2"),
);
echo json_encode( $data );
exit;
?>
javascript code: sould be wrapped in $(document).ready( function(){ }); block to ensure the button is ready to accept events
//attach refresh event to button
$("#refeshButtonId").click( function() {
var dropdown = $('#idOfTheDropdown');
//fetch the key/values pairs from the php script
jQuery.getJSON( "pathToPhpFile.php", function( data ) {
//empty out the existing options
dropdown.empty();
//append the values to the drop down
jQuery.each( data, function(i, v) {
dropdown.append( $('<option value="'+ data[i].id +'">'+data[i].label+'</option>');
});
});
});
refined code :)
<script type="text/javascript">
$(document).ready( function(){
$("#refeshButtonId").click( function() {
//fetch the key/values pairs from the php script
jQuery.getJSON( "pathToPhpFile.php", function( data ) {
var dropdown = $('#idOfTheDropdown');
//empty out the existing options
dropdown.empty();
//append the values to the drop down
jQuery.each( data, function(i, v) {
dropdown.append( $('<option value="'+ i +'">'+ v +'</option>') );
});
});
});
});
</script>
no sample code but I guess it goes like this
after the posting, create a callback
that updates the DOM, particularly
the options for the select box
maybe it goes something like this in code
in jquery:
$.ajax({
method: 'POST',
data : $('#newjobfield').val(),
dataType: 'text'
success : function(data){
$('#selectbox').append('<option value="' + data + '">' + data + '</option>')
}
});
in php
function getNew()
{
if ($_POST)
{
// update database
// then echo the record's 'name' (or whatever field you have in there)
echo $newInsertedJobName;
}
die();
}
Now this code sucks, so just tell me if something does not work (I haven't tested it, cuz I made it a few minutes ago, while at work :P)

Categories