jquery mobile AJAX call from listview - php

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>

Related

how to built ajax tabs in wordpress?

I try to display the departments in my website as tabs, when click one tab it will display the data related to this department according to department_id.
I try this code Execute php function only when clicked (wordpress) but I need the tabs number to be dynamic.
<div class="tabs">
<ul>
<?php
$arr1=array(2,3,5,10,22,25,27,28,29,30);
$arr2=array("dep1","dep2","dep3","dep4",
"dep5","dep6","dep7","dep8","dep9","dep10");
for($i=0;$i<10;$i++){?>
<li><a href="#tab" id="<?php echo $arr1[$i]; ?>"><?php echo
$arr2[$i];?>
</a></li>
<?php } ?>
</ul>
</div>
<div id="tab" class="section">
</div>
functions.php:
<?php
add_action('wp_ajax_tabsfunction', 'tabsfunction');
add_action('wp_ajax_nopriv_tabsfunction', 'tabsfunction');
function tabsfunction() {
$dept_id=$_GET[id];
/** Here I print data according to $dept_id **/
die();
}
?>
script.js:
jQuery(document).ready(function() {
jQuery('.tabs a').click(function(e) {
e.preventDefault();
var tab_id = jQuery(this).attr('id');
console.log(tab_id);
jQuery.ajax({
type: "GET",
url: "wp-admin/admin-ajax.php",
dataType: 'html',
data: ({ action: 'tabsfunction', id: tab_id}),
success: function(data){
jQuery('#tab').html(data);
},
error: function(data)
{
alert("Error!");
return false;
} });}); });
it dose not work, it displays data only for one tab.
console.log(tab_id) ----> it display the id for the first tab clicked
and did not change when click another tab.
You need to echo the output from the tabsfunction and also add the die() at end of the function like below :
add_action('wp_ajax_tabsfunction', 'tabsfunction');
add_action('wp_ajax_nopriv_tabsfunction', 'tabsfunction');
function tabsfunction() {
$dept_id=$_GET[id];
/** Here display data according to $dept_id **/
echo 'output';
die();
}
Hope it helps.
can you please correct your tab list code.
<div class="tabs">
<ul>
<?php
$arr1 = array(2,3,5,10,22,25,27,28,29,30);
$arr2 = array("dep1","dep2","dep3","dep4","dep5","dep6","dep7","dep8","dep9","dep10");
for($i=0;$i<10;$i++)
{
?>
<li><?php echo $arr2[$i];?></li>
<?php
}
?>
</ul>
</div>
<?php for($i=0;$i<10;$i++)
{
?>
<div id="tab<?php echo $arr1[$i]; ?>" class="section">
</div>
<?php
}
?>
Also return proper response on ajax request.
<?php
add_action('wp_ajax_tabsfunction', 'tabsfunction');
add_action('wp_ajax_nopriv_tabsfunction', 'tabsfunction');
function tabsfunction() {
$dept_id = $_GET[id];
echo $dept_id; // this just dispay requsted id as tab content here you can add your logic for dynamic content based on id
die();
}
?>
And your script js look like this
jQuery(document).ready(function() {
jQuery('.tabs a').click(function(e) {
e.preventDefault();
var tab_id = jQuery(this).attr('id');
console.log(tab_id);
jQuery.ajax({
type: "GET",
url: "wp-admin/admin-ajax.php",
dataType: 'html',
data: ({ action: 'tabsfunction', id: tab_id}),
success: function(data){
jQuery('#tab'+tab_id).html(data);
},
error: function(data)
{
alert("Error!");
return false;
} });}); });

Delete function using AJAX in CodeIgniter

