jQuery use .on(load) with ajax loaded content - javascript

I have a webpage with AJAX loaded content. If I click on "export" the content reloads and generate an HTML a-Element using PHP:
<a style=\"display:none;\" id=\"menue-export-link\" href=\"download/".$this->select->downloadcsv."\"></a>
Now I want to start the download automatically, so I wrote the following JavaScript code to start the download on a-Element load:
$(document).ready(function () {
$(document).on('load', '#menue-export-link', function() {
console.log('click export');
$('#menue-export-link').click();
$('#menue-export-link').remove();
});
});
But nothing happens, does somebody have any idea?

First of all there is no load or onload event for html anchor elements.
So as #The F said you have to trigger the download in your ajax success callback. Remember to find and trigger it after you have appended the html in your DOM. For more on jQuery ajax http://api.jquery.com/jquery.ajax/
And now comes triggering the download part. Triggering the click event which causes the navigation is a bit trickier. The following question answers that very well jQuery: how to trigger anchor link's click event and
How can I simulate an anchor click via jquery?

Your js is triggered when your main page is loaded and #menue-export-link probably does not exist to that time. If using $.ajax to load that link, place your javascript inside the success callback to make sure that your link exists or is being loaded before triggering your code.

$(document).on("click", "#menue-export-link", function() {
console.log("click export");
});

Related

Clearing javascript code from cache

I have page which contains jQuery code:
$('#tstButton').live('click',function(){
alert();
});
And I load this page from ajax call.
When I load the page multiple times, each time it loads the script and stores to cache.
Say when I make ajax call three times. and click $('#tstButton') once, then it will alert 3 time.
I have used:
cache:false
in ajax call. But still its not clearing cache.
How can I clear these javascript codes from cache?
You can unbind the event first before binding using die() if you're using jQuery < v1.7.2.
$('#tstButton').die('click').live('click', function() {
alert();
});
If you're using jQuery v > 1.7.2
You can use on and off:
$('#tstButton').off('click').on('click', function() {
alert();
});
You can OFF your previously binded click using jquery OFF function.
$('#tstButton').off("click").on('click',function(){
alert();
});
In my opinion, it is not a good solution to bind \ unbind event every time when you have dynamically loaded page.
You can use event delegation and bind it only once.
Execute this once on page load and it will properly work on any dynamically added elements:
$(document).on('click', '#tstButton', function() {
alert();
});
document can be replaced with more precise non-updating container which stores this button.
Here is a working JS Fiddle Demo

call on .load in not working properly

I have a page xyz.jsp which having a script on page load and its working fine.
function loginRegOverlay() {
$("#hiddenLoginButton").click();
};
but if i am calling this page on abc.jsp on jquery .load page is rendering but
$("#hiddenLoginButton").click(); is not working.
dont know the reason why its not coming.
please tell me that its working onload of xyz.jsp but if i calling that page on abc.jsp it not working
Adding code which is in abc.jsp:
function newstyle(){
$("#test").load("xyz.jsp");
};
so, newstyle calling onload on abc.HTML rendering fine but
function loginRegOverlay() {
$("#hiddenLoginButton").click();
};
which is in xyz.jsp not working fine if i am calling that on abc.jsp..i hope its clear now.
.load() is an ajax request so if you are loading elements from other page then direct binding of events to the element won't work. So workaround to this is event delegation which you have to delegate the event to the existing parent item which is loading the html from other page.
$(document).find('#hiddenLoginButton').click();
You can delegate it to the closest parent which was available at the time of page load:
$('#ID or .Class of the parent item').find('#hiddenLoginButton').click();
like:
$('#wrapper').find('#hiddenLoginButton').click();
side note:
if you are able to post some rendered html then that would be much better to see what is going on and what will be suggested to overcome this.
Try with .trigger like
$("#hiddenLoginButton").trigger('click');
and we assumed that you have called the function loginRegOverlay() on page load
AND I have noticed that you wrote code in xyz.jsp and you want to trigger it on abc.jsp then include that xyz.jsp at abc.jsp
inlcude('xyz.jsp');
and plz makesure that those buttons ids are unique bec xyz is loads on abc and due to duplicate in ids they wont work,you can give them same class and fire it as once
You can use .live or .on method for event delegation
$("#hiddenLoginButton").live('click', function(){});

Call JavaScript function when button loaded by ajax is clicked

