How Make Div Sortable And Updating Value In Database - php

i want to make my divs sort-able using jquery and getting their current new position so i can update that into database. i tried but not succeed. my code is
<div id="d">
df
</div>
<div id="d">
df
</div>
<div id="d">
df
</div>
jquery code is
$(document).ready(function(){
$('#d').sortable({
placeholder: "ui-state-highlight",
helper: 'clone'
});
});
})
anyone please help me out .thanks

jQuery UI sortable feature includes a serialize method to do this. It's quite simple, really. Here's a quick example that sends the data to the specified URL as soon as an element has changes position.
$('#el1').sortable({
axis: 'y',
update: function (event, ui) {
var data = $(this).sortable('serialize');
// POST to server using $.post or $.ajax
$.ajax({
data: data,
type: 'POST',
url: '/your/url/here'
});
}
});
It creates an array of the elements using the elements id. So, I usually do something like this:
<div id="el1" class="ui-sortable">
<div id="item_1">
df
</div>
<div id="item_2">
df
</div>
<div id="item_3">
df
</div>
</div>
Serialize option will create a POST query string like this: item[]=1&item[]=2 . So if you make use - for example - your database IDs in the id attribute, you can then simply iterate through the POSTed array and update the elements' positions accordingly.
$i = 0;
foreach ($_POST['item'] as $value) {
// Execute statement:
// UPDATE [Table] SET [Position] = $i WHERE [EntityId] = $value
$i++;
}

Related

Codeigniter - refresing multiple elements with multiple contents using JQuery ajax?

what I want to achieve is that multiple divs in my view get fill up with different content using ajax at the same time when a button is clicked, let's say something like this:
view:
<div id="one">
</div>
<div id="two">
</div>
<div id="three">
</div>
div one, two and three should be refreshed with different content each one.
my script is:
$("input[type='button']").click(function(){
var mail= $("#mail").val();
var password = $("#password").val();
$.ajax({
url: '<?php echo base_url()?>index.php/login/theLogin',
type: 'POST',
data: {'mail':mail, 'password':password},
success: function(data) {
$('div#one').html(data);
$('div#two').html(data);
$('div#three').html(data);
}
});
});
controller:
public function theLogin()
{
$this->load->view("ajax/newContent");
}
newContent.php:
<div id="ajax-one">
one
</div>
<div id="ajax-two">
two
</div>
<div id="ajax-three">
three
</div>
and the result is obviously the three divs in my view get refreshed with three divs (9 divs in total), but I don't want that, I want that div one gets refreshed only with the content of div ajax-one and so on.
I used something like this in my ajax method but no success:
success: function(data) {
$('#one').html($('#ajax-one' , data).html());
$('#two').html($('#ajax-two' , data).html());
$('#three').html($('#ajax-three' , data).html());
}
What possible solution could exists to solve this? thanks.
I would replace the DIVs with the new DIVs. So if you have a parent DIV you can replace the whole thing with the new data.
Consider this being your initial view:
<div id="myWrapperDiv">
<div id="one">
</div>
<div id="two">
</div>
<div id="three">
</div>
</div>
When your data is returned do this:
$("#myWrapperDiv").html(data);
UPDATE:
Since that was not a good option for you I have come up with another possible solution. Personally I would return a JSON array that separated the DIVs, however, I will offer a suggestion to work with your current code. I would split the return into an array and process it from there.
Let me show you. In the below we split the data on the closing div tags with a limit of 3. Without the limit you will get an empty string at the end of your array. Then we replace the contents of your DIVs with the ajax DIVs. We have to add back the closing div tags since it was removed when we split the data. I hope this helps :).
var myArray = data.split("</div>",3);
$("#one").html(myArray[0] + "</div>");
$("#two").html(myArray[1] + "</div>");
$("#three").html(myArray[2] + "</div>");
Here is a working fiddle. Change you response data to jQuery object. Hope this is what you need.
$("input[type='button']").click(function(){
var data = '<div id="ajax-one"><span>one</span></div><div id="ajax-two">two</div><div id="ajax-three">three</div>';
var $dataObj = $(data);
$('#one').html($dataObj[0]);
$('#two').html($dataObj[1]);
$('#three').html($dataObj[2]);
});

