My JavaScript is as follows:
$.get("/<page>.php", "userid='.$userid.'&"+status, function(data){
$("#status").show("fast").html(data).delay(4000).hide("fast");
});
I have many links on a page that will load this jQuery AJAX and display the status in a div correctly. It all works fine, except if a user click many of the links really fast. The data changes correctly, but the animations are delayed. I've tried including the jQuery stop() and stop(true) and stop(true, true) before the .show but it doesn't seem to help much. Animations can continue long after the last click; for example, if a user clicks 20 times, and then pauses, the hide animations seem to continue long afterwards, despite the stop(). What I want is if a user clicks on another link that causes the AJAX to cause a status display, the basically "resets" the status animations.
Any ideas?
Here's the full relevant JavaScript:
<script type="text/javascript">
...
$(document).ready(function () {
$("#entry a.styled").live("click", function(event){
var status = $(this).attr("rel")+"&game="+$(this).attr("name");
var teamid = $(this).attr("rel");
var gameid = $(this).attr("name");
$("[name="+gameid+"]").show(1);
$(this).hide(1);
$("[rel=t"+teamid.replace("pick=", "")+"]").removeClass();
$("[name=t"+gameid+"]").removeClass();
$("#t"+teamid.replace("pick=", "")).addClass("hilite");
$.get("/<filename>.php", "userid=1&"+status, function(data){
$("#status").stop(true, true).show("fast").html(data).delay(4000).hide("fast");
});
});
</script>
and some relevant HTML, this is within a larger table:
<tr class="row-a">
<td>8-man</td>
<td>1:00 pm</td>
<td class="hilite" id="t298" rel="t233" name="t3235">La Veta</td>
<td>Pick</td>
<td><img src="/images/delete.png" height="12" width="12" /></td>
<td>Pick</td>
<td id="t233" rel="t298" name="t3235">South Park**</td>
<td> </td>
</tr>
The user would click on the "Pick" link or the delete Image which calls the jQuery AJAX get.
Any other improvements to my (limited shown) code are appreciated as well.
jquery version:1.4.2
jqueryui version:1.7.2
Maybe stop() doesn't clear the delay() -- have you tried the .clearQueue() method?
alternatively, you could try with setTimeout rather than delay()...
// animInProgress and animDelay are global variabes
var animInProgress = false;
var animDelay;
//later, in your $.get success function...
$("#status").show("fast").html(data);
if(animInProgress) {
clearTimeout(animDelay);
}
animInProgress = true;
animDelay = setTimeout(function() {
$("#status").hide("fast");
animInProgress = false;
}, 4000);
Related
I have jQuery code that works beautifully for clicking a row in a table that exists at page-load and getting redirected to a new page:
$(document).ready(function() {
$("#myTable").on('click','tr',function() {
var href = $(this).find("a").attr("href");
if(href)
{ window.location = href; }
});
});
I have a second table that gets generated by a jQuery POST and is added dynamically and I know it works because I can alert() myself when I click on a row of a dynamically-created table:
$(document).on('click', '#myDynamicTable tr', function(e) {
var href = $(this).find("a").attr("href");
alert(href);
});
Obviously, href is undefined. So what code can I use to replace the alert() line with an actual redirect to the link that's in that particular TR?
Update with HTML code:
A sample HTML code that is returned via POST to the main page where the user clicks TRs:
<table id='myDynamicTable' border="1" cellspacing="0" cellpadding="10">
<tr><td>1</td></tr>
<tr><td>2</td></tr>
</table>
Again, the only difference between this dysfunctional table row clicking and other tables on the same page is the fact that myDynamicTable is generated dynamically via jQuery based on a search string put into an input type="Text" by the user.
If you just want to change the browser URL, just set window.location:
Presumably your have anchors inside TDs inside your TRs (you should show sample HTML too).
$(document).on('click', '#myDynamicTable tr', function(e) {
var href = $(this).find("a").attr("href");
window.location = href;
});
Technically you are meant to set window.location.href, but all browsers allow the shortcut. Javascript: Setting location.href versus location
User This
<table id='myDynamicTable'>
<tr>
<td>
redirect to
</td>
</tr>
your jquery code is true
$(document).on('click', '#myDynamicTable tr', function(e) {
var href = $(this).find("a").attr("href");
window.location=href;
});
I've got a table which is listing orders and I want to add the possiblity to filter results. Therefore I created a select field and an onchange effect in Jquery which is loading the same table with those filtered results into my Div. Therefore I used Ajax to update this "new Content" to my div. The problem is, that this table has several JQuery effects (for example a slide down when you click on a row) which doesn't work when the Content got created by the AjaxRequest. I have read some things already here in Stackoverflow and in other boards, but there was so many specific cases that I couldn't use any. I've heared something about a "init-function" which I need to call somewhere, so the JQuery things will also work on my Ajax generated content.
This is my Ajax Request:
$('.category').on('change', function (e) {
var optionSelected = $("option:selected", this);
var valueSelected = this.value;
$.ajax({
type: "POST",
url: "includes/listorders.php",
data: "filter=" + valueSelected,
success: function( data ) {
$( "#latestOrders" ).html(data);
}
});
});
This is what my listorders.php basically returns (probably not necessary to know to fix my issue):
$filter = $_POST['filter'];
//Prepare Queries
$lastOrders = "SELECT * FROM Orders ORDER BY dateAdded DESC LIMIT 0,48";
$ps_orders = $db->query($lastOrders);
$data = $ps_orders->fetchAll();
foreach($data as $row)
{
$orderid =$row['id'];
$username = $row['name'];
$done = $row['refsDone'];
$quantity = $row['quantity'];
$running =$row['refsRunning'];
$untouched = $quantity - ($done+$running);
?>
<tr class="header mySlideToggler" data-id="<? echo $orderid ?>">
<td class="align-center">TEST<? echo $username ?></td>
<td>0 %</td>
<td>22 Aug 2014</td>
<td><? echo $done . " / " . $quantity ?></td>
<td><? echo $running ?></td>
<td><? echo $untouched ?></td>
<td>
</td>
</tr><tr style="padding: 0"><td colspan="7" style="padding: 0">
<div class="accounts" style="display: none">
</div>
</td></tr>
<?
}
?>
My Slide effect including another Ajax request for the content which should be displayed into the slided div:
// Slide effect for listing account information to an order
$('.mySlideToggler').click(function( event ){
event.preventDefault();
event.stopPropagation();
var id = $(this).data('id');
var div = $(this).closest('tr').next().find('.accounts');
$.ajax({
type: "POST",
url: "includes/listaccounts.php",
data: "orderid=" + id,
success: function( data ) {
div.html(data);
}
});
$(this).closest('tr').next().find('.accounts').slideToggle();
});
You need to make sure to use the new live version of event listeners, to work with content loaded asynchronously
$('body').on('click', '.my-class', function(){
//handle click event for .my-class here
});
The above code is not specific to your situation, since you have not posted the js code that is not working on async content. It's just a sample of how you manage live event listeners.
Specific answer after reviewing your code update:
$('body').on('click', '.mySlideToggler', function(event){
//do toggle stuff here
});
Why?
The jQuery .click does not support events happening on content loaded asynchronously. The same problem applies to using the following code:
$('.mySlideToggler').on('click', function(event){
//THIS WONT WORK WITH ASYNC CONTENT
});
This is why jQuery has allowed us to register the event on a parent element that was not loaded asynchronously and the provide a second argument to .on that tells us which child of that element to listen for as a target or said event. This works with all events, click|change|focus|blur|etc...
Why $('body')
I generally attach these live handlers to the body of the html document because the body is rarely reloaded via async content, as reloading the entire content would probably warrant a new page load, however it's not necessary to use body. You can attach to any parent element that is static on the page, including document or window
Nice to know
jQuery formerly used the method .live() which has been deprecated for a while now, I think since 1.7
I suggest you read more about the change to .live here: http://api.jquery.com/live/
I hope this has sufficiently answered your question. Let me know if you're still having trouble.
Performance Concern
Attaching the parent object of the .on event as close to the child element as possible will increase performance if you are using a large number of these events, as jQuery doesn't have to traverse as far down the DOM Tree to find the child element.
More info here: http://api.jquery.com/on/#event-performance
I have very limited knowledge with scripts so I hope you guys can help me with a simple solution to a small problem that I have...
I'm using the following jquery function to refresh a div with new content when a link is clicked
<script>
$(function() {
$("#myButton").click(function() {
$("#loaddiv").fadeOut('slow').load("reload.php").fadeIn("slow");
});
});
</script>
My problem is, I need to send 2 variables to the reload.php page to use in a mysql query (I have no idea how to accomplish that), also I need to make multiple links work with this function, at the moment I have multiples links with the same id and only the first link works so I guess I must associate different ids to the function in order for this to work, how can I do that?
here's the page where i'm using this: http://www.emulegion.info/teste/games/game.php
You may want to use document ready instead of function on your first line as this will make sure the code is not executed until the full page (and all elements) have loaded.
You can then use the callback functions of the fade and load to perform actions in a timely manner.
additional variables you can add after the .php, these can then be read in your reload.php file as $var1 = $_GET['var1'];
Do make sure to sanitize these though for security.
<script type="text/javascript">
// execute when document is ready
$(document).ready(function() {
// add click handler to your button
$("#myButton").click(function() {
// fade div out
$("#loaddiv").fadeOut('slow',function(){
// load new content
$("#loaddiv").load("reload.php?var1=foo&var2=bar",function(){
// content has finished loading, fade div in.
$("#loaddiv").fadeIn('slow');
}); // end load content
}); // end fade div out
}); // end add click to button
}); // end document ready
</script>
For different variables you could add a HTML5 style variable to your button.
<input type="button" id="myButton" data-var1="foo" data-var2="bar" />
You can retrieve this when the button is clicked:
// add click handler to your button
$("#myButton").click(function() {
// get vars to use
var var1 = $(this).data('var1');
var var2 = $(this).data('var2');
...
load("reload.php?var1="+var1+"&var2="+var2
if you have multiple buttons/links I would use class instead of id "myButton". that way you can apply the function to all buttons with the above script. Just replace "#myButton" for ".myButton"
First, you should use .on('click', function() or .live('click', function() to resolve your one click issue.
You'll want to do something like:
<script>
$(function() {
$("#myButton").on('click', function() {
var a = 'somthing';
var b = 'something_else';
$.post('url.php', {param1: a, param2: b}, function(data) {
//data = url.php response
if(data != '') {
$("#loaddiv").fadeOut('slow').html(data).fadeIn("slow");
}
});
});
});
</script>
Then you can just put var_dump($_POST); in url.php to find out what data is being sent.
Try creating a function that would accept parameters that you want.
Like:
$(document).ready(function(){
$('.link').click(function(){
reload(p1,p2);
});
});
function reload(param1, param2){
$("#loaddiv").fadeOut('slow').load("reload.php?param1="+param1+"¶m2="+param2).fadeIn("slow");
}
But by doing the above code your reload.php should be using $GET. Also you need to use class names for your links instead of id.
<script type="text/javascript">
// execute when document is ready
**$(document).ready(function() {**
**$("#myButton").click(function() {**
**$("#loaddiv").fadeOut('slow',function(){**
**$("#loaddiv").load("reload.php?var1=foo&var2=bar",function(){**
// content has finished loading, fade div in.
$("#loaddiv").fadeIn('slow');
});
});
});
});
</script>
$("#myButton").click(function() {
// get vars to use
var var1 = $(this).data('var1');
var var2 = $(this).data('var2');
I have jquery code to delete data row by row in my table view. When the user click delete icon, conformation box is popup and have "Yes" and "No" button. If "Yes" the row is delete, if "No" close the conformation box and do nothing. The problem is, let say I have 2 row data like this:-
<tr bgcolor=#ACACAC id='ak1'>
<td align='center'>1.</td>
<td>Data 1</td>
<td>...</td>
<td>...</td>
<td>...</td>
<td align='center'>
<img src='image/DocEdit.png' class='editData' id='ID_16'> <img src='image/DocDelete.png' **class='deleteData'** id='**ID_16**'>
</td>
</tr>
<tr bgcolor=#6D6D6D id='ak1'>
<td align='center'>2.</td>
<td>Data 2</td>
<td></td>
<td></td>
<td></td>
<td align='center'>
<img src='image/DocEdit.png' class='editData' id='ID_17'> <img src='image/DocDelete.png' **class='deleteData'** id='**ID_17**'>
</td>
</tr>
So, when I click delete on Data 1, the ID_16 is past to jquery code. Than I click "No" on conformation box. After that, I click delete on Data 2. Now I click "Yes" on conformation box. Data ID_17 deleted from DB, buat after delete ID_17, my jquery will loop and delete ID_16 and all the data that I try to delete before. It's like queue the delete action for the data that I choose "No" on conformation box. Below is my jquery code.
//.deleteData is class for delete button
$('.deleteData').click(function(){
var idData=$(this).attr('id'); //get data id to delete
//Fade in the Popup for conformation delete
$('#cfm-box').fadeIn(300);
//Set the center alignment padding + border see css style
var popMargTop = ($('#cfm-box').height() + 24) / 2;
var popMargLeft = ($('#cfm-box').width() + 24) / 2;
$('#cfm-box').css({
'margin-top' : -popMargTop,
'margin-left' : -popMargLeft
});
// Add the mask to body
$('body').append('<div id="mask"></div>');
$('#mask').fadeIn(300);
//if button no click, do nothing
//#no refer to the button ID no.
$('#no').click(function(){
$('#mask , .cfm-popup').fadeOut(300 , function() {
$('#mask').remove();
});
});//end #no
//if yes click, delete data from db
//#yes refer to the button ID yes.
$('#yes').click(function(){
//parameter to send for delete WHERE statement
var tahun = $('#tahunSemasa').val();
var suku = $('#sukuSemasa').val();
var dataString = "tahun="+tahun+"&suku="+suku+"&id="+idData+"&action=delete";
$.ajax({
type: "POST",
url: "prestasiProses.php",
data: dataString,
cache: false,
success: function(html)
{
alert(html);
if(html=='true')
{
window.location.href="main.php?a=31&tahun="+tahun+"&suku="+suku+"&act=delete";
}
else
{
alert("Failed!");
}
}
});
$('#mask , .cfm-popup').fadeOut(300 , function() {
$('#mask').remove();
});
});//end #yes
});//end .deleteData
Any ideas why this code loop like that?
Thanks for the help
You shouldn't have all that code inside your $('.deleteData').click(function(){. Check out this fiddle to see how I think you should have your code laid out. Notice that I have made the idData a global variable and moved your $('#no').click(function(){ and $('#yes').click(function(){ code to the bottom. My fiddle isn't working because it doesn't have all your includes, but should show you what I mean.
I also moved your mask removal inside your ajax success handler as it seems like you want that to run once your ajax comes back. Is that the case?
EDIT:
The problem you are having is because you are binding to items with the deleteData class multiple times.
When you run the selector $('.deleteData').click(, you are saying, "get each instance of an element with the class 'deleteData' and then bind this function to it." Since you then had the $('#no').click( and $('#yes').click( INSIDE your $('.deleteData').click( you were binding your $('#no').click( and $('#yes').click( twice. If you had three instances of the 'deleteData', your ajax code would have run 3 times.
The problem is that everytime you click deleteData you will bind click to yes and no, to if you click deleteData twice, you bind click to yes and no twice, because it's inside deleteData click event.
So, to prevent this behaviour you have to remove it from inside deleteData event.
You can try this demo.
Type how many binds do you want
Click some text
See how many times it logs the value
I'm very sure a variation of this has been asked before, and my asking stems from my elementary knowledge of how it all works. I have been reading and reading and reading, and i'm turning to stackoverflow for some help on my question/problem.
Let me describe to everyone what i'd like. When a table is build on my webpage via a php include call, that table contains a column called 'Info', and in each row of that column for the table, is a hyperlink in created, called info. What i'd like to do is, when that hyper link is clicked, i'd like to return in a popup of some kind alert popup, jquery dialog, etc the data that the info link would return if navigating to that page. So in theory, i'm eliminating the navigation and providing that information to the user in a friendly dialog.
So on the index page where everything is happening i have code as follows:
include buildtable.php
Then in the buildtable.php i'm looping through a query and building a table. the column associated with the link look like:
echo '<td> Info </td>';
Now the above works if i navigate to that page; however, i'd like to try to display this in a dialog.
My questions are as follows:
1) should i keep the construction of the link as above, or should i change it to something like:
echo '<td> Info & nbsp;</td>';
2) the jquery dialog is confusing me, and i'm not even sure if i'm on the right track...
function getInfo(){
var $dialog = $('<div class="blah"></div>')
var $link = $this.val();)
.dialog({
autoOpen: false,
title: 'Information'
$.ajax {(
url:'myphpfile.php',
dataType: 'html',
data: 'link=' $link,
success: function( data ){
$('#<div id section on calling page>').html( data );
}//end success
}); //end ajax
});//end dialog
}//end Function
Any help and/or good tutorial links would be most appreciated.
use this link
echo '<td> <a id="infopopup" href="anotherpage.php?CheckoutId='.$DataArrDT[5].'&DbSchemaID='.$DataArrDT[2].'&DbId='.$DataArrDT[3].'">Info</a> </td>';
and use this javascript
$('#infopopup').click(function() {
var url = this.href;
var dialog = $("#dialog");
if ($("#dialog").length == 0) {
dialog = $('<div id="dialog" style="display:hidden"></div>').appendTo('body');
}
// load remote content
dialog.load(
url,
{},
function(responseText, textStatus, XMLHttpRequest) {
dialog.dialog();
}
);
//prevent the browser to follow the link
return false;
});`