Skip to content Skip to sidebar Skip to footer

Jquery: Load Body Of Page Into Variable

I'm using jQuery to load the result of a PHP script into a variable. The script is passed something that the user typed with a GET request. I want to take just what the script spit

Solution 1:

You are trying to access the dataloaded which might not be assigned due to the asynchronous nature of AJAX calls. The only safe place to access it is inside the success callback. Also you could use the .html() function to get the contents of the body tag:

functionloader() {
    var typed = $('#i').val(); //get what user typed in
    $.get('script.php', { i: typed }, function(loaded) {
        alert($(loaded).find('body').html());
    });
}

Also note that if the script.php only echoes 1!!2 without a <body> tag it won't work.

Solution 2:

Without knowing what console.log prints it is hard to say, but try these

alert($(dataloaded).find('body').html());

Or

alert($(dataloaded).find('body').text());

Solution 3:

I changed the page that I'm trying to fetch to XML. I'm using $.find to get each element of interest individually from the XML page, which suits this particular app well.

This problem has disappeared, as there is no longer a head section to ignore, and I'm just grabbing individual XML elements anyway.

Thanks for all your time and help!

Solution 4:

Use JSON type. I am not sure about whether your Jquery script correct or not but using JSON with a correct usage would solve problem. ie.:

functionloader() {
    var typed = $('#i').val(); //get what user typed in
    $.get("script.php", {i: typed}, function(loaded) {dataloaded = loaded;},"json");
    alert($(dataloaded).find('body'))
}

And POST variable from script.php after encoding JSON. Use Php's json_encode() function. You need to create variable as an array. For example:

<?php$title = 'Hello World';
$content = 'Get well soon Japan!';
$arr=array('title'=>$title,'content'=>$content);
echo json_encode($arr);
?>

And Jquery would be something like:

functionloader() {
var typed = $('#i').val(); //get what user typed in
$.get("script.php", {i: typed}, function(loaded) {var dataloaded = loaded.title+" "+loaded.content;},"json");
$("body").html(dataloaded);
}

You may need to use Jquery's parseJson() functions on some situations. Don't think you will need here.

Post a Comment for "Jquery: Load Body Of Page Into Variable"