I have a typical AJAX call that appends some HTML to the current page. I want to be able to access the newly inserted HTML with typical jQuery selectors.
Here's what I'd like to be able to do...
$.ajax({
url: url,
success: function(data) {
$('body').append(data);
}
});
$('#new_div').show();
#new_div
would be some HTML element from the data I retrieved. I don't necessarily want to attach events to the new elements (like click
), so using something like .load()
or .on()
doesn't work here (as far as I know).
I tried setting the $.ajax()
call to a variable: var new_div = $.ajax(...)
but that didn't get me anywhere.
AJAX just uses a combination of: A browser built-in XMLHttpRequest object (to request data from a web server) JavaScript and HTML DOM (to display or use the data)
XMLHttpRequest (XHR) objects are used to interact with servers. You can retrieve data from a URL without having to do a full page refresh. This enables a Web page to update just part of a page without disrupting what the user is doing. XMLHttpRequest is used heavily in AJAX programming.
Ajax requests do just that. With this, all codes following this one will execute immediately; you will not have to wait until the function returns. This way, your user would not have to wait for findItem() to return a result. Of course, because you still need an answer, you would have to include a callback.
Domajax is a free jQuery plugin that give you tools to add ajax calls within your application, without a piece of javascript. It uses HTML5's data- attribute, and jQuery's . on() method to handle your ajax interactions.
If you would like to manipulate the new content immediately after (or even before) inserting it to the DOM, you can put that in the AJAX success callback too:
$.ajax({
url: url,
success: function(data) {
$('body').append(data);
$('#new_div').show();
}
});
On the other hand, if you want to bind handlers to content that will be added to the page via ajax, jQuery does that like this:
$(document).on('click', '#new_div', function(){
alert("This function is bound to all #new_div's click events, even if they are added to the DOM via ajax later!")
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With