I have an html form that loads its contents through ajax and includes buttons that, when clicked, should execute a JavaScript function that is defined in the html page's script tag. SO: Button is loaded through ajax (works), but when button is clicked, it doesn't trigger the desired action and doesn't trigger a JavaScript error in Firebug. How does one get the onclick signal of a bunch of buttons loaded through ajax to bind to an already existing JavaScript function?
EDIT: I should have noted also that I am not using JQuery. I am willing to do so if it is the only way, but otherwise, I would prefer to use only native JavaScript.
EDIT2: My problem was a bit more involved, but as was stated in the chosen answer, you should be able to set the onclick event handler in the php script before sending the data through ajax. If you have a data-heavy response and want to reduce bandwidth, you might consider doing everything client-side, but I find it easier in most situations just to set the onclick attribute in the php script.
Your dynamically generated button could have an inline event bound to it. When generating the button, simply make sure it has an onclick="alreadyExistingFunc();" and the page will happily execute it.
Alternatively, when your AJAX data is finished writing itself into the document, find the new button(s) and bind the event to them:
function ajaxSuccess()
{
document.getElementById('newButtonIdHere').onClick = function() {
alreadyExistingFunc();
}
}
That should do the trick. Also note that if you ever "need" a small part of jQuery to do something (like selectors or event handling), you can almost always do it without loading the whole library.
Append/insert the HTML (retrieved AJAX response) to DOM and bind click event to it:
function alreadyExistingFunc() {
alert('button is clicked!');
}
var ajax_data ="<button id='my-button'>My Button</button>";
$('body').append(ajax_data).find('#my-button').on('click', function(e){
alreadyExistingFunc();
// some more code...
});
OR:
$('body').append(ajax_data).find('#my-button').on('click', alreadyExistingFunc);
You could also use a callback:
function getAjaxContent(callback) {
$.ajax({url: "url"}).done(function() {
callback(data);
});
}
getAjaxContent(function (data) {
//ajax content has been loaded, add the click event here
}

Jquery Mobile Onclick event does not work before refresh

I Created some button with an onclick event that runs a function that alerts "hi". The onclick event only works if I refresh the page.
Here is the function:
function testme(){
alert("test");
}
And here is the onclick event:
Button
How can I make an onclick event work without having to refresh the page?
You could try not using a function if that is all you doing.
Button
You could also try adding an click event in jQuery
$(document).ready(function(){
$('#someid').click(function(event){
event.stopImmediatePropagation();
event.preventDefault();
alert('hi')
});
});
edit 1
From the question spookycoder suggested:
You could also use rel="external" on the a tag, this will allow it to perform normally on the jQuery Mobile pages.
this worked for me (especially on iPhone/iPad):
Button
I got a workaround for this issue by changing the way I load my pages.
I put target="_self" into the href element so it don't load using the # system - this way the javascript loads with the initial page load while navigating from one page to a nother.
I will put the below link on my index.html page that will navigate to my signup.html page.
Signup
NOTE: You will lose the 'fancy' jQuery Mobile page transition feature
I think you have to use :
$(document).on('pageinit',function(){
//Some Code
});
instead of :
$(document).ready(function (){
//Some Code
});

jquery - Block specific links before a page fully loads and binds click events

I have a modal dialog plugin written in jquery, that binds to the click event of all of the <a> elements with a specific class.
The modal dialog 'fetches' a page via AJAX, which is declared under the 'href' parameter of the <a> element.
Everything works fine, but - when a user clicks the <a> link before the page was fully loaded and ready (before the click event is binded to the element) - the browser navigates to the page declared in the 'href' parameter.
Any ideas of how to prevent this behavior? An ideal situation would be to ignore clicks on these elements before the page has fully loaded. Client-side performance is crucial.
If you need to avoid inline scripting, then you could utilise jQuery's live() method to bind an event handler for elements that have not yet been added to the DOM:
1) Be sure to include jQuery in the <head> and not the <body>, since we need to initiate the following code before any elements in the body are created.
2) Include the following, also in the <head> (e.g. as an external js file):
$("a").live("click", function(){// Use a more specific selector than "a" if poss.
getAjax( // This is your Ajax function. Adapt as required.
$(this).attr('href') // Pass in the <a>'s href attribute.
);
return false; // Cancel the default click handler, to prevent page redirect.
});
Typically you'll avoid directly coding any href into the tag. Instead set href="javascript:void(0)" and handle the submission with jQuery.
Do something like this:
<a onclick="SomeJQueryCall()" href="javascript:void(0)">Click Me!</a>
And here's the jQuery script:
function SomeJQueryCall() {
//ask the web server for some AJAX xml
$.get(SomeUrl, null, SomeCallBackFunction(), "xml");
}

Categories

Resources