Ajax made Simple Part 1

Most developers have heard of Ajax by now. Unless you’ve worked with it, you probably think it’s another complicated form of alphabet soup. It actually turns out to be quite easy to use from NS Basic/App Studio.

First, let’s explain what it is (and isn’t). It stands for Asynchronous JavaScript And XML. The good news is that there’s no need to be asynchronous or to use XML – and that NS Basic takes care of the JavaScript.

Ajax makes it easy to exchange data with your server. Think of it as a function you can call that is running on another system. You can pass it parameters and it can return values. Since it’s running on your server, it can do things that you cannot do on your device. It can access files and databases on the server, or get data from other web sites without worrying about Same Origin Policies.

Let’s look at some code. We will have our NS Basic app send the server a string, which the server will return reversed. Here is what the app looks like:

The only code in this app is the “Reverse” button. The Ajaxfunction sends the contents of the top textarea to a PHP script that is running on the server. If it returns successfully, we display what came back. Otherwise, we show the error:

Function btnAjax_onclick()
  req=Ajax("ajax.php/?myText=" & txtSend.value)
  If req.status=200 Then 'success
  Else 'failure
    txtResponse.value="Error: " & req.err.message
  End If
End Function

The PHP script is even easier. It gets the input that is named myText, reverses it, and uses the echo statement to send it back.

 // Get the data from the client. 
 $myText = $_GET['myText'];
 // Send back the text, reversed
 echo "Data received from Device (reversed): " . strrev($myText); 

Here is the result:

A few notes:

  • The php script needs to be on the same folder on the server as the NS Basic app.
  • Ajax is based on XMLHttpPost.
  • A handy way to return data from your PHP script is in JSON format. PHP even has a handy json_encode() function.