Ajax made Simple Part 5: Asynchronous Calls

In our last Ajax discussion, we discovered that it could take half a second for an Ajax call to complete (actually, due to network latency, it could even be a lot more than that.) How do we do Ajax calls and not make our app look slow?

Easy. We send the Ajax message off, then go do other stuff. When the response comes back, we respond to it. This is called Asynchronous operation.

We do this by adding the name of the function to be called on completion as the 4th parameter of our Ajax call:

req=Ajax("ajax.php/?myText=" + txtSend.value, "", "", done)

Continue reading “Ajax made Simple Part 5: Asynchronous Calls”

Ajax made Simple Part 4: How fast is it?

If your app is going to communicate with your server while it is running, you’ve probably wondered how much your app will slow down when it has to wait for the server.

In this blog post, we’re going to make a program to test this. We’ll construct a little program which sends data to the server as many times as it can. The server will record the information in a log file. Here is what our app will do:

  Do Until SysInfo(10) > limit
    req=Ajax("ajaxLog.php/?myText=" + Now)
    counter=counter+1
  Loop

Continue reading “Ajax made Simple Part 4: How fast is it?”

Using Custom Fonts

It turns out that it is quite easy to use custom fonts in an App Studio project. This is useful if you need a specialized font (not one of the official 13) or want to give your app a unique look. Here’s a step by step guide:

  1. Put the font file in your project directory. It should be in .ttf format.
  2. Drag it from there into your Project Explorer
  3. Add this line to extraheaders in Project CSS:
    @font-face {font-family: sansation; src: url('Sansation_Light.ttf');}
    

    4. Set the fontfamily of your controls to the name of your font face. In this case, it would be ‘sansation’.

    That’s it!

    (See the CustomFont sample in folder 2 to try it out.)

NS Basic/App Studio 2.0.1 Released!

We have just released NS Basic/App Studio 2.0.1. The new release has some minor new features and a number of bug fixes. The URL is the same as before.

Here is the list:

2.0.1

  1. IDE: Add new default screen sizes on New Project.
  2. IDE: Added landscape form factors to New Project.
  3. Code Window: Highlight ‘Step’ keyword.
  4. Code Window: Try and Catch no longer are flagged as syntax errors.
  5. Docs: Handbook and Language Reference updated.
  6. Language: TimeSerial() now carries result if values are large.
  7. Runtime: jQuery Mobile updated to version 1.0.1.
  8. Samples: AddToNumbers: add a reset button.
  9. Samples: jQM List: Show text of selected item.
  10. Samples: new jQM ListWithScrolling sample.
  11. Samples: new SQLSample3.
  12. Samples: New Transitions sample – work in progress.
  13. Samples: Open Sample screen is resizable – more improvements coming.
  14. Toolbox: Add setIndex() function to Select control.
  15. Toolbox: Fix default on ‘hidden’ property.
  16. ToolBox: jQM FooterBar on new form fixed.
  17. Toolbox: native menu is now the default.
  18. Translator: CDate(“hh:yy:ss”) fixed.
  19. Translator: Replace(a, “&”, “&”) fixed.
  20. Translator: Replace(a,”&”, “&”) fixed.
  21. Translator: text in comments no longer affects function defs.

Changing the splash screen at runtime

If you save an app to the home screen on an iOS device, you can display a nice splash screen when it launches. But what if the user switches to a different app, then returns to yours? It will have quit and needs to launch again.

You can save the current state to localStorage and write some code to go right back to where you were: but the splash screen will show again. You can suppress it by adding these lines to your restart code:

Dim headerChildren=document.getElementsByTagName("head")[0].children
Dim i=0
Do While i<UBound(headerChildren) And headerChildren[i].rel<>"apple-touch-startup-image"
  i=i+1
Loop
document.getElementsByTagName("head")[0].removeChild(headerChildren[i])

This code finds the splash screen in the header of the page and removes it.

Tip: Embedding NS Basic Apps in web pages

You might be wondering how I managed to embed an NS Basic app in the following post about jQuery Mobile.

Easy – here is the HTML:

<iframe src="http://www.nsbasic.com/KitchenSink" width=320 height=480>
</iframe>

You can now run the app as normal. Great way to do demos!

jQuery Mobile and App Studio

NS Basic/App Studio 2.0 introduces support for jQuery Mobile. This will let you develop more powerful and better looking apps. Here’s an actual App Studio program which shows off all the jQuery Mobile controls.


(go ahead – click on it!)

History
First, a bit of history. jQuery is a library of useful JavaScript functions that is being developed by John Resig and the jQuery Team. Backers of the the jQuery Project include Adobe, Mozilla, BlackBerry, Nokia, Microsoft and many more. Approximately 52% of the top web sites use jQuery.

Development of jQuery Mobile started in 2010: the first release was in November, 2011. This went far beyond what jQuery itself did: it actually contains a full set of visual elements, optimized for mobile devices. It was an instant success: jQuery Mobile is very widely used for Mobile Application development.

When we started development of NS Basic/App Studio, jQuery Mobile did not exist. We realized that having a library of controls was an essential part of the product. The best one at the time, and still a very good one today, was iWebKit. Distributed under the Apache license, we included it in our product. It is now called “Classic” in App Studio.

We started on the integration of jQuery Mobile some time before its actual release. As we worked with it, we realized that it added some very nice features to App Studio, so we accelerated development. Quite a bit of work was needed to make the IDE work well with both Classic and jQuery Mobile. The good news is that it came out great.

Features
There are a number of nice things to the jQuery Mobile controls.

  • Themes – you can customize the look and feel of the controls.
  • Grouped controls – Combine several similar controls into one large one.
  • Icons – a nice built in set of icons that can be used on many controls.
  • Additional Controls: FooterBar, FlipToggle, NavBar
  • More powerful controls: A number of controls have additional features.

Compatibility
Since Classic and jQuery Mobile have conflicting CSS, you cannot use both in the same project. When you create a project, you select which framework you are using. Only controls which apply to that framework will show in the ToolBox.

Some controls have two versions as a result: one for Classic and one for jQuery Mobile. These include Button, CheckBox, RadioButton, TextArea, TextBox and more.

Other controls work fine with both frameworks: Grid, Image, PictureBox, Audio, Video, HTMLview and more.

Conversion
The best way to convert a project is to open a new App Studio project with jQuery Mobile set as the framework. Create your forms again using the jQuery Mobile controls, giving them the same names as you had in Classic. You will need to reposition and resize many of the controls: the jQuery versions are often larger than the Classic version. Once the forms are done, copy and paste the code. Most of the code will come over without changes.

NS Basic/App Studio 2.0 Released!

We happy to announce that Version 2.0 is ready. Better yet, it is a free upgrade for all registered NS Basic/App Studio users!

The list of enhancements and fixes is extensive. Major new features include:

  • Support for jQuery Mobile Controls. These are more attractive and powerful than the Classic controls. Here is an actual NS Basic/App Studio App which uses them:

  • Desktop Apps. See Tech Note 10 to discover how your NS Basic/App Studio apps can run on Windows and Mac systems, and how you can sell them in the Chrome App Store. See Tech Note 10 for the details.
  • Improved dialogs for New Project and Open Sample Project.
  • Lots of smaller improvements and fixes. Check out the complete history.

The URL is the same as before. If you don’t have it anymore, be patient: we are sending an email to all registered users with the information.

The team here has been working hard on this new release. Great job, guys!

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.