My mess that I'm trying to do with PHP, MySQL, jQuery and css

Let's see if I can explain what I'm trying to do here..
I've got a MySQL Database with some info stored in it. I am using PHP to query the database, pull my selected entries out, put each one into a separate <div> (with Bootstrap framework). I have accomplished this part.
Below is a snippet of what I'm doing...
$query = "SELECT `quote`,`id` FROM `db`";
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result))
{
echo ' <div class="panel panel-info">
<div class="panel-body text-muted" id="'.$row['id'].'">
'.$row['quote'].'
</div>
</div>';
}
Then I am wanting to use jQuery to add a css class on "click" to an individual <div> and be able to then use PHP to store the text of the "selected" <div> to a variable, for later use.
This is the part I am struggling with, I can not figure out how to separate each individual <div> specifically and have jQuery add the class to it, because the "id" of div differs with every result from the db query.
To add a class to a div when it is clicked -
jQuery
$('div').click(function() {
$(this).addClass('foo');
var divText = $(this).text(); // store to JavaScript variable
});
Now that you have the JavaScript variable stored you can send it to a PHP function via AJAX.
What I would do is add a class to the <div>s, and use that to attach the event.
<div class="panel-body text-muted click-panel" id="'.$row['id'].'">
Then in your JavaScript, do something like:
$(function(){
$('div.click-panel').click(function(){
var div_id = this.id,
div_text = $(this).text();
if(/* some condition eg. div_id === 5 */){
$(this).addClass('clicked');
}
});
});

