Search code examples
ajaxahah

Load part of a webpage with AJAX - no JQuery


I know that there is a JQuery way of doing this but that's not what I need right now.

I have the following javascript that pulls a page content into a div, however I don't want the whole page, just the content of a DIV from that page:

function ahah(url, target) {
document.getElementById(target).innerHTML ='<img src="ajax-loader.gif"/>';
 if (window.XMLHttpRequest) {
 req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
 req = new ActiveXObject("Microsoft.XMLHTTP");
}
if (req != undefined) {
req.onreadystatechange = function() {ahahDone(url, target);};
req.open("GET", url, true);
req.send("");
}
}  

function ahahDone(url, target) {
  if (req.readyState == 4) { // only if req is "loaded"
    if (req.status == 200) { // only if "OK"
      document.getElementById(target).innerHTML = req.responseText;
    } else {
      document.getElementById(target).innerHTML=" Error:\n"+ req.status + "\n" +req.statusText;
    }
  }
}

function load(name, div) {
ahah(name,div);
return false;
}

And then I call it like this:

<a href="page.php" onclick="load('page.php','ajaxcontent');return false;" class="slide_more">LOAD</a>

Where should specify the selector I want to load from page.php?


Solution

  • Normally in AJAX application, in order to get the HTML Fragment the server is the one who is returning the fragment instead of having it selected on the client's side. For example, see this Simple Example on Section 4. Cool AJAX example. Code from the website is provided below for your reference:

    <?php
    function validate($name) {
      if($name == '') {
        return '';
      }
    
      if(strlen($name) < 3) {
        return "<span id=\"warn\">Username too short</span>\n";
      }
    
      switch($name) {
        case 'bob':
        case 'jim':
        case 'joe':
        case 'carol':
          return "<span id=\"warn\">Username already taken</span>\n";
      }
    
      return "<span id=\"notice\">Username ok!</span>\n";
    }
    
    echo validate(trim($_REQUEST['name']));
    ?>
    

    Notice that the PHP page is just returning an HTML Fragment containing the <span> only instead of the full html. This is one of the benefits of AJAX call that you don't need to return the full page thereby saving the bandwidth cost since the payload is smaller