views:

2023

answers:

1

I'm trying to load a DIV element from an external page into my current page using the Ajax/jQuery.ajax function. While I have successfully been able to load an entire external page, I can't seem to load just the DIV element.

Here's my code:

$("a").click(function() {
  /* grabs URL from HREF attribute then adds an  */
  /* ID from the DIV I want to grab data from    */
  var myUrl = $(this).attr("href") + "#external-div";
  $.ajax( {
  url: myUrl,
  success: function(html) {
    /* loads external content into current div element */
    $("#current-div").append(html);
    }
  });
  return false;
});

It grabs the HREF attribute without any trouble, but won't append "#external-div" to the URL. Any ideas?

Thanks much!

~Jared Crossley

A: 

If you wanted to just return that div you could use the load method of jQuery to simply load the content returned into your #current-div ala

$("a").click(function() {
  /* grabs URL from HREF attribute then adds an  */
  /* ID from the DIV I want to grab data from    */
  var myUrl = $(this).attr("href") + " #external-div";
  $("#current-div").load(myUrl);
  return false;
});

Take a look at the jQuery Ajax/load documentation

Quintin Robinson
Hi Quintin,Thanks for your quick response. I would prefer not to use the load method as it limits what sort of effect chaining and data management I can do, but right now it's the only option of which I'm aware. Thanks again for your reply.Does anyone else know if the Ajax/jQuery.ajax function will allow me to load an external div?
That's not entirely true, you can still provide a callback for the load method and apply chaining in there, the scenario (via code) that is described appear to be anything beyond what load can do. Is there something in particular aside from what you posted that you are trying to accomplish?
Quintin Robinson
Good point. I guess my question wasn't entirely complete. The load method works just fine, but there are two other scenarios in which I may find myself. Scenario 1) I may need to load XML data (instead of HTML) and/or do a POST to a form. Scenario 2) For the above example, I'd like to fade out the current content, load the new content, then fade in the new content. However, as soon as I call the load() method, it instantaneously loads the new content rather than waiting for the previous content to completely fade out. My apologies for not being more clear.
Quintin, I somehow completely forgot that I could provide a callback on the .load() function. This solved scenario 2 as I can now chain my events. Thanks much!