Fortune Cookies Code

AJAX


  //----------------------------------------------------------
  //  AJAX file for Fortunes, Mark Brautigam, 15 Nov 2019
  //  Cribbed from: The Web Language Project, May-June 2015
  //----------------------------------------------------------

  var xhr = false;

  function get (id) { return document.getElementById (id); }

  //--------------------------------------------------
  function getxhr ()
  //--------------------------------------------------
  {
    var xhr = false;
    if (window.XMLHttpRequest) {
      xhr = new XMLHttpRequest ();
    }
    else if (window.ActiveXObject) {
      try {
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
      }
      catch (e) {
      }
    }
    return (xhr);
  }

  //--------------------------------------------------
  function updatepage () 
  //--------------------------------------------------
  {
    // The master function. 
    //
    serviceurl = "./one.php";
    xhr = getxhr ();

    if (xhr) {
      xhr.onreadystatechange = updateProverb;
      xhr.open ("GET", serviceurl, true);
      xhr.send (null);
    }
  }

  //--------------------------------------------------
  function updateProverb () 
  //--------------------------------------------------
  {
    // This is the callback function that updates the
    // page content after Ajax returns the data.
    //
    if (xhr.readyState == 4) {
      if (xhr.status == 200) {
        if (xhr.responseText) {
          var f = xhr.responseText.replace("~", "<br />~");
          get ('fortune').innerHTML = f;
        }
      }
    }
  }