I am using jQuery UIs Sortable to allow a user to move items from 4 columns as well as change the order of items within each column. I have the latter working without problem; updating the new order to the database.
But I'm not sure how to handle storing moving from Column A to Column B. Each unordered list has a unique ID so I'd like to send that information along; I just don't have a firm understanding of how to do this.
$("#list1, #list2, #list3, #list4").sortable({
connectWith: ".sort",
placeholder: "shadow",
dropOnEmpty: true,
opacity: 0.8,
cursor: 'move',
update: function() {
var order = $(this).sortable("serialize") + '&update=update';
$.post("/update.php", order, function(theResponse) {
$("#alert").html(theResponse);
$("#alert").slideDown('slow');
slideout();
});
}
});
I've found an answer to my own question. The answer is to pass the data to the PHP file in a slightly different manner that allows for a more robust amount of variables (rather than just serializing one set of information).
var item = ui.item;
var new_ul = item.parent();
var order = [];
container.children('li').each(function(i){
reorder[i] = $(this).attr('id');
});
$.ajax({
method:'post',
url: 'update.php',
data:{
'new_ul':container.attr('id'),
'item':item.attr('id'),
'order':order
}
});
Full credit for this solution goes to user 'Zehee' at CodeIgniter (Who I believe got the solution from 37signals) http://codeigniter.com/forums/viewthread/175134/#831756
Related
The code below works for autocomplete for FileNo (field) only. i want this function to work for other attributes of employee too. i.e FirstName, LastName
dataTextField: "FileNo" <---------------- here dataTextField gets sing field. how could it be for multiple fields?
Since you are the one that knows on which columns want to search, my recommendation is:
Implement index.php/hr_management/manage_hr/search_employee/ in such way that is able to do the search for any of the columns that you want (FileNo, FirstName, LastName...).
This service will return three columns (at least) providing an id, column name on which you found the match and match value.
match value is used for displaying values in the autocomplete.
Once selected value on autocomplete use the column name and match value for filtering on the grid.
You should use template to change what is displayed in the dropdownlist of the autocomplete. Then the dataTextField will only be used inside the input element.
Here is how it goes to create template.
Kendo Autocomplete has dataTextField that accepts a field name(e.g. employeeID, employeeName etc. of a datasource ) to use for filtering items.
To use multiple fields, you have to set one of the fields to hold concatenated fields during parsing of datasource in your schema as given below.
Then set your filter of AutoComplete to "contains"
I did it as follows.
var myDataSrc = new kendo.data.DataSource({
transport: {
read: {
type:"GET",
url:clientDataURL,
dataType: "jsonp",
contentType: "application/json",
}
},
schema: {
parse: function(clntDB) {
$.each(clntDB, function(ky, clnt) {
clnt.firstName = clnt.clientUID + " | " + clnt.firstName+ " " + clnt.lastName;
});
return clntDB;
}
},
pageSize: 4 // Number of Items to show during input
});
/// See the firstName above it's reconstructed to hold concatenated lastname , ID and firstname string.
Next step is to use parsed firstName as a value of dataTextField of kendo Autocomplete.
Then
var selectedClntID; //// Actually, this aims at getting the ID for future use
$("#YOURSEARCHINPUTID").kendoAutoComplete({
dataSource: myDataSrc ,
template: tmplSrchdClnt, // YOUR TEMPLATE like "<div>firstName</div>"
dataTextField:"firstName",
filter:"contains", /// DON'T FORGET TO ADD THIS
minLength : 1 ,
select: function(e) {
var selectedClnt = this.dataItem(e.item.index()),
x = kendo.stringify(selectedClnt);
selectedClntID = JSON.parse(x);
}
// headerTemplate: '<div><h2>ID - LastName</h2></div>'
});
However, tough to find resource indicating like this, it's awesome when you see it working.This is engine of my project when it comes to autocompletion. I did it this way.
Alternatively, you can convert to
data = new Employee(firstname, lastname, ID); // on client side
function Employee( firstname, lastname, ID ){
this.filterStr = firstname + ""+lastname+" "+ID;
}
give data to kendo AutoComplete dataSource and use filterStr as dataTextField.
Another code example adding a new field to the datacourse to use as dataTextField.
// Build our data source object.
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: readUrl,
}
},
group: {field: "region"},
schema: {
data: function(response) {
$.each(response, function(k, v) {
response[k].searchString = v.airport + " " + v.iataCode;
});
return response;
}
}
});
$(selector).kendoAutoComplete({
dataTextField: "searchString",
filter: "contains",
template: '<span class="k-state-default">#: data.airport # (#: data.iataCode #)</span>',
height: 400,
dataSource: dataSource,
});
I'm using jQuery ui's sortable. A list of objects is retrieved from the db an dynamically put into a list, the user drag and drops the list objects and the new order of the list should get saved.
Below is the jQuery code for sortable, which include creating an array of the new list order. However, next step is to do something so that I'm able to use this array in my php code.
The thing is that the user, apart from sorting the list objects also should be able to add some comments and do some other stuff and then submit it all. That is, I'm using a form for this. By that reason I must be able to put in the array with the list order into the form in some way, and here's where I need some help.
What method should I use? Ajax? Local storage? How could this be accomplished?
$('#listElements').sortable({
update: function(event, ui) {
var order = [];
$('.listObject li').each( function(e) {
order.push($(this).attr('id'));
});
}
});
You'll want to use AJAX to send the order array to PHP like so:
$('#listElements').sortable({
update: function (event, ui) {
var order = [];
$('.listObject li').each(function (e) {
order.push($(this).attr('id'));
});
$.ajax({
url: "/save_order_to_db",
type: "post",
data: {
order_data: order
}
}).success(function (data) {
console.log(data);
});
}
});
I have built a jQuery 5 star rating system, ratings are inserted/stored in database along with no of hits, I am having a problem in inserting rating into database when any star is clicked repeatedly.
I.e., if a star is continuously clicked the rating does not get inserted but hits get inserted which then effect the new resulting rating.
I need to add some delay or stop the click function to fire again, it would be better if a delay can be added to click function.
I am trying stop click function to fire again this way but its not working.
jQuery:
$('.u-rating').click(function (e){
var id = $(this).parent().attr('id');
var rating = ($(this).index()+1)/2;
$.ajax({
type: "POST",
url:"rating.php",
data: {rating:rating, id:id},
cache: false,
success: function(data1)
{
get_rating();
$('#u-rating p').html('Rating Submitted');
}
});
e.preventDefault();
e.stopImmediatePropagation();
return false;
});
How do I stop people from rating multiple times?
I would suggest that your real issue that your backend is registering just the hits but not the ratings - and you should probably focus on fixing the issue, not covering it with a band-aid.
Nevertheless, to address your question: You can use one() to bind the click handler just one, and then re-bind on every success (and error). See this jsfiddle for an example. Here is the code:
HTML:
<button id="button">Vote!</button>
JS:
var postClick = function () {
console.log('click fired!!');
el = $(this);
el.prop('disabled', true);
//var id = $(this).parent().attr('id');
//var rating = ($(this).index()+1)/2;
$.ajax({
type: "POST",
url:"/echo/json/",
//data: {rating:rating, id:id},
cache: false,
success: function(data1){
//get_rating();
//$('#u-rating p').html('Rating Submitted');
console.log('ajax success, starting timeout peridod. Clicks will not register now, for the next 5 seconds!');
setTimeout(function() {
$('#button').one('click', postClick);
el.prop('disabled', false);
console.log('Clicks are re-enabled!');
}, 5000);
}
});
}
$('#button').one('click', postClick);
If your voters are logged-in users, store all ratings made by these users in a table with their user_id, then there's absolutely no problem keeping track of votes. If not, store them in a table with a date and an ip-address.
Since ip's can renew and point to a different user after an approximate interval, you can set a timeout date of about at day/week or so. This would have the drawback that users can keep voting once a day/week (if they haven't changed ip's), I don't know if that's acceptable in your project.
Then you can just (pseudo-code)
if (not exists sql("select rating from voteditems
where ipaddress = #ip_adress // Switch to "user_id" if that's what you're using
and item_id = #item_id
and datevoted > getdate()-1")) // Or -7 or whatever interval you choose
{
insert_rating();
}
The hits can be counted as
select count(rating) from voteditems where item_id = #item_id
ok, so I have a database comprising of two tables, products and suppliers.
All suppliers fill in a form and their data is then stored in the suppliers table, and the products table contains a list of all of the products, so when the supplier fills in the form, he can choose as many products as he wishes as I use jQuery JSON and AJAX to get the list of all of the products and then populate a drop down list with all of them in it, which can then be cloned as many times as is needed.
The problem I am sitting with now is, how do I insert all of the different products the supplier chooses into the supplier table, or should I rather just relate all of the products he chooses to the one supplier for better normalization since all the products are already there?
I will be using jQuery $.ajax to POST the form data in JSON format to a waiting PHP file, which will then parse it and insert the data into the database.
So basically, I need to figure out how to relate the data in the database to achieve the best normalization possible, and I need to figure out a way of inserting a variable amount of products into the suppliers table or find a way to relate the many products he chooses to the one supplier.
I am very new to relational databases, so any advice on how to proceed would be a great help, so would any other advice you guys may have!
The jQuery code I use to populate clone and POST the products the supplier chooses:
$(document).ready(function() {
var count = 0;
//when clicked it will remove the closest div with a class of 'container'
$("span.remove").live('click', function(){
$(this).closest("div.container").fadeOut(400, function(){
$(this).remove();
$('#button').attr('disabled','');
});
});
//initialize the button
$('#button').attr('disabled','');
$('#button').click(function(){
var count = $("#systems_wrapper > .container").size();
var lastID = $("#systems_wrapper > .container:last").attr('id');
var exploded = lastID.split("_");
var increment = Number(exploded[1])+1;
//if the user has selected 5 products, disable the 'add' button
if(count >= 5){
$('#button').attr('disabled','disabled');
}else {
$('#button').attr('disabled','');
}
//clone the first drop down and give it a different ID, as well as it's child elements
var test = $('#systems_0.container').clone().attr('id', 'system_' + increment).appendTo('#systems_wrapper');
test.children(':nth-child(2)').append('<span class="remove"></span>');
test.children(':nth-child(2)').children(':first').attr('id', 'mail_' + increment).attr('class','dropDowns').attr('onchange','test();');
});
//get the products JSON object returned from test_post.php and run the necessary functions on the returned data
$.getJSON("test_post.php", function(data){
//clean out the select list
$('#box').html('');
//run the loop to populate the drop down list
$.each(data, function(i, products) {
$('#box').append(
$('<option></option>').html(products.products)
);
});
});
});
//this gets all of the products chosen and then gets each ones value and ID, and then posts it to the qwer.php file
function test(){
var sections = $('#systems_wrapper').find('.dropDowns');
var newArray = new Array();
sections.each(function(){
var id = $(this).attr('id');
var val = $(this).val();
var o = { 'id': id, 'value': val };
newArray.push(o);
});
alert(newArray);
$.ajax({
type: "POST",
url: "qwer.php",
dataType: 'json',
data: { json: JSON.stringify(newArray) }
});
}
Thanx in advance!
If i understand the problem correctly from a database level, should you be using an intermediate table called something like ProductSupplier containing a Product_ID and Supplier_ID column.
Then when a supplier selects a product, add both the supplier and product id to a new column in this table.
This will allow multiple suppliers to pick the same product and multiple products to be picked by the same supplier.
EDIT: I meant to say "add both the supplier and product id to a new ROW in this table"
I have a dilemma that just seems beyond my abilities at the moment!
I have a group of connected sortables using the class 'biglist'.
What I want to do is bind #biglist 's sortreceive callback (which is made whenever a list receives an element from another) to take the 'boxnum' value of the element (which signifies which list its coming from) and perform an UPDATE query changing the id's boxnum value from say 5(list it came from) to 7 (list its been dragged to) so that the state persists.
So the exchange would happen like so (roughly)
$( "#biglist" ).bind( "sortreceive", function(event, ui) {
ajax call to boxchange.php
create vars to represent elements 'boxnum' value and 'box moved to' value
});
Then inside boxchange.php ->
$id = $_POST['id']
$box = $_POST['boxnum']
->update query SET boxid to new boxid WHERE id = posted ID of element
I hope this makes sense. It seems like a pretty slick way to make my program work!
Any help is greatly appreciated.
EDIT:
Just cleaned up the function to see if there are any changes that need to be made to it (which I know there are, because it looks sloppy) This function would need to be copied/altered for each sortable separately but it'd totally make the program work at least!
function ReceiveTwo()
{
$('#sortable2').bind('sortreceive', function(event, ui)
{
boxnum = $(this).attr('boxnum');
id = $(this).attr('id');
$.ajax
({
url: "boxchange.php",
type: "POST",
data: boxnum, id,
success : function(feedback)
{
$('#data').html(feedback)
}
})
});
$('#sortable2').sortable("refresh");
});
$('#sortable2').bind('sortreceive', function(event, ui) {
$.ajax({
url: "boxchange.php",
type: "POST",
beforesend: function(){
boxnum = $(this).attr('boxnum');
id = $(this).attr('id');
},
data: {'boxnum': boxnum, 'id': id},
success : function(feedback) {
$('#data').html(feedback),
}
});
});
beforesend is the event that fires before the ajax call. I believe here you could set your properties to accomplish what you want.
I think the way you want to send your Javascript data to your server-side PHP script is using a Javascript associative array, like so:
$.ajax({
url: "boxchange.php",
type: "POST",
data: {'boxnum': boxnum, 'id': id},
success: function(data,status) { ... }
Your "boxchange.php" script would then be able to access those variables via $_POST['boxnum'] and $_POST['id'].
I think that was your goal, but I'm not entirely sure...