I am using CodeIgniter with the jQuery UI Sortable widget, to change my menu list position.
For example, if my menu list is like this:
<li>menu 1</li>
<li>menu 2</li>
<li>menu 3</li>
<li>menu 4</li>
I want to place the first menu under the second and have it stay there.
However I am stuck on the jQuery a bit.
This is what gets the list elements:
<ul id="sortable">
<?php foreach ($rows as $r)
{
echo '
<li id="sort_'.$r->pid.'" class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>
' . $r->page_name . '
</li>';
}
?>
</ul>
and the jquery:
$( "#sortable" ).sortable({
placeholder: "ui-state-highlight",
opacity: 0.6,
update: function(event, ui) {
var info = $(this).sortable("serialize");
alert(info);
}
});
$( "#sortable" ).disableSelection();
I managed to alert the array of the results.
Now I don't want anybody to write this for me, just a hint on how to use ajax with this for the update.
I think you can use $.ajax(..) inside your update method.
http://api.jquery.com/jQuery.ajax/
$.ajax({
url: "submit.php",
data: info,
context: document.body,
success: function(){
// success
}
});
I just check info is already serialized, so this should work. You can add method property depending on submit type (post, get).
First of all thanks for Kamil Lach for his hint, i managed to do it
Here is my code maybe someone wull make a use for it
created a function in my controller and loaded the model in it
function sort_items()
{
$this->load->model("admin/pages_model");
$this->pages_model->sort_insert();
}
the model
function sort_insert()
{
foreach($this->input->post("sort") as $p => $id)
{
$this->db->query(" UPDATE c_pages SET sort = ".$p." WHERE pid = ".$id." ");
}
}
the $p vaiable is the short position and the id is the menu id
and the jquery
$( "#sortable" ).sortable({
placeholder: "ui-state-highlight",
opacity: 0.6,
update: function(event, ui) {
var info = $(this).sortable("serialize");
$.ajax({
type: "POST",
url: "http://localhost/frame/admin/pages/sort_items",
data: info,
context: document.body,
success: function(){
// alert("cool");
}
});
}
});
$( "#sortable" ).disableSelection();
i passed the url to my controller function where my update model is loaded
and the view file
<?php if($rows) { ?>
<ul id="sortable">
<?php foreach ($rows as $r)
{
echo '
<li id="sort_'.$r->pid.'" class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>
' . $r->page_name . '
</li>';
}
?>
</ul>
<?php } else
{
echo "There are no pages created yet";
}
?>
And thanks again for your hint Kamil Lach
Related
I have a list
<ul id="my_ul">
<li data-value="1">111</li>
<li data-value="2">112</li>
<li data-value="3">113</li>
</ul>
I tried to pass the data-value on click event to MySQL query. I tried it with jQuery but when i var_dump the result its NULL.
Here is how i am getting the value
$('#my_ul').on("click", "li", function(){
$.ajax("fetch_test.php",{method:"post", data:{val:$(this).attr("data-value")}});
});
and here is the fetch_test.php file code :
function showValue(){
include_once "connect.php";
$test=$_SESSION['val'];
$query="SELECT * FROM product INNER JOIN smetka on smetka.id=product.smetka_id WHERE product.smetka_id=$test";
$result=mysqli_query($conn,$query);
$alert="";
while($row=mysqli_fetch_array($result)){
$alert .="<li data-value='$row[id]'><a href='test.php'>$row[name]";
$alert .= "</a></li>";
}
return $alert;
}
How can i pass the data-value from the li?
You should bind the event handler with anchor element and use event.preventDefault() to cancel its the default action. You can use .closest() to traverse up to li element.
$('#my_ul').on("click", "li a", function(e) {
//Cancels default action of anchor
e.preventDefault();
var value = $(e.target).closest('li').data("value");
console.log(value);
$.ajax({url: "fetch_test.php", method:"post", data:{val:value}});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="my_ul">
<li data-value="1">111</li>
<li data-value="2">112</li>
<li data-value="3">113</li>
</ul>
Use event.preventDefault() to prevent redirection to test.php
Instead of
$('#my_ul').on("click", "li", function(){
$.ajax("fetch_test.php",{method:"post", data:{val:$(this).attr("data-value")}});
});
Use
$('#my_ul').on("click", "li", function(event){
event.preventDefault();
$.ajax("fetch_test.php",{method:"post", data:{val:$(this).attr("data-value")}});
});
I have a table populated with two types of php variables from a single query. I want the reader to see the table with typeA variables, then switch to the same table but with viewB.
The reader can switch views from a little popup menu, which has list items "View A" and "View B"
I am trying to accomplish the view switch via an AJAX call, but it's not working. Drop down the "eye" menu, select "View B," and nothing happens.
What's not right about this? Any help would be warmly welcomed.
php:
<?php
$sql = //select all type-A and type-B columns//
{// process $sql results, return type-A and type-B variables }
$view = $_REQUEST['name'];
if ($view == 'viewA'){// include('table.php'); echo $table, populated with type-A variables }
if ($view == 'viewB') {// include('table.php'); echo $table, populated with type-B variables }
?>
... and here's the js and html:
$(function() {
$('#popupSwitchView').change(function() {
var theView = $.trim($('.theView').val());
if (theView.length > 0) {
$.ajax({
type: 'POST',
url: 'file.php',
data: ({
name: theView
}),
cache: false,
dataType: 'text',
success: onSuccess
});
}
});
$('#resultLog').ajaxError(function(event, request, settings, exception) {
$('#resultLog').html('Error Calling: ' + settings.url + '<br />HTTP Code: ' + request.status);
});
function onSuccess(data) {
$('#resultLog').html(data);
}
});
<div data-role='page'>
<a href='#popupSwitchView' class=' ui-btn ui-shadow ui-corner-all ui-icon-eye ui-btn-icon-notext ui-nodisc-icon ui-alt-icon ui-btn-inline' data-transition='turn' data-rel='popup' data-inline='true'>Switch view</a>
<div data-role='popup' id='popupSwitchView' data-theme='none'>
<ul data-role='listview'>
<li><a href='#' data-role='button' class='ui-btn-active switchview' name='theView' value='viewA'>View A</a>
</li>
<li><a href='#' data-role='button' class='switchview' name='theView' value='viewB'>View B</a>
</li>
</ul>
</div>
I have two lists
<ul class="sortable" id="list-A">
<li id="1">Value 1 </li>
<li id="2">Value 2 </li>
<li id="3">Value 3 </li>
</ul>
<ul class="sortable" id="list-B">
<li id="4">Value 1 </li>
<li id="5">Value 2 </li>
<li id="6">Value 3 </li>
</ul>
connected like this
$( ".sortable" ).sortable({
connectWith: '.sortable',
placeholder: "widget-highlight"
});
i knew how to save a one ordered list to database by saving the order
but how to save if the user moves an item from list a to list b ?
i want to save the item position but how
Using .sortable()'s .receive() callback, get the dropped node's .index() via ui.item.index(). How you process it in PHP will depend on how your ajax handler is setup.
$( ".sortable" ).sortable({
connectWith: '.sortable',
placeholder: "widget-highlight",
// Receive callback
receive: function(event, ui) {
// The position where the new item was dropped
var newIndex = ui.item.index();
// Do some ajax action...
$.post('someurl.php', {newPosition: newIndex}, function(returnVal) {
// Stuff to do on AJAX post success
});
},
// Likewise, use the .remove event to *delete* the item from its origin list
remove: function(event, ui) {
var oldIndex = ui.item.index();
$.post('someurl.php', {deletedPosition: oldIndex}, function(returnVal) {
// Stuff to do on AJAX post success
});
}
});
The above example will send the dropped node's new list position in $_POST['newPosition']
The events are fully described in the .sortable() API documentation
I am using the jQuery sortable() to order images in a DB. The HTML is as follows.
<h2>Revision 1</h2>
<ul class='sortable'>
<li class='sortPhotos' id='item_249745' >
<img src="../data/gallery/13387/images/album/1650519801.jpg"/>
<p>1650519801.jpg</p>
</li>
<li class='sortPhotos' id='item_249744' >
<img src="../data/gallery/13387/images/album/704633205.jpg"/>
<p>704633205.jpg</p>
</li>
</ul>
<h3>Revision 2</h3>
<ul class='sortable'>
<li class='sortPhotos' id='item_518811' >
<img src="../data/gallery/13387/images/album/001.jpg"/>
<p>001.jpg</p>
</li>
<li class='sortPhotos' id='item_518812' >
<img src="../data/gallery/13387/images/album/003.jpg"/>
<p>003.jpg</p>
</li
</ul>
The JS
<script>
$(".sortable").sortable({stop:function(i) {
$.ajax({
type: "GET",
url: "../albumUploader/queries/sort.php",
data: $(".sortable").sortable("serialize")
});
},
opacity:1.0
});
</script>
And finally the SQL
foreach($_GET['item'] as $key=>$value) {
mysql_query(" UPDATE galleryimage
SET sort = '{$key}'
WHERE id = '{$value}'
");
}
The issue with the above example -- the first revision is the only revision that is actually sorting in the DB. The other revision(s) are not. It does appear from monitoring the network in Chrome web developer extension that both lists are sending to the DB, but the second is not writing. Any ideas on this one?
Each sortable needs to have it's own unique id. I resolved it with:
ul id='sortable_" . $count ."'
$count++;
$(".revisionNum").each(
function(e) {
num = e + 1;
$("#sortable_" + num).sortable(
{stop:function(i) {
serial = $("#sortable_" + num).sortable("serialize");
$.ajax({
type: "GET",
url: "../albumUploader/queries/sort.php",
data: serial
});
},
opacity:1.0
});
});
One solution would be to only send one list to the server at a time. This could be done by sending the data from $(this) instead of from $(".sortable"):
$(".sortable").sortable({stop:function(i) {
$.ajax({
type: "GET",
url: "../albumUploader/queries/sort.php",
data: $(this).sortable("serialize")
});
},
opacity:1.0
});
I'm trying to delete a li item using jquery, but its not working. Here's my code:
the html file:
<li>
<img class="avatar" src="images/$picture" width="48" height="48" alt="avatar" />
<div class="tweetTxt">
<strong>$username</strong> $auto
<div class="date">$rel</div>
$reply_info
<div class="date"></div>
<a class ="delbutton" href="#" id = $id> Delete </a>
</div>
<div class="clear"></div>
</li>
The jquery file:
$(function () {
$(".delbutton").click(function () {
var del_id = element.attr("id");
var info = 'id=' + del_id;
if (confirm("Sure you want to delete this update? There is NO undo!")) {
$.ajax({
type: "POST",
url: "delete.php",
data: info,
success: function () {}
});
$(this).parents(".record").animate({
backgroundColor: "#fbc7c7"
}, "fast")
.animate({
opacity: "hide"
}, "slow");
}
return false;
});
});
the delete.php file:
<?php
include("includes/connect.php");
if($_POST['id'])
{
$id=$_POST['id'];
$sql = "delete from {$prefix}notes where id='$id'";
mysql_query( $sql);
}
?>
There is no element in your HTML with a class of record. I would try something like this:
<li class="record">
<!-- a bunch of other stuff -->
<a class="delbutton" href="#">Delete</a>
</li>
then in the JS:
$(function ()
{
$(".delbutton").click(function ()
{
if (confirm("..."))
{
$.ajax({ /* ... */});
$(this).closest(".record").fadeOut();
}
return false;
});
});
If your div look like this:
<ul>
<li>One | <a href='#' class='delete'>Delete</a></li>
<li>Two | <a href='#' class='delete'>Delete</a></li>
<li>Three | <a href='#' class='delete'>Delete</a></li>
<li>Four | <a href='#' class='delete'>Delete</a></li>
</ul>
jQuery:
jQuery(document).ready(function(){
jQuery('.delete').live('click', function(event) {
$(this).parent().fadeOut()
});
});
Check: http://jsfiddle.net/9ekyP/
EDIT:
You can remove your li after getting response in success function something like this:
jQuery(document).ready(function(){
jQuery('.delbutton').live('click', function(event) {
$.ajax({
type: "POST",
url: "delete.php",
data: info,
success: function(){
$(this).parent().parent().fadeOut();
}
});
});
});
There are several issues with your code...
element.attr("id") references undeclared element but this should probably be $(this).attr("id")
The <li> block has no class ".record" either
EDIT: You only fade your <li> but do not actually remove it from the DOM (don't know if this was deliberate though)
The <a>'s ID is not quoted (and not escaped either... as are the other strings you insert in PHP (EDIT) and the ID you use in your delete script - this is very dangerous as it allows cross-site scripting / XSS and SQL injection as TokIk already pointed out)
PHP:
echo '<li class="record">
<img class="avatar" src="images/'.htmlentities($picture).'" width="48" height="48" alt="avatar" />
<div class="tweetTxt">
<strong>'.htmlentities($username).'</strong> '.htmlentities($auto).'
<div class="date">'.htmlentities($rel).'</div>'.htmlentities($reply_info).'<div class="date"></div> <a class="delbutton" href="#" id="'.htmlentities($id).'"> Delete </a>
</div>
<div class="clear"></div>
</li>';
JavaScript:
$(document).ready(function() {
$(".delbutton").click(function(){
var del_id = $(this).attr("id");
var info = 'id=' + del_id;
if(confirm("Sure you want to delete this update? There is NO undo!")) {
$.ajax({
type: "POST",
url: "delete.php",
data: info,
success: function(){
alert('success');
},
error: function(){
alert('error');
}
});
$(this).parents(".record").animate({ backgroundColor: "#fbc7c7" }, "fast")
.animate({ opacity: "hide" }, "slow");
}
return false;
});
});
EDIT: Delete script (note the additional error check that $_POST['id'] exists and the pseudo-function for quoting the ID):
<?php
include("includes/connect.php");
if( isset($_POST['id']) ) {
$id = quote($_POST['id']);
$sql = "delete from {$prefix}notes where id='$id'";
mysql_query( $sql);
}
?>
I am assuming that '.records' is the container.
You can pass through your ID value to make <li> unique, result being:
<li id='record_12'>
//CONTENT
</li>
<li id='record_13'>
//CONTENT
</li>
And change your SUCCESS script to the following:
$(".delbutton").click(function(){
var del_id = element.attr("id");
var info = 'id=' + del_id;
if(confirm("Sure you want to delete this update? There is NO undo!"))
{
$.ajax({
type: "POST",
url: "delete.php",
data: info,
success: function(){
//Getting the unique LI and fading it out
$('#record_' + del_id).fadeOut();
}
});
Your code works fine well.I was trying to code a form that has multiple textbox, then after each textbox threre will be link called add which POST call the other php called addnew.php.
In addnew.php data will we added to database(postgres). But I am geting problem while getting the post variable itself.
this is my code for form (I will chage for multiple textbox once it works fine)
script:
<script type='text/javascript'>
$(window).load(function() {
jQuery(document).ready(function() {
jQuery('.add').live('click', function(event) {
var da = $('form#myform').serialize();
alert(da);
$.ajax({
type: "POST",
url: "addnew.php",
data:da,
success: function(data) {
if (data === "ok") {
$(this).parent().fadeOut();
$('#results').html(data);
}
else {
alert(data);
}
}
});
});
});
});
Form
<form name='myform' id='myform'>
<input name='da' type='text' id='da' value='none'>
<a href='#' class='add'>Add</a>
</form>
addnew.php code here
<? php
if( isset($_POST['da']) )
{
echo (da);
}
?>