Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind Events on Ajax loaded Content?

I have a link, myLink, that should insert AJAX-loaded content into a div (appendedContainer) of my HTML page. The problem is that the click event I have bound with jQuery is not being executed on the newly loaded content which is inserted into the appendedContainer. The click event is bound on DOM elements that are not loaded with my AJAX function.

What do I have to change, such that the event will be bound?

My HTML:

<a class="LoadFromAjax" href="someurl">Load Ajax</a> <div class="appendedContainer"></div> 

My JavaScript:

$(".LoadFromAjax").on("click", function(event) {     event.preventDefault();     var url = $(this).attr("href"),         appendedContainer = $(".appendedContainer");      $.ajax({     url: url,     type : 'get',     complete : function( qXHR, textStatus ) {                    if (textStatus === 'success') {             var data = qXHR.responseText             appendedContainer.hide();             appendedContainer.append(data);             appendedContainer.fadeIn();         }       }     });  });  $(".mylink").on("click", function(event) { alert("new link clicked!");}); 

The content to be loaded:

<div>some content</div> <a class="mylink" href="otherurl">Link</a> 
like image 717
confile Avatar asked May 16 '13 22:05

confile


People also ask

How do you trigger a change event after AJAX call?

One way to trigger an event is to use the jquery trigger function. Show activity on this post. function changeDate(){ $. ajax({ url, data: data, type: "POST", dataType: "json", success: function(cbdata) { update_table(cbdata); } }); } $('#selector').

What is bind in AJAX?

The bind() method attaches one or more event handlers for selected elements, and specifies a function to run when the event occurs.

What is contentType in AJAX?

contentType is the type of data you're sending, so application/json; charset=utf-8 is a common one, as is application/x-www-form-urlencoded; charset=UTF-8 , which is the default. dataType is what you're expecting back from the server: json , html , text , etc.

How would you fire a callback when any AJAX request on a page has completed?

The "complete" function executes only after the "success" of ajax. So try to call the printWithAjax() on "complete". This should work for you.


1 Answers

Use event delegation for dynamically created elements:

$(document).on("click", '.mylink', function(event) {      alert("new link clicked!"); }); 

This does actually work, here's an example where I appended an anchor with the class .mylink instead of data - http://jsfiddle.net/EFjzG/

like image 185
dsgriffin Avatar answered Oct 08 '22 08:10

dsgriffin