dynamically handle jquery events [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have a list of main subjects streams. let's say they are Art, Science, Commerce. For each main steam there are several subjects.
Such as for Science, subjects are Mathamatics, Bio Science and etc.
When a user select a main stream, I want to show relevent subjects for the selected main stream.
I use jquery pannels. Basicaly, when a stream is checked the releveant subjects div will be toggle.
I get Main stream and subjects are from database. they can be change(dynamic). So how to handle this?
I used following code. But this is not dynamic.
$("#Science").change(function(){
$("#Mathas").slideToggle("fast");
});
$("#Bio_cience").change(function(){
$("#b").slideToggle("fast");
});
$("#Pure_Maths").change(function(){
$("#cc").slideToggle("fast");
});
I want to make above script dynamic. How to proceed?
You need something common between your checkbox and the div, and you probably don't need to make another trip to the server (via ajax) to do this. Instead add an attribute when you generate the page with PHP and then use the jQuery data() method to help make the association. For example:
<input type="checkbox" data-category="a">
<input type="checkbox" data-category="b">
<div id="main-stream-art-a">Content A</div>
<div id="main-stream-art-b">Content B</div>
<script>
$(function(){
$('input[type="checkbox"]').change(function() {
var category = $(this).data('category');
$('#main-stream-art-sub-' + category).slideToggle("fast");
});
})
</script>
Your html will like...
<div id="1sub" class="sub">sub1</div>
<div id="2sub" class="sub">sub2</div>
<div id="3sub" class="sub">sub3</div>
<div id="stream-1" class="stream" style="display:none;">Stream 1</div>
<div id="stream-2" class="stream" style="display:none;">Stream 2</div>
<div id="stream-3" class="stream" style="display:none;">Stream 3</div>
Now,in jquery
$(".sub").click(function(){
var subClicked = $(this).attr('id');
$(".stream").hide();
$("#stream-" + subClicked.substring(0,1)).toggle();
});
To periodically get updates from the server, you could use AJAX something like this:
function load_subjects(){
$.ajax({
url: "http://www.example.com/loader",
cache: false,
success: function(html){
$("#items").html(html);
}
});
}
setInterval(load_subjects, 240000);
I depends on how much data you need to load. It's a personal choice really, if there are just a few records then you could load them into an array as the page loads, for larger data sets I would use ajax.
Something like this can load html into your #display area
$("#Main_stream_arts").change(function(){
$.ajax({
type: "POST",
url: "some.php",
dataType: "html",
data: { id: $(this).val()}
}).done(function(html) {
$("#display").html(html);
});
});
You could also change the dataType to json and output a json encodeed string from PHP
Or a shorter version - depending on how much control you want:
$("#Main_stream_arts").change(function(){
$('#display').load('some.php?id='+$(this).val());
});
You could create a HTML structure like this which you could duplicate for every stream. This will be helpful if you have multiple streams in your HTML.
<div class="container">
<div class="header">
<input type="checkbox" value="Electronics" id="electronics" />
<label for="electronics">Electronics</label>
</div>
</div>
Then, assuming your data in database looks like this ,
{
"Electronics": [
"VLSI",
"Tele Communication",
"Digital Circuits",
"Analog Communication"
],
"Medicine": [
"MBBS",
"MD",
"General Surgeon",
"Dental"
],
"Computers": [
"fuzzy logic",
"DataStructures",
"JavaScript"
]
}
You could get value by json["Electronics"] - that's how we'll simulate an ajax call. Then your change event would look like this.
$(".header [type=checkbox]").change(function () {
//remove all the older values - not necessary
$(".content").slideToggle(500, function () {
e.preventDefault();
$(this).remove();
});
//check if youre checking or unchecking
if (this.checked) {
//choosing header
var $header = $(this).closest(".header");
//building container element with ul for subjects in stream
var $content = $("<div/>", {
"class": "content"
}).append("<ul></ul");
var value = this.value;
//simulate ajax call -
var json = res[value];
//ajax here. result is json
//ajax success start - starting here , you could put this in the success function of ajax
//construct the lis - u could do it in any way
var $li = $.map(json, function (val, i) {
return "<li>" + val + "</li>";
});
//add the li to the uls
$content.find("ul").append($li);
//insert the content after specific header
$content.insertAfter($header).promise().done(function () {
//wait for the append to happen, else you wont get the animation
//open up the content needed
$content.slideToggle(500);
});
//ajax success end
}
});
Basically we're adding an element which contains the subjects in a stream dynamically right next to the header. So this will help if you have multiple streams in your HTML. So the resulting HTML would look like this :
<div class="container">
<div class="header">
<input type="checkbox" value="Electronics" id="electronics" />
<label for="electronics">Electronics</label>
</div>
<div class="content">
<ul>
<li>Fuzzy Logic</li>
<!--more li's like this-->
</ul>
</div>
</div>
Demo : http://jsfiddle.net/hungerpain/Uyugf/

jQuery UI Sortable, then write order into a database

I want to use the jQuery UI sortable function to allow users to set an order and then on change, write it to the database and update it. Can someone write an example on how this would be done?
The jQuery UI sortable feature includes a serialize method to do this. It's quite simple, really. Here's a quick example that sends the data to the specified URL as soon as an element has changes position.
$('#element').sortable({
axis: 'y',
update: function (event, ui) {
var data = $(this).sortable('serialize');
// POST to server using $.post or $.ajax
$.ajax({
data: data,
type: 'POST',
url: '/your/url/here'
});
}
});
What this does is that it creates an array of the elements using the elements id. So, I usually do something like this:
<ul id="sortable">
<li id="item-1"></li>
<li id="item-2"></li>
...
</ul>
When you use the serialize option, it will create a POST query string like this: item[]=1&item[]=2 etc. So if you make use - for example - your database IDs in the id attribute, you can then simply iterate through the POSTed array and update the elements' positions accordingly.
For example, in PHP:
$i = 0;
foreach ($_POST['item'] as $value) {
// Execute statement:
// UPDATE [Table] SET [Position] = $i WHERE [EntityId] = $value
$i++;
}
Example on jsFiddle.
Thought this might help as well. A) it was designed to keep payload to its minimum while sending back to server, after each sort. (instead of sending all elements each time or iterating through many elements that server might chuck out) B) I needed to send back custom id without compromising the id / name of the element. This code will get the list from asp.net server and then upon sorting only 2 values will be sent back: The db id of sorted element and db id of the element next to which it was dropped. Based on those 2 values, server can easily identify the new postion.
<div id="planlist" style="width:1000px">
<ul style="width:1000px">
<li plid="listId1">List 1</li>
<li plid="listId2">List 1</li>
<li plid="listId3">List 1</li>
<li plid="listId4">List 1</li>
</ul>
<div id="pl-1"></div>
<div id="pl-2"></div>
<div id="pl-3"></div>
<div id="pl-4"></div>
</div>
<script type="text/javascript" language="javascript">
$(function () {
var tabs = $("#planlist").tabs();
tabs.find(".ui-tabs-nav").sortable({
axis: "x",
stop: function () {
tabs.tabs("refresh");
},
update: function (event, ui) {
//db id of the item sorted
alert(ui.item.attr('plid'));
//db id of the item next to which the dragged item was dropped
alert(ui.item.prev().attr('plid'));
//make ajax call
}
});
});
</script>
You're in luck, I use the exact thing in my CMS
When you want to store the order, just call the JavaScript method saveOrder(). It will make an AJAX POST request to saveorder.php, but of course you could always post it as a regular form.
<script type="text/javascript">
function saveOrder() {
var articleorder="";
$("#sortable li").each(function(i) {
if (articleorder=='')
articleorder = $(this).attr('data-article-id');
else
articleorder += "," + $(this).attr('data-article-id');
});
//articleorder now contains a comma separated list of the ID's of the articles in the correct order.
$.post('/saveorder.php', { order: articleorder })
.success(function(data) {
alert('saved');
})
.error(function(data) {
alert('Error: ' + data);
});
}
</script>
<ul id="sortable">
<?php
//my way to get all the articles, but you should of course use your own method.
$articles = Page::Articles();
foreach($articles as $article) {
?>
<li data-article-id='<?=$article->Id()?>'><?=$article->Title()?></li>
<?
}
?>
</ul>
<input type='button' value='Save order' onclick='saveOrder();'/>
In saveorder.php; Keep in mind I removed all verification and checking.
<?php
$orderlist = explode(',', $_POST['order']);
foreach ($orderlist as $k=>$order) {
echo 'Id for position ' . $k . ' = ' . $order . '<br>';
}
?>
This is my example.
https://github.com/luisnicg/jQuery-Sortable-and-PHP
You need to catch the order in the update event
$( "#sortable" ).sortable({
placeholder: "ui-state-highlight",
update: function( event, ui ) {
var sorted = $( "#sortable" ).sortable( "serialize", { key: "sort" } );
$.post( "form/order.php",{ 'choices[]': sorted});
}
});
I can change the rows by following the accepted answer and associated example on jsFiddle. But due to some unknown reasons, I couldn't get the ids after "stop or change" actions. But the example posted in the JQuery UI page works fine for me. You can check that link here.
Try with this solution: http://phppot.com/php/sorting-mysql-row-order-using-jquery/
where new order is saved in some HMTL element.
Then you submit the form with this data to some PHP script,
and iterate trough it with for loop.
Note: I had to add another db field of type INT(11) which is updated(timestamp'ed) on each iteration - it serves for script to know which row is recenty updated, or else you end up with scrambled results.

Creating a JSON object from multiple form fields using jQuery

I am trying to create a JSON object from a bunch of grouped HTML elements, this is my markup,
HTML:
<div id="locations_wrapper">
<div id="location_0" class="locations">
<div class="container">
<label for="locations_province">Province: </label>
<div>
<select id="locations_province" name="locations_province" onchange="get_cities(this);">
<option value="">Select one</option>
<option>Eastern Cape</option>
<option>Freestate</option>
<option>Gauteng</option>
<option>KZN</option>
<option>Limpopo</option>
<option>Mpumalanga</option>
<option>North West</option>
<option>Northern Cape</option>
<option>Western Cape</option>
</select>
</div>
</div>
<!-- City -->
<div class="container">
<label for="locations_city">City: </label>
<div>
<select id="locations_city" name="locations_city">
<option value="">Select one</option>
</select>
</div>
</div>
<!-- Towns -->
<div class="container">
<label for="locations_towns">Towns: </label>
<div>
<input type="text" name="locations_towns" id="locations_towns" />
</div>
</div>
</div>
</div>
At the moment I am cloning these 3 fields and appending them to the parent div locations_wrapper, I also increment the id attribute of each field, the problem now is that I need to get all of the cloned elements and somehow, using jQuery/ajax, capture all of the data of each location into a database.
How could I go about getting that information?
here is some jQuery I wrote that basically does the same thing, but with one fied instead of 3:
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);
});
$.ajax({
type: 'POST',
url: 'qwer.php',
dataType: 'json',
data: { json: JSON.stringify(newArray) }
});
Maybe I could try creating a JSON object with 3 fields province, city and town? I am a little unsure.
Thanx in advance!
The easiest way to serialize a form as JSON is to use jQuery's serializeArray():
JSON.stringify($("#myForm").serializeArray());
You will need to wrap a form around your HTML for this to work though. It won't change the behavior.
http://api.jquery.com/serializeArray/
It's not very clear, from your question, what you're trying to accomplish. But I'm guessing, from your markup, that you're building something that will allow the user to add multiple "locations" within the "locations_wrapper" object. This sort of thing usually starts with markup like you've shown, providing a single blank "location" form for the user to fill in (3-fields, in this case); and a button that they can click to add additional "location" blocks as needed.
Assuming that this is what you're doing, my first suggestion would be that, instead of cloning the three form fields individually, you should be cloning only their parent container, "location_0". Something like this should do the trick:
$('#location_0').clone().appendTo('#locations_wrapper');
That will copy the entire block -- and you don't really need to worry about changing the ids of things, jQuery and/or the browser will take care of ensuring that everything has a unique id behind-the-scenes.
Now, assuming that your markup is located within a form, the easiest way to get the information back up to the server is just to submit the form. The form post will contain multiple fields with the same name -- which is completely valid, and most server-side languages have a simple way of dealing with it.
In php, multi-value request parameters come in as an array. So in php, you could do something like this:
<?php
$field_names = ['locations_province', 'locations_city', 'locations_town'];
$locations = array();
foreach( $field_names as $fieldname ) {
$temp = (array)$_REQUEST[$fieldname];
for( $i=0; $i<count($temp); ++$i ) {
if( !isset($locations[$i]) ) $locations[$i] = array();
$locations[$i][$fieldname] = $temp[$i];
}
}
If you'd rather aggregate it all in javascript, you can access your field groups like this:
var allLocations = [];
$(".locations").each( function(i, location) {
// for each location block
location = $(location);
var loc = {
'locations_province' : $("select[name='locations_province']", location).val(),
'locations_city' : $("select[name='locations_city']", location).val(),
'locations_towns' : $("input[name='locations_towns']", location).val()
};
allLocations.push( loc );
});
// allLocations will contain a list of objects with properties representing
// your locations. at this point, you can do whatever you want with 'em
// send them up via Ajax, or whatever.
good luck!
My thought, if you've got control over what the server can accept, would be to pass a bag instead of an array e.g.
{"province" : "", "city" : "", "town" : ""}
I'd then create a payload object:
var province, city, town, payload;
province = $("#locations_province").val();
city= $("#locations_city").val();
town= $("#locations_town").val();
payload = {"province" : province, "city" : city, "town" : town};
...and give the payload to $.ajax:
$.ajax({
type: 'POST',
url: 'qwer.php',
dataType: 'json',
data: payload
});
jQuery will URI encode the payload for you.
You can streamline the payload creation even further if you use Mustache.

Categories