Musterknabe February 2016

Printing out HTML via an Ajax-Request that is having errors stops further JS from working

I made a little experiment with my site. I have a site, that is empty. Then it makes an AJAX-Request to a php file where a random website is being gathered. The website is being gathered by using multiple random words, doing a search request with them to google and select a random result. Then with curl I follow that result and print out the contents, and set the in my ajax-request into my html. Then, normally the next page should be gathered.

However, the problem is, that after a website loaded, the website itself has JavaScript errors (probably because of paths or sth?)

How would I fix this? This is my code. As I said, it's just an experiment, so I'm not using Prototypes, classes, tests, comments or whatever, just plain stupid writing the code down

<section id="content">
</section>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.0.min.js"></script>

<script type="text/javascript">
    $(document).ready(function(){
        newSite();

        function newSite()
        {
            $.ajax({
                url: 'sites.php',
                dataType: 'html'
            }).done(function(data) {
                $('#content').html(data);
                $('#content').scrollTop(300);

                newSite();
            });
        }
    });
</script>

And this is where I get the site contents and print them out in the php file (I'm not showing the full code here, because there is stuff you don't need)

$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_URL, $final);

$content = curl_exec($ch);

echo $content;

$final is the URL of the google result. Any ideas?

Answers


Ilya February 2016

If you want to load a random website, you can't just insert the first page in your own document, the site often has other files to load with some relative path that won't work in your page (JS, images,...).

You can strip the JS content, but some sites will break without it, and even if they doesn't you could still be missing some parts.

Instead of sending the content, you could send the URL from your PHP code and use window.open to display the target website (and window.close to close the previous one).

For instance:

var windowRef = window.open(url, name);

Usually the window is opened in a new tab. If name is not empty, the window will reuse the tab opened with the same name instead of opening another.

Post Status

Asked in February 2016
Viewed 3,908 times
Voted 4
Answered 1 times

Search




Leave an answer