Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 996
kneidels Avatar asked Jan 29 '14 11:01

kneidels


1 Answers

Try using jQuery.parseHTML();

Description: Parses a string into an array of DOM nodes.

$.ajax({
   url: 'http://www.somesite.com/',
   type: 'GET',
   success: function(res) {
      var data = $.parseHTML(res);  //<----try with $.parseHTML().
      $(data).find('div.content').each(function(){
          $('#here').append($(this).html());
     });

   }
 });

because ajax response is a string and that way you can't use .find() method to find a dom node. so first you have to parse the string as dom nodes which you recieved from server then you can use .find() to select your target element.

like image 112
Jai Avatar answered Oct 24 '22 13:10

Jai