O'Reilly logo

Learning PHP, MySQL, JavaScript, and CSS, 2nd Edition by Robin Nixon

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Implementing Ajax via POST Requests

Type in and save the code in Example 17-2 as urlpost.html, but don’t load it into your browser yet.

Example 17-2. urlpost.html

<html><head><title>Ajax Example</title>
</head><body><center />
<h1>Loading a web page into a DIV</h1>
<div id='info'>This sentence will be replaced</div>
<script>

params = "url=oreilly.com"
request = new ajaxRequest()
request.open("POST", "urlpost.php", true)
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
request.setRequestHeader("Content-length", params.length)
request.setRequestHeader("Connection", "close")

request.onreadystatechange = function()
{
    if (this.readyState == 4)
    {
          if (this.status == 200)
          {
               if (this.responseText != null)
               {
                     document.getElementById('info').innerHTML =
                          this.responseText
               }
               else alert("Ajax error: No data received")
          }
          else alert( "Ajax error: " + this.statusText)
    }
}

request.send(params)

function ajaxRequest()
{
    try
    {
          var request = new XMLHttpRequest()
    }
    catch(e1)
    {
          try
          {
               request = new ActiveXObject("Msxml2.XMLHTTP")
          }
          catch(e2)
          {
               try
               {
                     request = new ActiveXObject("Microsoft.XMLHTTP")
               }
               catch(e3)
               {
                     request = false
               }
          }
    }
    return request
}
</script></body></html>

Let’s go through this document line by line, and look at what it does. The first three lines simply set up an HTML document and display a heading. The next line creates a <div> with the ID “info,” containing the text “This sentence will be replaced” by default. Later on, the text returned from the Ajax call will ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required