Using jQuery To Load Content Onto A Page Without An iFrame

8th February 2011

iFrames can be a convinent way of loading content from one domain onto another, but they do have their limitations. For example, it usually isn't possible to style the contents of the iFrame and you are therefore left at the mercy of a third party site. They also look pretty shonky if the third party site does down for whatever reason. Displaying large "page not found" statements on your page is quite unsightly.

There is a function in jQuery called load() that will use an AJAX request to load content from page onto another, and can even extract specific areas of the page and return only those parts. I thought I would run through some examples and then show how it is possible to display content from another domain on a page. Lets say we have a PHP file on the server that generates a random number, this would be the following very simple code.

  1. <?php
  2. echo rand();

This can be loaded into a div on a page of HTML using a single call in jQuery that utilises the load() function. This will just grab the text from the random_number.php file (the contents of which is in the above example) and put the result in the div with the id of test. Here is a page of HTML that does just that. Note that if you want to run this you'll need to put it on a server to enable the AJAX calls, otherwise it won't do anything.

  1. <!DOCTYPE HTML>
  2. <html>
  3. <head>
  4. <title>Loader</title>
  5. <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
  6. <script type="text/javascript">
  7. $(document).ready(function(){
  8. $('#test').load('/random_number.php', '', function(response, status, xhr) {
  9. if (status == 'error') {
  10. var msg = "Sorry but there was an error: ";
  11. $(".content").html(msg + xhr.status + " " + xhr.statusText);
  12. }
  13. });
  14. });
  15. </script>
  16. </head>
  17. <body>
  18. <div id="test"></div>
  19. </body>
  20. </html>

Taking this a step further it is possible to get part of the text on a page by passing an extra bit of text to the load() function. The first parameter of the function is the location of the resource, but it is also possible to add a CSS identifier to the resource that will bring back only the block you were looking for. Take the following little HTML snippet, which would be loaded into a file called html_snippet.html on the server.

<div>Some <strong class="aclass">content</strong></div>

It is possible to grab the contents of just the "strong" element by adding a space and then the CSS selector you need to extract that bit of content, in this case it is ".aclass". This means we only need to change the jQuery example above a little bit to get this working.

