jQuery sortable - PHP - php

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
});

Related

jquery mobile AJAX call from listview

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>

jQuery: Change an element value after Ajax Call

I am trying to change the value of a span after using jQuery.ajax.
JavaScript
$(document).on('click', '.kssico', function(event) {
var for_uid = $(this).parents("li").attr('data'),
for_name = $(this).parents("li").attr('unme'),
dataString = "for_uid=" + for_uid + "&for_name=" + for_name;
$.ajax({
type: "POST",
url: "include/ajax.php",
data: dataString,
success: function (html) {
if(html=="300") {
$('#myModal .modal-body p').html("Error Please Try Again.");
$('#myModal').modal('show');
}
else {
$(this).parents("li span.mi-val").html(html);
$('#myModal .modal-body p').html("The Requested Action Has Been Notified To Your Friend.");
$('#myModal').modal('show');
}
}
});
});
HTML
<li class="mispan main-span" >
<div class="thumbnail">
<h3 class="miheader">Dewashree Singh</h3>
<a >
<div class="miprofile-pic-cnt" ></div>
</a>
<div class="caption">
<p>
<a href="#" class="btn kssico miclickks">
<img src="/lisps.png"><span class="mi-val">0</span>
</a>
<a href="#" class="btn bdico miclickbd">
<img src="/besd.png"><span class="mi-val">1</span>
</a>
</p>
</div>
</div>
</li>
When I click on a.miclickks it should complete the Ajax call and return a value too be placed inside the span on the button anchor. However, nothing is being changed!
jsFiddle
I don't know what your whole code looks like, but you should be able to modify this to do what you are trying to:
$('#id').on('click', function() {
var that = this;
$.ajax({
url: 'wherever.php',
success: function(html) {
$(that).find("li span.mi-val").html(html);
}
});
It looks like you have two problems. The first is that as #Barmar posted above, mi-val is a child of micclickks, not a parent. The second is that your ajax complete function is asynchronous, so $(this) isn't what you expect it will be. Both of these are solvable though.
Your code is a bit messy and your html is missing the proper attributes, but this is I think roughly what you want:
$('.kssico').on('click', function(event) {
var for_uid = $(this).parents("li").attr('data'); //the li element in your html doesn't have a data attribute
var for_name = $(this).parents("li").attr('unme'); //the li element in your html doesn't have a 'unme' attribute
var dataString = "for_uid=" + for_uid + "&for_name=" + for_name;
$.ajax({
type: "POST",
context: this,
url: "include/ajax.php",
data: dataString,
success: function (html) {
if(html=="300")
{
$('#myModal .modal-body p').html("Error Please Try Again.");
$('#myModal').modal('show');
}
else
{
$(this).parents("li span.mi-val").html(html);
$('#myModal .modal-body p').html("The Requested Action Has Been Notified To Your Friend.");
$('#myModal').modal('show');
}
}
});
});

retrieve file location return string after ajax call for jplayer

i am building a mpe player for my production website, using the jplayer. the problem i have is i give my visitors the full song to listen to and for that reason i have to attempt to secure my music so heres the problem. jplayer requires a string that is a file location to the track that is to be played. i would like to make a ajax call and return that location. i tried to return a varible after a ajax call to be placed in the string location,but the code runs threw before the call is finish....
heres my code:
html markup:
<div id="player"></div>
<!-- Using the cssSelectorAncestor option with the default cssSelector class names to enable control association of standard functions using built in features -->
<div id="jp_container" class="demo-container">
<p>
<div class="pro"></div>
<span class="play-state"></span> : <span class="track-name">nothing</span><br />
of <span class="jp-duration"></span>, which is
<span class="jp-current-time"></span><br />
</p>
<ul class="toolbar ui-widget-header ui-corner-all">
<li><button class="jp-Prev" href="#">Prev</button></li>
<li><button class="jp-play" href="#">Play</button></li>
<li><button class="jp-pause" href="#">Pause</button></li>
<li><button class="jp-stop" href="#">Stop</button></li>
<li><button class="jp-Next" href="#">Next</button></li>
<li><button class="jp-mute" href="#">Mute</button></li>
<li><button class="jp-unmute" href="#">Unmute</button></li>
<li><div class="jp-volume-bar"></div></li>
</ul>
<ul class="playlist">
<li><span>Select a track :</span></li>
<? Beats(); ?>
</ul>
</div>
Jquery markup:
$("#jp_container .track").on("click",function(event) {
var x = $(this).attr('id');
var mp3File = // maybe a function can go here
my_jPlayer.jPlayer("setMedia", {
mp3: //this is where the string is expected
});
my_jPlayer.jPlayer("play");
my_trackName.text($(this).text());
$(this).blur();
return false;
});
// here is were i get the location in a function i workout already
function url(x){
var mp3;
$.ajax({
type: "POST",
url: "hosts/beats/beat.php",
data: "<?=md5('url')?>="+x+"&ok=<?=md5(rand(1,20))?>",
dataType: "html",
success:function(data){ var mp3 = data; }
});
return mp3;
}
first "A" in AJAX is for ayshnchronous...you can't return mp3 from your function because the ajax hasn't completed when you try returning it.
You need to do the setMedia within success callback of ajax
$("#jp_container .track").on("click", function(event) {
var x = $(this).attr('id');
$.ajax({
type: "POST",
url: "hosts/beats/beat.php",
data: "<?=md5('url')?>=" + x + "&ok=<?=md5(rand(1,20))?>",
dataType: "html",
success: function(data) {
my_jPlayer.jPlayer("setMedia", {
mp3: data
});
my_jPlayer.jPlayer("play");
my_trackName.text($(this).text());
$(this).blur();
}
});
return false;
});

Jqueryui sortable list with ajax update

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

Deleting a list item <li> with jquery?

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);
}
?>

Categories