Call JavaScript function when button loaded by ajax is clicked - javascript

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
}

Related

toggleClass not working when coming from an AJAX request

I have a webpage with a link to make an AJAX request. When the following .js comes back the toggleClass function does not work.
$(document).ready(function(){
$("td").click(function(){
$(this).toggleClass("br");
});
});
If I replace toggleClass("br") with something like addClass("br") then that does work.
Furthermore, toggleClass works fine if I put the .js into the html page or if I run it from the console. It seems that something about both toggleClass and AJAX requests together stops this code from working but I have no Earthly idea as to why that might be.
UPDATE
I've figured out the problem. I had accidentally included jQuery two times and so javascript from AJAX requests was being run twice. Hence why only toggleClass was "not working" while addClass and removeClass were.
The only mystery left is why this was only the case when the .js came from an AJAX request as opposed to when it was in the HTML itself.
Assuming you want the click handler to be on an element that is populated by the AJAX query, you have to late bind the event to a DOM element that exists before the AJAX query fires. Let's say you have the following HTML:
<html>
<body>
<table id="populatedByAjax"></table>
</body>
</html>
...and you know you're going to populate the table via AJAX. Then we need to declare our jQuery selector like this:
$("#populatedByAjax").on("click", "td", function(){
$(this).toggleClass("br");
});
That makes sure that the click event is bound to any current or future td elements in the selector #populatedByAjax
Use delegated events to bind the click event to dynamically created elements and also to avoid the need to frequently attach and remove event handlers.
$(document).on('click', '#td', function() {
$(this).toggleClass("br");
});

__doPostBack is not triggering from external Js file

When i tried to trigger __doPostBack() manually from external Js file is not triggering.
$(document).ready(function () {
$("#tabsids a").click(function () {
__doPostBack('<%= btntrigger.ClienID%>', '');
});
});
You need the name attribute of the HTML element of the button you wish to click as the first argument to __doPostBack(). HOw you will get that in your actual case is a different matter, but you cannot use server code blocks ()<%=%> outside of ASP context (i.e., outside of aspx, ascx files). Perhaps you can consider a partial ID selector with jQuery, something like
$("input[id$='btntrigger']").attr("name")
where input is the element type, so you may need to change it.
YOu can also simply try the click() method of the jQuery wrapper that you get, perhaps it will do the job.

jQuery method .on() on dynamically(AJAX) loaded data

So i have a page in my site that has a with class name 'mainContent' that automatically updates with new data every like 1 minute using AJAX .ajax(). Content in this requires some JavaScript for some functionalities. The problem now is that JavaScript does not work on the new data loaded into the DOM without whole page refresh. I have searched and found using .on() to bind the data to the DOM should work, like so:
$(document).on('click', '.mainContent',function(){
expand();
});
where expand is a JS function.
However, it only works fully on the new data but not on the data that had been added in the previous AJAX call...
You're almost there, it's just your logic. This is how this jQuery function works:
You set a container. This is the element that will hold the AJAX-crated items that you want to bind. The more specific, the better. Otherwise, you'll wire an event for your whole page, which is bad
The event. What are you listening to?
Who will fire the handler. A selector to form the phrase: when these guys inside this big guy fire this event, run this code.
Let's suppose that your mainContent gets filled with hyperlinks (I'm not sure because your question lacks on details):
$('.mainContent').on('click', 'a', function () {
//do your magic
//$(this) is the clicked link
});
This way, our phrase is: when links inside .mainContent are clicked, run this.
UPDATE
Based on the comments, I think that your problem may be on the expand function.
Let's give a try:
$('.mainContent').on('click', 'a', function () {
$(this).simpleexpand();
});
Have you try to apply your binding on the callback of the ajax function that load your new datas ?
Something like that :
$.ajax({
url: url...//Classic ajax call
}).done(function ( data ) {
//Apply your 'on' here
});

jquery load / get and dom elements not triggering...?

I'm loading a simple page using:
$.get('../admin/login.php', function(data) { $('#box-contents').html(data); });
Now, on this login.php page I have an input field, and in my global JavaScript file, I have an event that triggers on .change() - but this isn't firing!?
Is this because I have loaded this file on the page so jquery doesn't know that it's now there? Do I need to also include my global JS file within the 'login.php' page too?
Any help on this would be much appreciated
instead of using .get(), use .load() as it was intended for this purpose. Also for your .change() event, you need to either attach it after the element exists (which could be done in your callback below), or you can use .live() to attach the event to any current or future DOM elements.
Callback method
$('#box-contents').load('../admin/login.php', function() {
$('input').change(function() {
//do stuff on change
});
});
Live method
$('input').live('change', function() {
//do stuff on change
});

How to call a Javascript after a div is replaced?

I dynamically have to call a Javascript after a tag is rendered. Is it possible? I am doing some Ajax call which on return should repaint a DIV tag. And it is repainting successfully. I need to fire a Javascript method AFTER the DIV tag is repainted. How to do that?
Thanks
Short answer: directly it ain't possible (there is no "repaint" or "change" event on DIVs).
However using jQuery or other JS framework that supports custom events you could add an event listener on the div and fire an event in your AJAX call (i suppose it the onSuccess function; so as the last action inside fire custom event).
Even more simply you could just call the desired JavaScript method after you finish changing your DIV.
// I am doing some Ajax call
function ajax( url ) {
xmlHttp.onreadystatechange = function () {
// ...
};
// which on return should repaint a DIV tag.
div.modify();
// I need to fire a Javascript method AFTER the DIV tag is repainted.
javascriptMethod();
}
Or am I missing something here? :) Maybe you want to do the painting thing when the request is finished, but still i don't see any problem here.

Categories

Resources