$('#test').load('/html_snippet.html .aclass', '', function(response, status, xhr) {

The thing that separates iFrames from AJAX calls is that an iFrames can point anywhere, whereas an AJAX call MUST be on the same domain as the original file. This is a built in security feature of JavaScript and cannot be circumvented. This means we need to add a quick workaround to bypass this security mechanism. To take a realworld example I thought it might be a good idea to try and download some Google search results and print them onto the page. First we need to create the PHP code to download the Google search results, which is actually quite easy. Here we are searching for the term "wibble".

  1. <?php
  2. $url = 'http://www.google.com/search?hl=en&q=';
  3. $output = file_get_contents($url . urlencode('wibble'));
  4. echo $output;

Call this file something like searchgoogle.php and pop it on your server. We now need to update the jQuery so that we only display the search results and not all of the other stuff on the Google search results page that isn't needed. We do this by supplying the CSS selector "#res". Here is the updated line of code that you need to change. Once this is done the page automatically loads the test div with the search results for the term "wibble".

$('#test').load('/searchgoogle.php #res', '', function(response, status, xhr) {

Just loading the results onto the page when the DOM has loaded isn't quite the best way to do things in every situation, it is also nice to add a "Loading" graphic and a swishy effect when the content is changed to make things nice and pretty. This is all controlled via a link element at the top of the page. This requires a little bit more jQuery code to be added so I have printed it out in full again with the additional actions added. We are essentially adding a click event to the link element so that it will run the load() function. There are some other action and animation functions here that will cause the content to show and hide at different times, but the basic functionality is still there. Now, when a user clicks on the "Load" link they are presented with the search results for the term "wibble".

  1. <!DOCTYPE HTML>
  2. <html>
  3. <head>
  4. <title>Loader</title>
  5. <style type="text/css">
  6. div#container {
  7. width:500px;
  8. height:500px;
  9. overflow:auto;
  10. }
  11. </style>
  12. <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
  13. <script type="text/javascript">
  14. var externalpagepart = '#res';
  15. var loadinggif = '/loading.gif';
  16.  
  17. $(document).ready(function(){
  18. // set up the click event
  19. $('a.loader').live('click', function() {
  20. var toLoad = '/searchgoogle.php ' + externalpagepart;
  21. $('.content').slideUp('slow', loadContent);
  22. $('#load').remove();
  23. $('#waiting').append('<div id="load"><img src="' + loadinggif + '" alt="Loading" /></div>');
  24. $('#load').fadeIn('normal');
  25. function loadContent() {
  26. $('.content').load(toLoad, '', function(response, status, xhr) {
  27. if (status == 'error') {
  28. var msg = "Sorry but there was an error: ";
  29. $(".content").html(msg + xhr.status + " " + xhr.statusText);
  30. }
  31. }).slideDown('slow', hideLoader());
  32. }
  33. function hideLoader() {
  34. $('#load').fadeOut('normal');
  35. }
  36. return false;
  37. });
  38. });
  39. </script>
  40. </head>
  41. <body>
  42. <p><a class="loader" href="javascript: null(0);">Load</a></p>
  43. <div id="container">
  44. <p id="waiting"></p>
  45. <div class="content"></div>
  46. </div>
  47. </body>
  48. </html>

Finally, I thought it might be a good idea to integrate a input box into the page so that the user can control the search term they want to send over to Google. The first task is to do is to allow the passing of a post variable called 'string' to the Google search URL. This is wrapped in a call to urlencode() to stop any errors occurring when users type in spaces and other things. We will come onto how to send this data in the next snippet.

  1. <?php
  2. $url = 'http://www.google.com/search?hl=en&q=';
  3. $postVariable = 'string';
  4.  
  5. if (isset($_POST['string'])) {
  6. $output = file_get_contents($url . urlencode($_POST[$postVariable]));
  7. $output = preg_replace('#<script.*</script>#ismU', '', $output);
  8. $output = preg_replace('#<style.*</style>#ismU', '', $output);
  9. echo $output;
  10. }

To pass post values through the AJAX call we need to use the second parameter in the load() function. This is a JSON encoded collection of variables that we might want to use. The property of the JSON object is the key in the $_POST array on the PHP side. To send the value "wibble" to the previous PHP code snippet we use the following:

$('.content').load(toLoad, {'string': 'wibble'}, function(response, status, xhr) {

We can now tie this all together and create a form that will allow users to search Google without actually leaving the current page. To use this just type a value into the input box and click on the link. This will trigget the action and run the load() method. This can probably be tied into a form properly, but this is enough to demonstrate how things would work.

  1. <!DOCTYPE HTML>
  2. <html>
  3. <head>
  4. <title>Loader</title>
  5. <style type="text/css">
  6. div#container {
  7. width:500px;
  8. height:500px;
  9. overflow:auto;
  10. }
  11. </style>
  12. <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
  13. <script type="text/javascript">
  14. var externalpagepart = '#res';
  15. var loadinggif = '/loading.gif';
  16.  
  17. $(document).ready(function(){
  18. // set up the click event
  19. $('a.loader').live('click', function() {
  20. var toLoad = '/searchgoogle.php ' + externalpagepart;
  21. $('.content').slideUp('slow', loadContent);
  22. $('#load').remove();
  23. $('#waiting').append('<div id="load"><img src="' + loadinggif + '" alt="Loading" /></div>');
  24. $('#load').fadeIn('normal');
  25. function loadContent() {
  26. var searchterm = $('#searchterm').val();
  27. $('.content').load(toLoad, {'string': searchterm}, function(response, status, xhr) {
  28. if (status == 'error') {
  29. var msg = "Sorry but there was an error: ";
  30. $(".content").html(msg + xhr.status + " " + xhr.statusText);
  31. }
  32. }).slideDown('slow', hideLoader());
  33. }
  34. function hideLoader() {
  35. $('#load').fadeOut('normal');
  36. }
  37. return false;
  38. });
  39. });
  40. </script>
  41. </head>
  42. <body>
  43. <input type="text" name="searchterm" id="searchterm" value="wibble" />
  44. <p><a class="loader" href="javascript: null(0);">Load</a></p>
  45. <div id="container">
  46. <p id="waiting"></p>
  47. <div class="content"></div>
  48. </div>
  49. </body>
  50. </html>

One final thing that might be a good idea to do is strip out any style and script tags within the content of the page, this can be done through two calls to preg_replace(). This is probably a prudent thing to do anyway as you can end up with unwanted CSS and potentially dangerous JavaScript appearing on your site.

  1. $url = 'http://www.google.com/search?hl=en&q=';
  2. $postVariable = 'string';
  3.  
  4. if (isset($_POST['string'])) {
  5. $output = file_get_contents($url . urlencode($_POST[$postVariable]));
  6. $output = preg_replace('#<script.*</script>#ismU', '', $output);
  7. $output = preg_replace('#<style.*</style>#ismU', '', $output);
  8. echo $output;
  9. }

This was al quite easy to set up and shows the power that a simple load() call can have, especially within a CMS application. Feel free to use these examples on your own sites but drop me a message to let me know as I would quite like to see other people's implementation of this method.

Comments

Permalink
Here you send variables to google as GET variables. What if I wanted to send as POST Variables.

Raj (Tue, 01/31/2017 - 11:36)

Permalink
As much as I want to get rid of the bloat of JQuery, the concept of maintaining more SLoC within the project is actually a worse off decision IMO.

Anonymous (Thu, 03/09/2017 - 07:44)

Permalink
This jQuery Load tutorial is very well explained. I just have one question which is - how to use jQuery Load to make cross domain calls. Please help thank you.

Yogi (Tue, 05/09/2017 - 04:21)

Permalink
Thank you so much, I believe this has me on the verge of solving a 2 week long issue! I just have one more feature different than your example, and that would be a submit form and button. Is there a way to get this script to fire on submit? My current form is setup as:
  1. <form id="index2" action="index2.php" method="GET" enctype="multipart/form-data" target="test"></form>
  2. <input type="text" name="sb" id="searchBox" placeholder="" value="" maxlength="20" autocomplete="off" onmousedown="" onblur="" /><input type="button" id="searchBtn" value="Submit" /><div> id="test"></div>
Thank you for any assistance you can provide!

Christopher Landolfi (Mon, 05/15/2017 - 23:49)

Add new comment

The content of this field is kept private and will not be shown publicly.