ajax call only works when tablesorter is clicked - php

I really don't know how to explain this. I have a table and I am using tablesorter to make columns sortable.
at the end of each row i have a button that has a jquery listener to fire off an ajax call. For debugging purposes, all that called script does is print_r($_POST). This ajax call only works after I click on a column to sort table. IF i don't, i get no response from ajax call. In firebug, if i dont click on column to sort, I get a red http:Post response, if i click on a table column, i get the response i would expect.
//tablesorter call
$('#pendingItems').tablesorter();
//dialog setup
$('#removeItem').dialog(
{
autoOpen:false,
width: 500,
modal: true,
resizable: false,
closeOnEscape: true,
buttons:
{
"Ok": function()
{
//window.location.replace('items.php');
}
}
});
//listener for button click
$('.removeItem').click (function()
{
var attrId = $(this).attr('id');
var gid = attrId.split('_');
var itemId = gid[1];
$.ajax({
type: "POST",
url: "removeItems.php",
data: "itemId="+itemId,
success: function(result)
{
alert('hi');
$('#removeItem').html(result);
$('#removeItem').dialog('open');
}
});
});
and in the table.
<input type='image' src='images/trashcan2.png' id='remove_" . $r['id'] . "' name='remove_" . $r['id'] . "' class='removeItem'>
where $r['id'] is a number.
in firebug:
looking at net tab. on failed attempt, the post goes to items.php (the original page). if i click on table column, and then the button, the post goes to the removeItems.php (the correct page)......

