Communicating with a Server - JS: Difference between revisions

From NSB App Studio
Jump to navigation Jump to search
JwellsNB (talk | contribs)
No edit summary
 
(5 intermediate revisions by 2 users not shown)
Line 1: Line 1:
== Purpose ==
== Purpose ==


The purpose of this tutorial is to demonstrate to send data from a form to a server, and then to receive information in return. This is useful for a variety of functions: verifying an username and password, updating information in a database on the server or getting information back from the server.
The purpose of this tutorial is to demonstrate sending data to a server, and then receiving information in return. This is useful for a variety of functions: verifying an username and password, updating information in a database on the server or requesting information from the server.


=== Description of the Program ===
=== Description of the Program ===
Line 7: Line 7:
The program to be developed will display a textarea. When the Send Data button is clicked, the information in the textarea is sent to the server. The server then replies and the program puts the information in the reply into the results area.
The program to be developed will display a textarea. When the Send Data button is clicked, the information in the textarea is sent to the server. The server then replies and the program puts the information in the reply into the results area.


This tutorial assumes the user has already worked through the earlier tutorials and is familiar with how to use the IDE, create controls and deploy complete apps.
This tutorial assumes the user has already worked through the earlier tutorials and is familiar with how to use the IDE, create controls and deploy complete apps. It also assumes the user has access to a server which can execute PHP scripts. (The AppStudio Server, does not support PHP.)


The program that this tutorial produces is available in the Samples that come with App Studio. It is called SendData.
The technique used is Ajax. For much more information on Ajax, read [[Ajax made Simple|Ajax made Simple]].
 
The program this tutorial produces is available in Samples Folder 7/Ajax and ReadFile, which comes with App Studio. It is called Ajax.


== Program Development ==
== Program Development ==
Line 17: Line 19:
Start App Studio from the Start menu.
Start App Studio from the Start menu.
At the initial screen select New Project dialog box, with the following settings:
At the initial screen select New Project dialog box, with the following settings:
Framework should be Classic.
* Form factor should be iPhone/iPad/Nexus
Form factor should be iPhone/iPad/Nexus
* Name is Ajax.nsx
Name is SendData.nsx
* Language is JavaScript
Language is BASIC
* Create a form that looks like this:
Create a form that looks like this:
 
[[File:TT07.01.JPG]]
 
The two TextAreas have their id set to txtSend and txtResponse. The Send Data button should have the id of btnSendData. All other properties are the default, with one exception:


On txtSend, set the 'name' property to myText. When we send the information on the form, only controls that have a name will have their values sent. All others will be ignored.
[[File:Ajax1.png]]


Tip: If you want to send data that does not appear on any control on the screen, add a Text control with inputType set to 'hidden'. Give it a name, of course, and it will be included.
The two TextAreas have their id set to txtSend and txtResponse. The Send Data button should have the id of btnSendData.


=== The Send Button ===
=== The Send Button ===
Line 35: Line 32:
Open the code window and add this code:
Open the code window and add this code:
<pre>
<pre>
var req;
btnSendData.onclick = function() {
btnSendData.onclick = function() {
  form1.submit();
    req = Ajax("https://www.nsbasic.com/i/Ajax/ajax.php/?myText=" + txtSend.value, done);
};
 
 
function done() {
    if (req.status == 200) { //success
        txtResponse.value = req.responseText;
    } else { //failure
        msg = "Error: Status = " + req.status;
        if (TypeName(req.statusText) == "string") {
            msg = msg + " " + req.statusText;
        }
        if (TypeName(req.err) == "string") {
            msg = msg + " " + req.error;
        }
        NSB.MsgBox(msg);
    }
}
}
</pre>
</pre>
The submit function collects the value of of all controls on the form which have names, and builds a string out of them, in the form of


    ?name1=value1&name2=value2&...
The Ajax() function sends the text to ajax.php, a program running on the server. When the Ajax call completes, the function 'done' is called.


