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");
}
});
Related
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.
I have a four menu tabs. in One tab is a submit form (default), the second tab contain list of entries, each entry has a button called change status. When i click "change status" I called windows.reload using ajax to update the page with out refresh but the tab will go back to the default one which is the first one. Now my problem is how can i update the menutab class to the current selected menu to become an active one. below is my ajax codes:
<input type="button" value="change status"> // a button to click to change status
<a class="active">tab1</a> // need to change classname when the button clicked
<a class="nonactive">tab2</a> // need to change classname when the button clicked
<script>
$(document).ready(function() {
$(".closeBTN").click(function() {
var data = $(this).attr('id');
//alert (data);
$.ajax( {
type: "POST",
url: "../deals_status_update.php",
data: { 'id': data }
}).done(function(msg) {
$("#notification").html(msg);
window.setTimeout(function(){
location.reload()
$('#itrade .active').removeClass().addClass('nonactive');
$('#iopendeals .nonactive').removeClass().addClass('active');
},100)
});
});
});
</script>
location.reload() reloads the website, so you cant use jQuery methods after that.
maybe window.location.hash can help you.
Add a hash and parse this hash after the website reload to trigger your classes?
try using location.hash, cuz as explained location.reload() will actually refresh the page, and i still don't get why you need to refresh the page to update data !
<input type="button" value="change status"> // a button to click to change status
<a class="active">tab1</a> // need to change classname when the button clicked
<a class="nonactive">tab2</a> // need to change classname when the button clicked
<script>
$(document).ready(function() {
$(".closeBTN").click(function() {
var data = $(this).attr('id');
$.ajax( {
type: "POST",
url: "../deals_status_update.php",
data: { 'id': data }
}).done(function(msg) {
$("#notification").html(msg);
window.setTimeout(function(){
location.hash = 'iopendeals';
location.reload();
},100)
});
});
if(location.hash != '') {
$('.active').removeClass().addClass('nonactive');
$(location.hash + ' .nonactive').removeClass().addClass('active');
}
});
</script>
You're reloading the page, so any JavaScript that happened later will lose its state. DOM modifications are only good for the current page session. Once it is navigated away or reloaded, they lose progress.
Have you considered not reloading? Why are you reloading for anyway?
or,
Can you maybe do those changes client-side, and instead of reload, redirect to the same page with different GET parameters?
<li class="menuitem<?=$_GET['page'] == 'homepage' ? ' active' : ''?>">
Homepage
</li>
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.
So, basicly what I'm trying to achieve:
In index.php
I would enter products code to search for products information and it's images (that query is run in open_first.php, called via ajax post request).
It works just perfect..
When open_first.php is loaded, it displays me some images I can select from (when I click on the image, it's relevant checkbox get's checked containing the image id).
This works too, just fine.
BUT,
If I enter a code in the field: "productCodeCopy" and click on "confirmCodeCopy" -button it reloads the whole page, I mean index.php and everything I've entered is lost and I'm back in the starting point again. I don't understand why it does so. I suppose it has something to do with the fact, that the second ajax request is made from a dynamically created page (open_first.php)?? Do I miss something I should POST too?? Or what's the problem, this is really frustrating me since I've tried to fix this for hours now.
Note:
Jquery is loaded in index.php, open_first.php and open_second.php, I've just ignored that to keep the code simpler.
FILE: index.php (the "starting point")
<!-- head -->
<script type="text/javascript">
$(document).ready(function() {
$("#confirmCode").on('click', function(){
var productCode = $("#productCode").val();
$.ajax({
url: 'open_first.php',
type: "POST",
data: ({code: productCode}),
success: function(data){
$("#found").html(data);
},
error: _alertError
});
function _alertError() {
alert('error on request');
}
});
});
</script>
<!-- body -->
<input type="text" class="textfields" id="productCode" name="productCode" value="YT-6212">
<input type="button" class="admin-buttons green" name="confirmCode" id="confirmCode" value="Search">
<div id="found"></div>
FILE open_first.php
<script type="text/javascript">
$(function() {
$("#foundImage").on('click', function(){
$('#foundImage').toggleClass("foundImage-selected foundImage");
var myID = $('#foundImage').data('image-id');
var checkBox = $('input[id=selectedImages-'+myID+']');
checkBox.prop("checked", !checkBox.prop("checked"));
});
$("#confirmCodeCopy").on('click', function(){
var checkedItems = $('input:checkbox[name="selectedImages[]"]:checked');
// this code here reloads the whole page / view (as in "index.php")
$.ajax({
url: 'open_second.php',
type: "POST",
data: ({checked: checkedItems, copyTo: productCodeCopy, code: "<?php echo $_POST['code']; ?>"}),
success: function(data){
$("#copyToProducts").append(data);
},
error: _alertError
});
/*
// the code below runs just fine when I hit the button "confirmCodeCopy"
alert('Fuu');
return false;
*/
});
function _alertError() {
alert('error');
}
});
</script>
<!--BODY-->
<!-- these are dynamically generated from php, just to simplify we have checkbox that contains value "1" to be posted in ajax -->
<div class="foundImage" id="foundImage" data-image-id="1"><img src="image.jpg"><input type="checkbox" id="selectedImages-1" name="selectedImages[]" value="1" style="display: none;"></div>
<label for="productCodeCopy">Products code</label>
<input type="text" class="textfields" id="productCodeCopy" name="productCodeCopy">
<br /><br />
<label for="confirmCodeCopy"> </label>
<input type="button" class="admin-buttons green" name="confirmCodeCopy" id="confirmCodeCopy" value="Search">
<div id="copyToProducts"></div>
open_second.php only prints out POST variables for now, so nothing special yet.
SOLVED
So ok, I solved it. With dumdum's help.
I removed the line:
$('input:checkbox[name="selectedImages[]"]:checked');
And added this:
var checkedItems = new Array();
var productToCopy = $('#productCodeCopy').val();
$("input:checkbox[name=selectedImages[]]:checked").each(function() {
checkedItems.push($(this).val());
});
Since there was no form element present, it didn't get the field values unless "manually retrieved" via .val() -function.. Stupid me..
I don't know how much this affected but I changed also:
data: ({checked: checkedItems, copyTo: productCodeCopy"})
To
data: {"checked": checkedItems, "copyTo": productToCopy}
So now it's working just fine :) Cool!
WHen you apply event hander to a button or a link to do ajax...always prevent the browser default processing of the click on that element
There are 2 ways. Using either preventDefault() or returning false from handler
$("#confirmCodeCopy").on('click', function(event){
/* method one*/
event.preventDefault();
/* handler code here*/
/* method 2*/
return false;
})
The same is true for adding a submit handler to a form to do ajax with form data rather than having the form redirect to it's action url
your code $('input:checkbox[name="selectedImages[]"]:checked'); is returning undefined making the json data in the ajax call invalid. Check you selector there.
I have a table populated with data from the database, where each row has a cell with an anchor element inside. This anchor would lead to the same page but with a query string telling php which row contains the data it should delete.
I need a jQuery dialog box to be opened when the user clicks an anchor asking him to confirm his intentions BEFORE loading the url. The 'cancel' button should close the dialog and do nothing. The 'OK' button should then let the url open.
Any help is highly appreciated.
// edit with 'what I have tried'. It's my first time messing with jQuery and time for studying is running out... =(
jQuery(document).ready(function(){
var $dialog = jQuery('<div class='msg_dialog'></div>')
.html('Are you sure you want to do this?')
.dialog({
autoOpen: false,
title: 'Confirm action',
buttons: [{
text: "Cancel",
click: function(){
jQuery(this).dialog("close");
}
}] // didn't even try the OK button since I couldn't even get the dialog opened
});
jQuery('#confirm_del').click(function(){
$dialog.dialog('open');
return false;
});
});
$("a").on("click", function(e) {
var link = this;
e.preventDefault();
$("<div>Are you sure you want to continue?</div>").dialog({
buttons: {
"Ok": function() {
window.location = link.href;
},
"Cancel": function() {
$(this).dialog("close");
}
}
});
});
Example: http://jsfiddle.net/uRGJD/
(Redirecting to Google won't work on JSFiddle but should work on a normal page)
how about using:
<a href="<?php echo 'your_url'.'?query_string='.$query_string ?>" onclick="return confirm('Are your sure?')">
Go
</a>
You can create a dialog that creates the buttons for you, but I like the approach where you create the buttons yourself so that you can use real links instead of using javascript to navigate.
Working demo: http://jsfiddle.net/gilly3/sdzbB/
<div id="dialog-confirm">
<div class="message">Are you sure?</div>
<div class="buttons">
<a class="cancel" href="#">Cancel</a>
<a class="ok" href="#">Ok</a>
</div>
</div>
$("#dialog-confirm").dialog({ autoOpen: false }).find("a.cancel").click(function(e){
e.preventDefault();
$("#dialog-confirm").dialog("close");
});
$("a[href]:not(#dialog-confirm a)").click(function(e) {
e.preventDefault();
$("#dialog-confirm")
.dialog("option", "title", $(this).text())
.dialog("open")
.find("a.ok").attr({
href: this.href,
target: this.target
});
});
The benefit to using a real link instead of location.href = link, is that you get all kinds of built in goodies, like mouse shortcuts to open the link in a new tab, the ability to drag the link to the bookmarks bar or desktop, the ability to copy the link to the clipboard, keyboard access via tab, etc.
You should prevent default behavior of the link which can be done like this code.
$('.tableId tr td a').click(function(event){
//code to display confirmation dialog
event.preventDefault();
}
You can use this JQuery plugin for confirmation dialog.http://jqueryui.com/demos/dialog/#modal-confirmation