Jquery stops when content is updated via Ajax - ajax

I have:
$('.image.txt_over').hover(function(){
$(".screen", this).stop().animate({top:'165px'},{queue:false,duration:300});
$(this).fadeTo("slow", 1);
}, function() {
$(".screen", this).stop().animate({top:'226px'},{queue:false,duration:460});
});
and I am trying to keep the jquery hover effect once a new set of images are refreshed via Ajax. Currently the jquery is killed once the Ajax refreshes.
I think I need .delegate() or .live() but cant seem to get either to work. Still learning jquery.

Try this:
$('body').delegate('.image.txt_over', 'mouseover mouseout', function(event) {
if (event.type == 'mouseover') {
$(".screen", this).stop().animate({top:'165px'},{queue:false,duration:300});
$(this).fadeTo("slow", 1);
} else {
$(".screen", this).stop().animate({top:'226px'},{queue:false,duration:460});
}
});

Related

jquery .submit live click runs more than once

I use the following code to run my form ajax requests but when i use the live selector on a button i can see the ajax response fire 1 time, then if i re-try it 2 times, 3 times, 4 times and so on...
I use .live because i also have a feature to add a post and that appears instantly so the user can remove it without refreshing the page...
Then this leads to the above problem... using .click could solve this but it's not the ideal solution i'm looking for...
jQuery.fn.postAjax = function(success_callback, show_confirm) {
this.submit(function(e) {
e.preventDefault();
if (show_confirm == true) {
if (confirm('Are you sure you want to delete this item? You can\'t undo this.')) {
$.post(this.action, $(this).serialize(), $.proxy(success_callback, this));
}
} else {
$.post(this.action, $(this).serialize(), $.proxy(success_callback, this));
}
return false;
})
return this;
};
$(document).ready(function() {
$(".delete_button").live('click', function() {
$(this).parent().postAjax(function(data) {
if (data.error == true) {
} else {
}
}, true);
});
});​
EDIT: temporary solution is to change
this.submit(function(e) {
to
this.unbind('submit').bind('submit',function(e) {
the problem is how can i protect it for real because people who know how to use Firebug or the same tool on other browsers can easily alter my Javascript code and re-create the problem
If you don't want a new click event bound every time you click the button you need to unbind the event before re-binding it or you end up with multiple bindings.
To unbind events bound with live() you can use die(). I think the syntax using die() with live() is similar to this (untested):
$(document).ready(function(){
$('.delete_button').die('click').live('click', function(){
$(this).parent().postAjax(function(data){
if (data.error == true){
}else{
}
}, true);
});
});
However, if you are using jQuery 1.7 or later use on() instead of live() as live() has been deprecated since 1.7 and has many drawbacks.
See documentation for all the details.
To use on() you can bind like this (I'm assuming the delete_button is a dynamically added element) :
$(document).ready(function(){
$(document).off('click', '.delete_button').on('click', '.delete_button', function(){
$(this).parent().postAjax(function(data){
if (data.error == true){
}else{
}
}, true);
});
});
If you are using an earlier version of jQuery you can use undelegate() or unbind() and delegate() instead. I believe the syntax would be similar to on() above.
Edit (29-Aug-2012)
the problem is how can i protect it for real because people who know
how to use Firebug or the same tool on other browsers can easily alter
my Javascript code and re-create the problem
You can some-what protect your scripts but you cannot prevent anyone from executing their own custom scripts against your site.
To at least protect your own scripts to some degree you can:
Write any script in an external js file and include a reference to that in your site
Minify your files for release
Write any script in an external js file and include a reference to that in your site
That will make your html clean and leave no trace of the scripts. A user can off course see the script reference and follow that for that you can minify the files for release.
To include a reference to a script file:
<script type="text/javascript" src="/scripts/myscript.js"></script>
<script type="text/javascript" src="/scripts/myscript.min.js"></script>
Minify your files for release
Minifying your script files will remove any redundant spacing and shorten function names to letters and so no. Similar to the minified version of JQuery. The code still works but it is meaningless. Off course, the hard-core user could follow meaningless named code and eventually figure out what you are doing. However, unless you are worth hacking into I doubt anyone would bother on the average site.
Personally I have not gone through the minification process but here are some resources:
Wikipedia - Minification (programming)
Combine, minify and compress JavaScript files to load ASP.NET pages faster
How to minify (not obfuscate) your JavaScript using PHP
Edit (01-Sep-2012)
In response to adeneo's comment regarding the use of one().
I know you already found a solution to your problem by unbinding and rebinding to the submit event.
I believe though it is worth to include a mentioning of one() in this answer for completeness as binding an event with one() only executes the event ones and then unbinds itself again.
As your click event, when triggered, re-loads and rebinds itself anyway one() as an alternative to unbinding and re-binding would make sense too.
The syntax for that would be similar to on(), keeping the dynamic element in mind.
// Syntax should be right but not tested.
$(document).ready(function() {
$(document).one('click', '.delete_button', function() {
$(this).parent().postAjax(function(data) {
if (data.error == true) {} else {}
}, true);
});
});​
Related Resources
live()
die()
on()
off()
unbind()
delegate()
undelegate()
one()
EDIT AGAIN !!!! :
jQuery.fn.postAjax = function(show_confirm, success_callback) {
this.off('submit').on('submit', function(e) { //this is the problem, binding the submit function multiple times
e.preventDefault();
if (show_confirm) {
if (confirm('Are you sure you want to delete this item? You can\'t undo this.')) {
$.post(this.action, $(this).serialize(), $.proxy(success_callback, this));
}
} else {
$.post(this.action, $(this).serialize(), $.proxy(success_callback, this));
}
});
return this;
};
$(document).ready(function() {
$(this).on('click', '.delete_button', function(e) {
$(e.target.form).postAjax(true, function(data) {
if (data.error) {
} else {
}
});
});
});​
jQuery.fn.postAjax = function(success_callback, show_confirm) {
this.bind( 'submit.confirmCallback', //give your function a namespace to avoid removing other callbacks
function(e) {
$(this).unbind('submit.confirmCallback');
e.preventDefault();
if (show_confirm === true) {
if (confirm('Are you sure you want to delete this item? You can\'t undo this.')) {
$.post(this.action, $(this).serialize(), $.proxy(success_callback, this));
}
} else {
$.post(this.action, $(this).serialize(), $.proxy(success_callback, this));
}
return false;
})
return this;
};
$(document).ready(function() {
$(".delete_button").live('click', function() {
$(this).parent().postAjax(function(data) {
if (data.error == true) {
} else {
}
}, true);
});
});​
As for the "people could use Firebug to alter my javascript" argument, it does not hold : people can also see the request that is sent by your $.post(...), and send it twice.
You do not have control over what happens in the browser, and should protect your server side treatment, rather than hoping that "it won't show twice in the browser, so it will prevent my database from being corrupt".

HighChart not working when called by ajax

Hi guys i have a page which is working perfectly it contains a highchart. I want to show this page on the existing page through an ajax call. My ajax is working perfectly but the highcharts are not displaying when i make ajax call.
link of my highchart is
http://www.rahatcottage.com/AI/J/examples/line-log-axis/index.php
And My ajax script goes here
var xmlhtt
function load(str,str1)
{
xmlhtt=GetXmlHttpObject();
if (xmlhtt==null)
{
alert ("Your browser does not support Ajax HTTP");
return;
}
var url="examples/line-log-axis/index.php";
url=url+"?q="+str;
url=url+"&q1="+str1;
xmlhtt.onreadystatechange=getOutpt;
xmlhtt.open("GET",url,true);
xmlhtt.send(null);
}
function getOutpt()
{
if (xmlhtt.readyState==3||xmlhtt.readyState==2||xmlhtt.readyState==1|
|xmlhtt.readyState==0)
{
document.getElementById("apDiv1").innerHTML="Loading ";
}
if (xmlhtt.readyState==4)
{
document.getElementById("apDiv1").innerHTML=xmlhtt.responseText;
document.getElementById("apDiv1").focus();
}
}
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
I guess because highgraphs are using Jquery thats y ajax is not running them
EDITED
So what you are doing is, that you have a working chart page, and through ajax you wish to load that page into a div of another page. I don't think that will be possible, you can just do that, especially if that page has javascripts, what you are doing is just getting the generated html of the working chart page, and pasting it inside the div, this won't run the necessary javascripts for the chart generation.
Try using an iframe instead.
HTML
<iframe id="frame" />
SCRIPT
function load(str,str1)
{
$('#frame').attr('src', "examples/line-log-axis/index.php?q="+str+"&q1="+str1);
}
**OLD**
series: [{
data: JSON.parse("[" + text + "]")
}]
`text = ','`, hence a json parse error. Revisit your json building # php to correctly spit `text`

How to use AJAX as an alternative to iframe

I'm trying to put together a snappy webapp, utilizing JS, Prototype and AJAX for all my requests once the GUI has loaded. The app is simple: A set of links and a container element to display whatever the links point to, just like an iframe. Here's an approximate HTML snippet:
<a class="ajax" href="/somearticle.html">An article</a>
<a class="ajax" href="/anotherarticle.html">Another article</a>
<a class="ajax" href="/someform.html">Some form</a>
<div id="ajax-container"></div>
The JS that accompanies the above (sorry it's a bit lengthy) looks like this:
document.observe('dom:loaded', function(event) {
ajaxifyLinks(document.documentElement);
ajaxifyForms(document.documentElement);
});
function ajaxifyLinks(container) {
container.select('a.ajax').each(function(link) {
link.observe('click', function(event) {
event.stop();
new Ajax.Updater($('ajax-container'), link.href, {
method: 'get',
onSuccess: function(transport) {
// Make sure new ajax-able elements are ajaxified
ajaxifyLinks(container);
ajaxifyForms(container);
}
});
});
});
}
function ajaxifyForms(container) {
console.debug('Notice me');
container.select('form.ajax').each(function(form) {
form.observe('submit', function(event) {
event.stop();
form.request({
onSuccess: function(transport) {
$('ajax-container').update(transport.responseText);
// Make sure new ajax-able elements are ajaxified
ajaxifyLinks(container);
ajaxifyForms(container);
}
});
});
});
}
When clicking a link, the response is displayed in the container. I'm not using an iframe for the container here, because I want whatever elements are on the page to be able to communicate with each other through JS at some point. Now, there is one big problem and one curious phenomenon:
Problem: If a form is returned and displayed in the container, the JS above tries to apply the same behavior to the form, so that whatever response is received after submitting is displayed in the container. This fails, as the submit event is never caught. Why? Note that all returned form elements have the class="ajax" attribute.
Phenomenon: Notice the console.debug() statement in ajaxifyForms(). I expect it to output to the console once after page load and then every time the container is updated with a form. The truth is that the number of outputs to the console seems to double for each time you click a link pointing to a form. Why?
I found another way to achieve what I wanted. In fact, the code for doing so is smaller and is less error prone. Instead of trying to make sure each link and form element on the page is observed at any given time, I utilize event bubbling and listen only to the document itself. Examining each event that bubbles up to it, I can determine whether it is subject for an AJAX request or not. Here's the new JS:
document.observe('submit', function(event) {
if (event.target.hasClassName('ajax')) {
event.stop();
event.target.request({
onSuccess: function(transport) {
$('ajax-container').update(transport.responseText);
}
});
}
});
document.observe('click', function(event) {
if (event.target.hasClassName('ajax')) {
event.stop();
new Ajax.Updater($('ajax-container'), event.target.href, {
method: 'get'
});
}
});
Works like a charm :)

Why are the jQuery functions only working the first time they're called?

There is a link that, when clicked, toggles between loading HTML into a div and emptying the div. When the div is clicked to load the html, I use the jQuery ajax load() function. When the text is loading, I want to display "Please wait...", so I tried using the jQuery ajaxStart() and ajaxStop() methods, but they only seemed to work the first time the load() function was called. So I switched to ajaxSend() and ajaxSuccess, but that also only seems to work the first time the load function is called. What's wrong?
HTML:
<p id="toggleDetail" class="link">Toggle Inspection Detail</p>
<p id="wait"></p>
<div id="inspectionDetail"></div>
jQuery:
$(
function(){
$('#toggleDetail').click(function(){
if($.trim($('#inspectionDetail').text()).length)
{
$('#inspectionDetail').empty();
}
else
{
$('#inspectionDetail').load('srInspectionDetailFiller.cfm');
}
});
}
);
$(
function(){
$('#wait').ajaxSend(function() {
$(this).text('Please wait...');
});
}
);
$(
function(){
$('#wait').ajaxSuccess(function() {
$(this).text('');
});
}
);
You should put up the 'Please wait...' message in your click function, then clear the message upon successful completion of your load:
$('#toggleDetail').click(function(){
if($.trim($('#inspectionDetail').text()).length)
{
$('#inspectionDetail').empty();
}
else
{
$('#wait').text('Please wait...');
$('#inspectionDetail').load('srInspectionDetailFiller.cfm', function() {
$('#wait').text('');
});
}
});
Edit: Although ajaxSend should technically work here, I don't recommend it. With ajaxSend, "All ajaxSend handlers are invoked, regardless of what Ajax request is to be sent". It seem overkill to me to hook all Ajax requests on the page which you're really only trying to deal with this single click.

Colorbox not appearing on links called through ajax

I am trying to use colorbox on a page where i have three links each of which have onclick event which call an ajax page and response text is shown in the necessary divs. everything is working fine except colorbox links. After i call the content through ajax the links are not working to appear the colorbox. Here is my code to call the colorbox which is when page is loaded working.
<p>
$(document).ready(
function()
{
$(".editchecklist").colorbox({width:"50%", height:"35%", iframe:true, onClosed:function(){ location.reload(true); } });
}
);
I tried to look for this problem but everything is related to jQuery ajax call not simple ajax call. The are advising to use .live() or rebind methods which i have no idea how and where should i use them.
here is my ajax call code:
function getxmlhttp()
{
var xmlHttp = false;
if (window.XMLHttpRequest)
{
// If IE7, Mozilla, Safari, etc: Use native object
var xmlHttp = new XMLHttpRequest();
}else
{
if (window.ActiveXObject)
{
// ...otherwise, use the ActiveX control for IE5.x and IE6
var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
function process_ajax2(phpPage, objID, getOrPost,clickedLink)
{
xmlhttp = getxmlhttp();
var obj = document.getElementById(objID);
if(getOrPost == "get")
{
xmlhttp.open("GET",phpPage);
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById('change_'+clickedLink).innerHTML = xmlhttp.responseText;
}
}
xmlhttp.send(null);
}
}
Please tell me how would i solve this problem?
thanking you.
if I understand your question correctly, you've loaded content into the page via ajax after pageload.
The javascript that you've got is only going to work for data that is there on page load, so what you'd need to do is use .live() which will work on elements loaded at page load and after.
(note: I don't know what page you're trying to call here - so I am assuming it is in the link href)
Something like this should work
$(function(){
$(".editchecklist").live('click',function(e){
e.preventDefault();
$.colorbox({
width:"50%",
href:$(this).attr('href'),
height:"35%",
iframe:true,
onClosed:function(){
location.reload(true);
}
});
});
});
more on jquery live http://api.jquery.com/live/

Resources