The values are encoded, so embedded spaces and special characters are handled. The maximum size for the browsers that App Studio supports is quite high - people have tested sending as many as 80,000 characters. This string is commonly referred to a query string.
The text following the question mark in the Ajax function is called a Query String. The maximum size is quite high - people have tested sending as many as 80,000 characters.


=== URL to send to ===
=== The Server Side ===
 
In the Project Explorer, choose form1. Put "http://www.nsbasic.com/sendData.php" into the URL property.
 
[[File:TT07.02.JPG]]
 
This is the URL of the program on the server that is waiting for a message from your app.


=== Set the method ===
On the server side, ajax.php waits for messages from client apps. There are a number of other programming languages and techniques for doing this. Others include ASP and CGI.


The method is in the form properties. It can be set to GET or POST. Use POST if you are sending more than about 2K of data. If you are using POST, make sure the method of your first form is also set to POST, otherwise, the data will not return properly.
Let's create our own small PHP script. Use a text editor to create a small file in your project folder called ajax.php, with the following contents:
 
=== The Server Side ===
 
On the server side, a program called sendData.php waits for messages from client apps. There are a number of programming languages and techniques for doing this. PHP and ASP are popular server side scripting languages. CGI, which calls out to other languages, is also popular. In this case, we'll use a small PHP script:
<pre>
<pre>
<?php
<?php
  // Get the data from the client. Use $_POST if form method was POST.  
  // Get the data from the client.  
  $myText = $_GET['myText'];
  $myText = $_GET['myText'];
  // Send back the text, reversed
  // This next line really doesn't make sense if we are going to
  echo "Data received from Device (reversed): " . strrev($myText);  
// another page right away - it will get wiped out immediately.
  echo "<h2>Data sent from Device</h2><p>Your data: <b>" . $myText . "</b>\n";
 
// Now, redirect back to the client, adding some information for it.
header("HTTP/1.1 303 See Other");
header("Location: http://www.nsbasic.com/SendData/index.html?Status=thanks&OrderNumber=123213");
?>
?>
</pre>
</pre>
Data sent from Device


From the Finder, drag the file into the Project Explorer. It should look like this:


The first line of code in this script reads a value from the query string. We named the the controls of txtSend 'myText', so that value is put into a variable.
[[File:Ajax1a.png]]<br />


The second line echoes the contents of myText to the screen. The output of our server side script goes to our browser: any output from it is rendered on the screen as html.
The first line of code in this script reads a value from the query string. We named the value of txtSend 'myText' in the query string, so that value is put into a variable.


Something important to note here: when we went to sendData.php, our app went away. It's the php script that is currently running. The php script could do all kinds of processing: it could update a database, write out a text file, look up some information or do a complex calculation. All of this takes place on the host system.
The second line echoes the contents of myText back to our app, but reversed. It will be put into the req object which we DIMmed.
 
When the PHP script has done everything it needs to do, we want to go back to our app. It writes a couple of header lines out, which has the effect of chaining back to our app. We can use our old friend, the query string, to send results back. In this case, we're sending back two fields: Status and OrderNumber, with arbitrary values.
 
Note: this script is kind of silly. The first two statements display the query string that was sent, then the second two statements immediately wipes that out. However, if you remove the second two statements and run again, this can be used as a diagnostic to see if the correct data is going in.
 
sendData.php is saved on the server just as any other web page.


=== Back to our App ===
=== Back to our App ===


The final line of the server side script restarts our app. It loads as a fresh start to the app - the values of local variables are all lost and it starts again with blank controls in the forms. If you want the app to look just as it did when you submitted the form, you are responsible for saving the current state of your app into localStorage, then putting it all back on restart.
The final line of the server side script sends the results back to our app and calls the done() function. The results are in req.responseText.
 
We won't worry about that in this app. We do want to get the results that were passed back to us, however. App Studio has a function that allows you to do that: GetURLParameter.
 