Maybe (probably...) tablesorter is modifying the DOM, causing your bindings to disappear.
To see if that is the problem - and to solve it - just change:
$('.removeItem').click (function()
to:
$('.removeItem').on('click', function()
Note that on() requires jQuery 1.7+

Also in POSt type, data should be like: data: {temId: itemId},

So i found that input type image submits the form. Adding return false; to the click event fixed the problem.

Related

Dynamic element ID in jQuery script on click event

I'me trying to implement an on/off button on a php loop but I can't make it work because of the id of jQuery event. How can I get the correct id on click and pass it to the rest of the script?
The problem is in the $('#myonoffswitch')...
<script type="text/javascript">
$(document).ready(function(){
$('#myonoffswitch').click(function(){
var myonoffswitch=$('#myonoffswitch').val();
var wnfID=$('#wnfID').val();
if ($("#myonoffswitch:checked").length == 0) {
var a="2";
var b=wnfID;
} else {
var a="3";
var b=wnfID;
}
$.ajax({
type: "POST",
url: "ajax_wnf_status.php",
data: "statusWnf="+a+"&wnfID="+b,
success: function(html) {
$("#display").html(html).show();
}
});
});
});
</script>
I'm generating different id's for the loop rows (ex: id="#myonoffswitch1" ; id="#myonoffswitch2"; etc).
I'm not certain I fully understand the question, but .val() will not get the ID of an element. You should use .attr('id') instead.
Also, it looks like you're trying to format data for a GET request, not a POST.
If I understand the question correctly, I think you're looking for
event.target.id
where 'event' is passed in to your handler:
('#myonoffswitch').click(function(event){
id = event.target.id
. . .
Though at that point, you might not need the id, since you can just use event.target directly.

Need some guidance on creating a jEditable custom input

I'm using the jEditable plugin and the following code to toggle between On and Off for a series of settings on a page.
$(document).ready(function() {
$('.editable_select').editable(''http://someexamplepage.com/save.php', {
indicator: '<img src="/images/spinner.gif">',
data : " {'✓':'✓','✗':'✗'} ",
tooltip : 'Click to Edit',
type : 'select',
onblur : 'submit',
style : 'inherit'
});
});
And then this in the html:
<b class="editable_select" id="setting1" style="display:inline">✓</b>
When the checkmark indicating On is clicked, it produces a dropdown menu with checkmark for On and the X for Off in it, which the user can then select. What I would prefer is that clicking the check/X not open a dropdown, but instead send the current On or Off setting to the save.php file. I could then just write the save.php file to return the opposite value, so that clicking just toggles between the two without opening any kind of edit window. I tried the following code:
$(document).ready(function() {
$('.editable_select').editable('http://someexamplepage.com/save.php', {
indicator: '<img src="/images/spinner.gif">',
tooltip : 'Click to Edit',
onclick : 'submit',
style : 'inherit'
});
});
But clicking the text still opens a little editing window, which I don't want. I'm still new to JavaScript and jQuery, so any help is greatly appreciated!
I wouldn't use a plugin for this, but rather a very simple bit of jQuery to run on the ready event.
I would include the current state as a data attribute on the DOM, so change your tags to:
<b class="editable_select" id="[ID FOR ITEM]" data-state="checked">ઙ</b>
Then do something like:
$(function(){
var update_dom = function(data){
var item_id = data.id;
var state;
data.state === 'checked' ? state = '✓' : state = '✗';
$('#'+item_id).data('state', data.state).html(state);
};
var selected = function(evt){
var item_id = $(this).attr('id');
var state = $(this).data('state');
$.ajax({
url: PATH_TO_SCRIPT,
data: {id: item_id, state: state},
type: "POST",
success: update_dom
});
}
$('.editable_select').click(selected);
});
This binds the click event to everything that has a class of editable_select. When you click on it, it'll call the selected function, which wil get the data from the DOM, and call your script. When your script is complete, it should send back a response (JSON would be good here), and, the success handler will update the DOM and display the state back to the user.

jQuery UI dialogs based on dynamically generated information

Right now I have a table with a few items, each of which has an Edit icon. When the edit icon is clicked, the corresponding database ID of the item (its name) is sent via a $.get() AJAX method to process.php, which generates a JQuery UI dialog consisting of a few of that database item's attributes.
The first item that I click on brings up the proper dialog box with all of the attributes filled in the text boxes. However, when I click a different item, the same dialog box appears with the first item's information. Any other ones I click on still have that first item's information in the dialog box.
What I'm guessing is happening is that the data sent back to index.php, the new div and the jquery dialog call, has already been echo'd through and appended to the page--thus I get the same first box over and over. I just can't figure out how to fix it.
portion of index.php:
$('#edit_link').live('click', function(e){
var ID = $(this).attr('name');
console.log(ID);
$.get('process.php', {taskID: ID}, function(data){
$('body').append(data);
});
e.preventDefault();
})
...the console successfully logs each item's taskID, so that's not the problem.
process.php:
if(isset($_GET['taskID'])){
$taskID = $_GET['taskID'];
$task = TaskDB::getTask($taskID);
$duration = $task->getDuration();
$description = $task->getDescription();
$deadline = $task->getDeadline();
echo '<script>$("#dialog").dialog({
height: 150,
width: 300,
modal: true,
buttons: {
"Save Task": function() {
$( this ).dialog( "close" );
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
});</script><div id="dialog" title="Edit Task" style="display:none;">
<p>Deadline: <input type="text" style="margin-right:10px;" value="'.$deadline.'"/> Duration (hours): <input type="text" style="width:20px;" value="'.$duration.'"/></p>
<p>Description: <input type="text" style="width: 200px;" value="'.$description.'"/></p>
</div>';
}
The echo portion is where I think the problem is, as the previous echoed data is not cleared out if another Edit was clicked.
Any help would be greatly appreciated. Also, I'm not entirely sure if what I'm doing is the best means for carrying out this goal (having PHP generate so much html/javascript), so any suggestions regarding that would also be very much appreciated. Thanks!
I think you should first remove the previous dialog from body. Try this:
$('#edit_link').live('click', function(e){
var ID = $(this).attr('name');
console.log(ID);
$("#dialog").remove(); // Delete the previous dialog
$.get('process.php', {taskID: ID}, function(data){
$('body').append(data);
});
e.preventDefault();
})
That sounds like you have to use .destroy() function when close the dialog. This function will reset your dialog
$('.dialog').dialog({
// your options
close : function() {
$('.dialog').dialog("destroy");
}
});

jQuery/Ajax - Click to reveal

I want to basically create a link which says:
Click here to show contact information
Upon clicking it, it will ping a script via an ajax request, the ajax request will look up the user table where the ID is what is contained in the alt tag, it will return a certain field from the database and then the div will change from this link, to a contact number.
I'm sure some of you have seen this done before, for example:
Click to see persons phone number
They click it, and it changes to their phone number.
How would I go about doing this? I want to do it using ajax instead of having the phone number in the source code, because that really defeats the purpose of them having to click to reveal if bots can get it from the source code.
Thanks :)
Somethign along the lines of
$("#reveal").click(function(){
$.get('getphoneNumber.php',{id:$(this).attr('alt')}, function(data) {
$('#reveal').html(data);
});
});
with a php script called getphoneNumber.php that accepts a get parameter of id
Try this one
$('#reveal').click(function () {
var th = $(this);
$.get('/get-the-phone-number', { id: th.attr('alt') }, function (response) {
th.text(response);
});
});
Also, I'd recommend you put the id number inside a data-contact-id attribute and access it via th.data('contact-id') instead of using the alt attribute. Ignore me if you have other reasons to do this.
$("#reveal").live('click',function(event) {
var link = $(this).attr('alt');
var dataString = 'alt=' + link ;
$.ajax({
type: "POST",
url: "url",
cache:false,
data: dataString,
success: function(data){
this.href = this.href.replace(data);
}
});
}
Click here to show contact information
<div id="myHiddenDiv"></div>
$("#reveal").click(function(){
$.get("test.php", { id: $(this).attr("alt") },
function(data){
$("#myHiddenDiv").html(data);
$("#myHiddenDiv").show();
});
});
This example works assuming you've only got one of these "plugins" on your site, if you'll have multiple, use this:
Click here to show contact information
<div class="myHiddenDiv"></div>
$(".reveal").click(function(){
var divSelector = $(this).next("div");
$.get("test.php", { id: $(this).attr("alt") },
function(data){
divSelector.html(data);
divSelector.show();
});
});

How can I revert a 'draggable' upon failed AJAX request?

I have a draggable div, that needs to be dropped on a droppable. If it is dropped correctly, the droppable calls an AJAX request. If the draggable does not have a valid id or the AJAX request fails, the draggable should be reverted to it's original position. Is that something that can be done with jQuery?!
Any help is greatly appreciated!!
$("div.draggable").livequery(function(){
$(this).draggable({
revert: 'invalid',
distance: 20
})
});
$("#trash").droppable({
tolerance: 'touch',
drop: function(event, ui)
{
var item = ui.draggable;
var id = item.attr('id');
if (id)
{
$.ajax(
{
type: "POST",
url: "delete.php",
data: "id=" + id,
success: function(html)
{
if (html)
{
item.remove();
}
else
{
// FAILED AFTER AJAX
// is it possible to revert the draggable from here??
}
}
});
}
else
{
// FAILED BEFORE AJAX
// is it possible to revert the draggable from here??
}
}
});
I had the same problem,
You can simply do:
item.css({"top":0, "left":0});
tip: draggable has relative position.
Im not too familiar with jquery - but id suggest using the prototype framework (along with scriptaculous) - within prototype you can definately achieve this effect.
If you can guess what it's original position was in the fail block, just use a selector to find it and the manipulation functions to remove it from its current position and move it to the old one.
If you need to, perhaps you can store the original position (parent and child-index) when it is dragged, then move it back there when it fails

Categories