Ajax made Simple Part 3: Data from another site

One of the basic security features of the modern web is the Same Origin Policy. It states that a web app cannot pull up just any data from another site. This becomes a problem if you need data on someone else’s site.

Fortunately, they left an easy workaround. While a web app isn’t allowed to access the files on another site, a PHP script is. We’ll get our PHP script to do the dirty work for us and return the results to our app. The technique we will use is often called scraping.

Time to look at some code again. Here’s the App Studio part that calls the PHP script. It looks very much like the code in Ajax Made Simple. The main difference is that we’re calling a different PHP script.

Function btnGetFile_onclick()
  req=Ajax("ajaxGetURL.php/?urlToGet=" & txtURL.value)
  If req.status=200 Then 'success
    htmResponse.innerHTML=req.responseText
  Else 'failure
    htmResponse.innerHTML=req.err
  End If
  htmResponse.refresh()
End Function

Before we talk about what is going to happen at the server end, let’s see what the app looks like:

And here is what the PHP script looks like:

<?php
echo file_get_contents($_GET['urlToGet']); 
?>

Let’s take apart this one line:

  • $_GET(‘urlToGet’) gets the parameter string that was attached to the URL in our App Studio code.
  • _file_get_contents get the contents of the file, in this case, the URL that was passed.
  • echo sends the result back to our App Studio program.

Pretty simple, isn’t it?

(In this example, we’re grabbing the robots.txt file from Microsoft’s site, just to show we can get files from anywhere. Nearly all sites have a robots.txt file: it is used to guide search engines.)