The first subroutine that gets call when an app start is Main. Let's set up our Main() like this:
<pre>
function getURLParameter(name) {
    return decodeURI(
        (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
    );
}
 
function Main() {
  status = getURLParameter("Status");
  if(status=="" ) { return; }
  orderNumber = getURLParameter("OrderNumber");
  txtResponse.value="Status: " +  status;
  txtResponse.value=txtResponse.value + "\nOrderNumber: " + orderNumber;
}
</pre>
Main is run whenever the app is started - not just when we are called by our PHP script. If we are started normally, the query string will be blank. In our routine, we exit if that happens. But if there is a value, we put it into our txtResponse field.
 
That's it. We can now test it. Note that we will gave to test using a deployed version of the app. If we are running it locally in the browser, the final line in the PHP script will take us back to the wrong place. Fancier PHP scripting could probaby take care of that.
 
[[File:TT07.03.JPG]]
 
=== Notes ===


You can also create the query string in your own code and use that to call the server side, bypassing the Form Submit.
That's it. We can now test it. Note that we have to test using a deployed version of the app. For security reasons, only PHP scripts which are on the same server as your app can be called. (The AppStudio Server does not support PHP, so you will need to test this on your own server.)


  location="http://www.nsbasic.com/sendData.php/?myText=George"
[[File:Ajax2.png]]

Latest revision as of 08:53, 27 August 2015

Purpose

The purpose of this tutorial is to demonstrate sending data to a server, and then receiving information in return. This is useful for a variety of functions: verifying an username and password, updating information in a database on the server or requesting information from the server.

Description of the Program

The program to be developed will display a textarea. When the Send Data button is clicked, the information in the textarea is sent to the server. The server then replies and the program puts the information in the reply into the results area.

This tutorial assumes the user has already worked through the earlier tutorials and is familiar with how to use the IDE, create controls and deploy complete apps. It also assumes the user has access to a server which can execute PHP scripts. (The AppStudio Server, does not support PHP.)

The technique used is Ajax. For much more information on Ajax, read Ajax made Simple.

The program this tutorial produces is available in Samples Folder 7/Ajax and ReadFile, which comes with App Studio. It is called Ajax.

Program Development

Start by creating a new project

Start App Studio from the Start menu. At the initial screen select New Project dialog box, with the following settings:

  • Form factor should be iPhone/iPad/Nexus
  • Name is Ajax.nsx
  • Language is JavaScript
  • Create a form that looks like this:

The two TextAreas have their id set to txtSend and txtResponse. The Send Data button should have the id of btnSendData.

The Send Button

Open the code window and add this code:

var req;

btnSendData.onclick = function() {
    req = Ajax("https://www.nsbasic.com/i/Ajax/ajax.php/?myText=" + txtSend.value, done);
};


function done() {
    if (req.status == 200) { //success
        txtResponse.value = req.responseText;
    } else { //failure
        msg = "Error: Status = " + req.status;
        if (TypeName(req.statusText) == "string") {
            msg = msg + " " + req.statusText;
        }
        if (TypeName(req.err) == "string") {
            msg = msg + " " + req.error;
        }
        NSB.MsgBox(msg);
    }
}

The Ajax() function sends the text to ajax.php, a program running on the server. When the Ajax call completes, the function 'done' is called.

The text following the question mark in the Ajax function is called a Query String. The maximum size is quite high - people have tested sending as many as 80,000 characters.

The Server Side

On the server side, ajax.php waits for messages from client apps. There are a number of other programming languages and techniques for doing this. Others include ASP and CGI.

Let's create our own small PHP script. Use a text editor to create a small file in your project folder called ajax.php, with the following contents:

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

From the Finder, drag the file into the Project Explorer. It should look like this:


The first line of code in this script reads a value from the query string. We named the value of txtSend 'myText' in the query string, so that value is put into a variable.

The second line echoes the contents of myText back to our app, but reversed. It will be put into the req object which we DIMmed.

Back to our App

The final line of the server side script sends the results back to our app and calls the done() function. The results are in req.responseText.

That's it. We can now test it. Note that we have to test using a deployed version of the app. For security reasons, only PHP scripts which are on the same server as your app can be called. (The AppStudio Server does not support PHP, so you will need to test this on your own server.)