PROBLEM SOLVED.. I update my code accordingly.. Thanks all
Intro: My code display array of message traces (each message display in grey-panel). User can delete unwanted message by click on delete button, the message will be deleted in both DB and disappear from screen.
Seems my delete function is not working.. Appreciate for advice.. I don't know AJAX.. this is my first try. Thanks in advance.
The following are my code:
ajax code:
$(document).ready(function(){
$("body").on("click", "#responds .del_button", function(e) {
e.preventDefault();
var $btn = $(this),
$li = $btn.closest('li');
var traceId = $li.data('trace-id');
jQuery.ajax({
type: 'post',
url: 'traceDelete',
dataType: 'text',
data: { 'traceId': traceId },
success: function (res) {
if (res === '1') {
$btn.fadeOut();
}
},
error: function (xhr, ajaxOptions, thrownError){
alert(thrownError);
}
});
});
part of view code:
<ul id="responds">
<?php foreach ($line as $dataName => $contents){ ?>
<li data-trace-id="<?php echo $contents->trace_id; ?>">
<div class="grey-panel" style="text-align:right">
<div class="del_wrapper" id="<?php echo $contents->trace_id; ?>">
<a href="#" class="del_button" id="<?php echo $contents->trace_id; ?>" data-hover="tooltip" title="Delete this message <?php echo $contents->trace_id; ?>" >
<i class="fa fa-times"></i>
</a>
</div>
<div class="col-sm-12 col-xs-12">
<?php print $contents->trace_hdr.'<br />';
print $contents->trace_src.'<br />';
print $contents->trace_dest.'<br />';
// some other things ?>
</div>
</div>
</li>
<?php } ?>
</ul>
controller code:
public function traceDelete($traceID) {
if ($traceId = $this->input->post('traceId')) {
return $this->model_general->deleteTrace($traceId);
}
return false;
}
model code:
public function deleteTrace($id) {
$this->db->where('trace_id', $id);
$this->db->delete('trace_tbl');
return $this->db->affected_rows() > 1 ? true:false;
}
First, you are using the id attributes wrong. They are meant to be unique as in appear on one element and not multiple as you have done. (As well, id attributes cannot start with a digit.) There's really no need to put it on multiple containing elements as you can easily traverse to the parents or children with jQuery's .find(), .parent(), .closest(), and other traversing methods. However, this should not be the cause of your problem.
Now, what I do think is the cause of your problem is that you are passing the 2nd character of your id attribute into your AJAX request.
$(document).ready(function(){
$("body").on("click", "#responds .del_button", function(e) {
e.preventDefault();
// assign the ID e.g. "abc" to clickedID
var clickedID = this.id;
// problem: assign the second character of your ID i.e. "b" into DbNumberID
var DbNumberID = clickedID[1];
// assign the same value to myData (which is redundant)
var myData = DbNumberID;
$(this).hide();
jQuery.ajax({
type: "POST",
url: 'traceDelete',
dataType:"text",
// sending "myData=b"
data: { myData: myData },
success:function(traceDelete){
alert("Deleted");
$(DbNumberID).fadeOut();
},
error:function(xhr, ajaxOptions, thrownError){
alert(thrownError);
}
});
});
I am not too familiar with CodeIgniter anymore, but you need to get value from the $_REQUEST or $_POST array or use their built-in function.
$myData = $this->input->post('myData'); // because you are sending myData
EDIT
This is untested but here's how I would do it.
HTML
First, let's use HTML5 data attribute call it data-trace-id. This will be used instead of your numerous improper usages of id attributes.
<ul id="responds">
<?php foreach ($line as $dataName => $contents) : ?>
<li data-trace-id="<?php echo $contents->trace_id ?>">
<div class="grey-panel" style="text-align: right">
<div class="del_wrapper">
<a href="#" class="del_button" data-hover="tooltip" title="Delete this message <?php echo $contents->trace_id ?>">
<i class="fa fa-times"></i>
</a>
</div>
<div class="col-sm-12 col-xs-12">
<?php echo $contents->trace_hdr ?><br />
<?php echo $contents->trace_src ?><br />
<?php echo $contents->trace_dest ?><br />
<!-- etc -->
</div>
</div>
</li>
<?php endforeach ?>
</ul>
JavaScript
Next, let's simplify your JavaScript. I'll use the dreaded alert() for debugging purposes -- but it's usually better to use console.log().
$(function() {
$("#responds").on("click", ".del_button", function (e) {
e.preventDefault();
// keyword 'this' refers to the button that you clicked;
// $(this) make a jQuery object out of the button;
// always good idea to cache elements that you will re-using;
var $li = $(this).closest('li');
// get the associated trace ID from the list-item element;
var traceId = $li.data('trace-id');
alert('trace ID ' + traceId);
// assuming you only want to hide the message only if it has been been successfully deleted from the DB?
// if that is the case, then you have to wait for the AJAX response to tell you whether it was
jQuery.ajax({
type: 'post',
url: 'traceDelete',
dataType: 'text',
// notice how I am using 'traceId'? on the server-side, the data will accessible by using $_POST['traceId'] or $this->input->post('traceId')
data: { 'traceId': traceId },
// look at the response sent to you;
// if I am not mistaken (boolean) true and false get sent back as (strings) 1 or 0, respectively;
// so if the response is 1, then it was successfully deleted
success: function (res) {
alert('AJAX response ' + res);
if (res === '1') {
alert('hiding button');
// hide the message
$li.fadeOut();
}
},
error: function (xhr, ajaxOptions, thrownError){
alert(thrownError);
}
});
});
});
PHP
Lastly, we take the value from the $_POST array. Check whether there is a value: if so, delete the item; otherwise ignore it.
public function traceDelete()
{
if ($traceId = $this->input->post('traceId')) {
echo $this->model_general->deleteTrace($traceId) ? '1' : '0';
}
echo '0';
}
remove var DbNumberID = clickedID[1]; var myData = DbNumberID;, as its not needed. Directly assign data: { myData: clickedID },. Also get value of myData in controller via POST.
public function traceDelete() {
$traceID = $this->input->post('myData');
if($traceID)
return $this->model_general->deleteTrace($traceID);
return false;
}

Jquery UI sortable, write order into a MySql database

I'm currently using JQuery UI Dragabble, Droppable and sortable. I have two div sections at top and bottom of my php file were i'm dragging and dropping contents from bottom to top div sections.
In top div section i'm performing Sortable JQUery opertions my next requirment is when i perform sorting operation in top section its order should be automatically updated in my MYSQL DB i gotta stuck like how to pass the sorted order to my MySQL db via ajax and php file. Can somebody suggest some help in Achieving it!
Thanks!
Html/PHP code
<div class="drop_list">
<ol id="sortable" style="list-style:decimal;"></ol>
</div>
<div class="sort_list">
<ul id="draggable">
<?php
for($i=1;$i<=5;$i++)
{
?>
<li data-id='article_<?php echo $i;?>' class="draggable_li qitem" >
<div class="main_div">
<div class="secondary_div">
<div class="form_div">
<form>
<input style="width:15px;" type="checkbox" class="hello"/>
</form>
</div>
<label class="item_div">
<span class="item">Item = <?php echo $i; ?></span>
</label>
</div>
<button class="hello btn btn-success add_top">
Add to Top Stories
</button>
<span class="AH_section" style="display:none;float:right;">
<input type="checkbox"/>Home Section
<input type="checkbox"/>App Home Section
</span>
</div>
</li>
<?php
}
?>
</ul>
</div>
</div>
</div>
</div>
JQuery code
$(document).ready(function() {
$("#sortable").sortable({
revert: true,
refreshPositions: true ,
helper : 'clone',
cursor: "move",
delay: 1,
tolerance: 'pointer',
revert: 50
/*stop:function(event,ui){
var data = $(this).sortable('serialize');
}*/
}).serialize();
$("ol li").disableSelection();
$(".sort_list li").draggable({
//containment : "#container",
tolerance:"pointer",
helper : 'clone',
refreshPositions: true ,
revert : 'invalid',
opacity:.4,
});
$(".drop_list ol").droppable({
revert:true,
//hoverClass : 'ui-state-highlight',
greedy: true,
refreshPositions: true,
drop : function(ev, ui)
{
$(ui.draggable).clone().appendTo(this);
if($(this)[0].id === "sortable")
{
console.log($(this).closest("button").find('.hello'));
$(this).find('.hello').hide();
$(this).find('.AH_section').show();
//$(ui.draggable).draggable( 'disable' ); //this will not append dragged list at top of the container
ui.draggable.draggable( 'disable' ).closest('li').prependTo(ui.draggable.closest('ul')); //this will append dragged list at top of the container
return true;
}
}
});
});
change data-id='article_<?php echo $i;?>' to id='<?php echo $i;?>'
add this to your sortable(),
update: function (event, ui) {
var serial=$(this).sortable('serialize');
save_sortable(serial);
}
so here on update, you are calling save_sortable() function, from ajax , update your db in the order returned from sortable()
function save_sortable(serial)
{
$.ajax({
url: "path to your file to update in db.",
type: 'POST',
data: serial,
success: function (data) {
//alert(data);
}
});
}
You can add some id attribute to li, in my case will be get_id.
and then call below function onDropSendSort(); when you want, ie after drop.
<li data-id='article_<?php echo $i;?>' get_id="<?php echo $object_id; ?>" class="draggable_li qitem" >
function onDropSendSort() {
var data = [];
$('#draggable li').each(function() {
var id = $(this).attr('get_id');
data.push(id);
});
// data = [id_1, id_3, id_n];
$.ajax({
url: 'some_url',
type: 'POST',
data: {sort: data},
complete: function(res) {
console.info(res);
}
});
}

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

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