kneidels kneidels - 1 month ago 8
Ajax Question

Getting specific element from external site using jQuery / ajax

I am using jQuery and this plugin to pull content from an external site.

It works great using the following code:

$.ajax({
url: 'http://www.somesite.com/',
type: 'GET',
success: function(res) {
$("#here").html(res.responseText);
}
});


But what I would really like to do, is only pull a section (div) from the target site, and I understand this is only possible when using the
load()
method, not
GET
.

I then found this code , but when I tried to build it into the code, it didn't seem to work, as such:

$.ajax({
url: 'http://www.somesite.com/',
type: 'GET',
success: function(res) {
$(res).find('div.content').each(function(){
$('#here').append($(this).html());
});

}
});


Looking into the request on Firebug, the request does seem successful, but the code can't seem to find the following tag:
<div class="content row">
on the target site.

Do I need to make sure the target element has an #ID, instead of a class?

Thanks!

Rui Rui
Answer

In your original success callback you're fetching your html contents from responseText, you should do the same in the second case:

   success: function(res) {
      $(res.responseText).find('div.content').each(function(){
          $('#here').append($(this).html());
     });

Using class="content" or id should work. However, you should be aware that the code above adds all div's that have class content to your id="here" div, which might not be what you want. If you want just the contents of a specific element, use its id instead.