Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing DOM object after AJAX call?

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.

like image 709
Shpigford Avatar asked Sep 04 '13 12:09

Shpigford


People also ask

Is Dom used in AJAX?

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)

Which object can be used to retrieve data in AJAX?

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.

Does AJAX wait for response?

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.

What is Dom AJAX?

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.


1 Answers

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!")
});
like image 64
doctororange Avatar answered Oct 07 '22 08:10

doctororange