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.)

Ajax made Simple Part 2: POST.

You may have read the recent blog entry called Ajax made Simple. Today we’re going to extend that a bit and talk about using the POST method.

The last blog post discussed the simplest Ajax call, which sends data to the server by adding it to the end of the URL, a method called, rather misleadingly, GET. But what if we want to send more data? GET has a limit, some say, of around 2000 characters. For more than that, we’ll use the also badly named POST method. POST has an upload limit on most servers of 8 megabytes. If you need more, server settings can be adjusted.

Let’s look at some code. You’ll see it looks very much like our last post:

Function btnAjax_onclick()
  req=Ajax("ajaxPost.php","POST",txtSend.value)
  If req.status=200 Then 'success
    htmResponse.innerHTML=req.responseText
  Else 'failure
    htmResponse.innerHTML="Error: " & req.err
  End If
End Function

The difference is a couple of extra parameters. We add “POST” and the data we want to send as a separate parameter. Before we talk about what is going to happen at the server end, let’s see what the app looks like:

OK, here is the PHP code on the server which we are calling:

<?php
 // uncomment the next line to see runtime error messages from this script
 // ini_set('display_errors','1');
 
 // Get the data from the client.
 $myText = file_get_contents('php://input');
 // Send back the text, reversed
 echo "Data received from Device (reversed):<br>" . strrev($myText); 
 
 //write the data out to a file on the server
 //make sure permissions are all OK!
 $myFile = "AjaxPost/ajaxPost.txt";
 echo "<p>Writing data to " . getcwd() . $myFile;
 $f = fopen($myFile'w'or die("can't open file");
 fwrite($f$myText);
 fclose($f);

?>

The file_get_contents(‘php://input’) call gets the data, exactly as it was sent. We’ll do two things with it: echo it back reversed and we will write it to a file on the server. The first part is easy: anything in an echo statement is sent back to our app:

echo "Data received from Device (reversed):
" . strrev($myText);

The second part involves a bit more PHP, but is straightforward. It writes the data was received to a file.

 $myFile = "AjaxPost/ajaxPost.txt";
 echo "<p>Writing data to " . getcwd() . $myFile;
 $f = fopen($myFile, 'w') or die("can't open file");
 fwrite($f, $myText);
 fclose($f);

What would you use this feature for?

  • Upload a JSON copy of your database.
  • Upload some pictures in Base64 format.
  • Create a .htm file which can be accessed as a web page.
  • Lots more ideas!

A tip on debugging PHP scripts
Since PHP scripts run on the server and not on your screen, you don’t get to see the error messages. This can make debugging difficult. If you put this statement at the top of your PHP script, the error messages will be echoed to your app:

ini_set('display_errors','1');

The error messages come back as HTML formatted text. The best way to look at them is to assign them to the innerText property of an HTMLview control.

NS Basic/App Studio 1.4.2 released!

We happy to announce that Version 1.4.2 is ready!

It features a new Ajax() function, a new collections datatype and a bunch of fixes and minor enhancements.

The URL is the same as before.

1.4.2

  1. Language: Added new Ajax() function.
  2. Language: Support added for Collections.
  3. Samples: Added AjaxPost sample: reverse a string and save as file on server.
  4. Samples: Add Collections sample.
  5. Samples: New C# WebSockets sample. (Thanks to Christian Probst!)
  6. Controls: Added false to Hidden property.
  7. Controls: Font styling added to DateTime controls.
  8. Controls: Allow width to be changed on Checkbox, RadioButton.
  9. Docs: Handbook and Language Reference updated.
  10. Translator: BTNew changing to BTnew fixed.
  11. Translator: If a then MsgBox 0 fixed.
  12. Translator: MsgBox 0 no longer shows blank.
  13. Translator: Case of ‘Case’ no longer changed to ‘case’
  14. Translator: MsgBox false no longer shows blank.
  15. Translator: Object.Add and Object Delete added: collections!
  16. Translator: UBound(object) returns items in object.
  17. Translator: Comments with embedded colons fixed.

Documentation Changes for Version 1.4.2

  1. The new Ajax function is a more powerful version of ReadFile(). It can directly replace ReadFile, plus do POST. POST lets you send larger files to the server – the usual limit is 8 megs, but this can be increased. Calling arguments are Ajax(URL, method, data), which URL is the name of the file or server side script, method is GET or POST, and data is a string containing the data you wish to transfer. Only the URL argument is required: if method is not supplied, it defaults to GET.

  2. Collections: A collection is like an array, except the members are accessed by name instead of number.

NS Basic/App Studio 1.4.1 Released!

We happy to announce that Version 1.4.1 is ready!

It features a much easier to use and more powerful RadioButton, ToolBox search, multiple forms at one time and better AJAX capabilities. There is also a long list of smaller enhancements and fixes.

The URL is the same as before.

Here’s the complete list of what has been changed:

1.4.1

  1. Controls: Add new RadioButton control. Replaces OptionButton.
  2. Language: ReadFile() can now specify method. See Language Reference.
  3. Code Window: Auto Indent/Outdent improved for Select and Do Loop.
  4. Controls: Form has new properties: left, top and openMode.
  5. Controls: Button: fix iOS padding problem. Now matches Design Screen.
  6. Controls: Button: Orange flash on Android should finally be gone.
  7. Controls: Grid – cellstyle now applies to all cells.
  8. Controls: TextBox: fix iOS padding problem. Now matches Design Screen.
  9. Docs: Handbook and Language Reference updated.
  10. IDE: Typo fixed in save message.
  11. Language: NSBVersion fixed.
  12. Runtime: Improve logic to hide URL bar on iOS.
  13. Runtime: NSB.InputBox bombed when used with Sencha Touch.
  14. Runtime: NSB.InputBox no longer bounces in Android.
  15. Runtime: Multiple forms can be opened side by side.
  16. Samples: Added new Ajax sample.
  17. Samples: Added new RadioButton sample.
  18. Samples: Added new SideBySideFormsTablet sample.
  19. ToolBox: Search feature added.

Documentation Changes for Version 1.4.1

  1. TextBox and Input box: These controls had a problem. On iOS devices, they were showing 10 pixels wider than in the Design Screen and on Android devices. The problem was fixed by setting padding:0px in the internal code which creates them. This change will affect the appearance of your programs on iOS devices. It should actually make most of them look better, especially short textboxes and buttons. To go back to the old appearance, you will need to add “padding:10px;” to the style property of the control.

  2. RadioButton: This new control is much improved over the old OptionButton control. While OptionButton will continue to work, its use is discouraged. The new one is much prettier. You can set up all the options in one control, instead of needing a control for each one. It also has a much simpler interface. See the Language Reference for the details.

  3. Forms no longer have to be full screen and you can have more than one open at a time. This allows techniques like side by side forms on tablets (see sample) and pop up dialog boxes.

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
    txtResponse.value=req.responseText
  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.

<?php
 // 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.

iWebInspector: Debugging on iOS devices

An amazing new product crossed my desk today. iWebInspector lets you open up a debugging session on an NS Basic/App Studio app that is running in the iOS iPhone or iPad Simulator.

It was developed by Max Firtman (who has come up with other innovations that we at NS Basic have used), based on a discovery by Nathan de Vries on how to enable the Remote Web Inspector on iOS 5.

Since the iOS Simulator only runs on Mac OS, this tool requires a Mac. You’ll also need to download Apple’s XCode, which includes the iOS 5 SDK and the Simulator. It’s a 1.6 gig download, but easy to install once it is there. You won’t have to learn XCode or even how to start the Simulator: iWebInspector will take care of that for you.

Here’s how iWebInspector looks when you start it: (this is Beta 0.9 – expect it to get better looking quickly):

If you click on Open iOS Simulator, the Simulator will start automatically. If it is purely a web app, open it in Safari then choose “Load from Safari”. If it has been saved to the Home Screen, start it and choose “Load from webapp”. PhoneGap apps can even be debugged: enter the App name and “Load”.

This tool will be especially useful for debugging apps which can only be tested on a device.

NS Basic/App Studio 1.4.0 released!

Features great new ToolBox!

We’ve completely redone the toolbox. With its folders, it is able to accomodate many more controls than before. Being able to drag and drop onto the Design Screen makes it easier and more natural to use. All new icons make it look great. To top it off, we’ve added new Slider, Date and Time controls.

The URL is the same as before.

Here’s the complete list of what has been changed:

  1. ToolBox: Completely replaced – vastly improved!
  2. ToolBox: All new icons!
  3. ToolBox: Drag and drop controls to Design Screen.
  4. Controls: New Data, DateTime, Month and Time controls. (iOS5)
  5. Controls: New Slider control (iOS5)
  6. ToolBox: Double click adds control to Design Screen.
  7. Code Window: Indentation problem fixed with ‘If’ after a blank line.
  8. Code Window: Recompile of source code improved.
  9. Code Window: Syntax checking is back.
  10. Code Window: Very long statements are handled much better.
  11. Controls: PayPal – New addField() function added.
  12. Controls: PayPal – Subscribe and Unsubscribe added.
  13. Controls: CommandButton is now called Button.
  14. Deploy: Build status screen appearance improved.
  15. Deploy: Unicode characters allowed in configxml.
  16. Docs: Handbook and Language Reference updated.
  17. Docs: Tutorials 1-4 overhauled.
  18. Design Screen: Right click to add control do so at cursor position.
  19. IDE: Added “Reset IDE Panels” to View Menu.
  20. IDE: Control descriptions now appear in the Hints area.
  21. IDE: Format of .nsx file improved for more readability.
  22. IDE: View menu fixed.
  23. Installation: Unicode characters allowed in install path.
  24. Property Box: Spaces in control ID no longer allowed.
  25. Runtime: NSB.InputBox input field sized properly on Safari.
  26. Runtime: NSB.InputBox no longer bounces on Android
  27. Samples: New Slider sample (iOS5)
  28. Samples: DateTime updated to use new controls.
  29. Translator: Integer Divide operator now works (“”)
  30. Translator: VBCritical now parses properly.
  31. Translator: Multiple statements per line using : fixed.

Documentation Changes for Version 1.4.0

  1. The ToolBox has been overhauled. It looks a lot nicer, can scroll (so users with small screens can see all the controls again) and has some new features. To add controls to your project, either drag & drop them or double click.

Building Native Apps

The enhancements in NS Basic/App Studio 1.3.1 make building native apps much easier. First, a bit of background: NS Basic/App Studio is designed to make Web Apps. These apps take advantage of the power of current browsers and HTML5 to make native appearing apps. With the speed improvements of JavaScript in recent years, they have excellent performance. Web Apps can also be compiled into Native Apps, which have their own advantages and disadvantages.

Under the Run menu, there is an option called “Build Native App”. Once you have tested your project, use this option to submit your app to the PhoneGap Build server. The compilers and SDKs to build native apps are large and complex: using a server to perform these operations saves you a lot of grief installing and maintaing them.

Once submitted, you can check the status of the build using “Get Native Build Status” under the Run menu.

Completed builds have their download links listed.

Some useful notes:

  • Each user of PhoneGap Build should have their own account. For demo purposes, NS Basic has a default account, but your files will not be secure there. It’s easy to sign up for your own. Once you have it, enter the information into “Deploy Options” under the Tools menu.
  • The program name and your icon will be taken from your project properties. Other PhoneGap options are set up in the configxml property in your project’s properties. Read more about using config.xml here.
  • iOS will not build until Apple’s signing information has been entered.
  • PhoneGap Build is in beta right now. PhoneGap may start charging for this service at a some point.

NS Basic/App Studio 1.3.1 Released!

NS Basic/App Studio 1.3.1 is ready to download. You can download it from the same URL as before.

Here is what is new and changed:

1.3.1

  1. Deploy: config.xml file now created automatically. See below.
  2. Controls: Adsense – id property added.
  3. Controls: Textarea now has single finger scrolling (iOS 5)
  4. Deploy: PhoneGap Build 404 errors now handled gracefully.
  5. Globals: AppBuildStamp, AppLegalCopyright, AppVersion, NSBVersion added.
  6. IDE: New control: range slider. Part of TextBox. (iOS 5)
  7. IDE: New project property: configxml
  8. IDE: New project property: Version
  9. IDE: phonegap property removed. See below.
  10. Runtime: Buttons no longer have orange flash on Android
  11. TechNotes: New Tech Note 8: Web Apps Compared to PhoneGap Apps

Documentation Changes for Version 1.3.1

  1. Config.xml is a file that PhoneGap uses for its settings: icon, program name, version, features used, etc. Until now, you had to create this file yourself. Now, it is generated automatically using the information already in your project. To customize it for your own needs, edit configxml in Project Properties. Full documentation on config.xml is here.

  2. The phonegap property has been removed from Project Properties. It conflicted with PhoneGap Build and was rarely used. To accomplish the same thing, add <script src="phonegap.js"></script> to the extraheaders property.

  3. Range


    The Range option in the TextBox control allows you to have an input slider. (iOS 5).