I have spent ages at this and dont understand why it is not working. I am using ajax to send a post to php curl which brings a url in it then goes back to ajax. When I send an alert all the html of that page is displayed in the alert. Now I want to use jquery to find each element i.e. body, h1, title and output the contents but when I do this it doesnt work for the body or title. Why is that?
Here is my jquery
$.ajax({
type: "POST",
url: "senddom.php",
data: {"dataString" : dataString },
success: function(response) {
$('body').append("<p> contents of title:" + $(this).find('title').html() + "</p>");
$('body').append("<p> contents of all: " + $(this).find('body').html() + "</p>");
$(response).find('h1').each(function() {
$('body').append("<p> contents of H1: " + $(this).text() + "</p>");
});
this is my php
<?php
$site= $_POST['dataString']; // get data
function curl_get($site){
$useragent = 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.0.3705; .NET CLR 1.1.4322; Media Center PC 4.0)';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$site);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,5);
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
$data=curl_exec($ch);
curl_close($ch);
return $data;
}
function getdom($site){
$html = curl_get($site);
$xml = new DOMDocument();
@$xml->loadHTML($html);
echo($html);
}
echo getdom($site);
?>
inside your success block:
$(this)->$(response)Follow Up: Full text HTML vs Fragments
While this may seem to take care of the immediate problem, it is dependent on whether or not your response is the full body HTML.
In this case, it seems as though
responseis the full text HTML.The jQuery parseHTML method does not deal with full text HTML, and unfortunately
responsewon’t be parsed properly. Fore more info see: https://github.com/jquery/jquery/blob/master/src/core.jsIn the case where you are looking to parse full text HTML, one approach would be to use the DOMParser API. It is worth noting that the support for parsing
"text/html"is currently lacking; only available in Firefox. An alternative isdocument.implementationwhich has support in all but IE<9.That said, an example in the case where you want to use
DOMParser—An example in the where you want to use
documentation.implementation—For more information, I’ll defer to a nice jQuery plugin (that deals with the x-browser support) that I found on github: jquery.parsehtml.js.