Monday, November 21, 2016

Notes to W11 Forms

The task is, basically, in the combination of my post "Simple PHP form explained" with Demo File from week 11.
In the first post, cited above,  I showed how in the processing program defined in the action parameter of the form you should use $_POST[...] for getting access to the values in the form.
So you just need to declare some PHP variables and get those values into them, like:
$name = $_POST["name"];
....
If in the form you had a field name as "name".

After that you use the part from from the Demo File (only one INSERT statement) but instead of the hard coded values  - use the variables from shown above with values from the form

...

 mysql_query("INSERT INTO people (FirstName, LastName, Age) 
 VALUES ('$name', and other similar variables here)");


The reading program is actually in the same Demo File after the comment:

 //Read the result

 $result = mysql_query("select * from people");

 if (!$result)
   {
   die('Could not read: ' . mysql_error());
   }
   echo "got records!";

 echo "Passed!";

 while($row = mysql_fetch_array($result))
   {
   echo $row['FirstName'] . " " . $row['LastName'];

   }

 mysql_close($con);

   echo "Finished";
 ?>

You just need to use this code in a separate program where you first select the database (all my code from the Demo File up to the couple of INSERT statements) and then skipping INSERT statements in the Demo File use the code after    "//Read the result " comment.

And that's it!


Make this lab work (who couldn't ) to get the grade that you deserve, resubmit the forum and the assignment A11.2 and email me about the completion. Your grade might be somewhat increased but, what is more important, you will be able to get a better course grade. Otherwise, even if all other labs work - it cannot be more than a B, since this lab uses cumulative knowledge from the previous weeks on PHP and MySQL.

Alternatively, you can use the code from w3schools where the same form file was calling itself for processing (I described it in my another post), but still will need to use the variables taking info from $_POST[...] method. But I think what I showed above is simpler (but for real life code remember that for simplicity in the shown code we didn't use protection against PHP injection as described on w3schools site).

Ajax with Database

In this video, I am giving more explanations to the examples from w3schools.
These examples combine all main parts that you've learned in the course in some real life examples using XML and SQL database on the server side working together with HTML, JavaScript and AJAX on the server side.

Note that in my example I added the check of the parameter passed from AJAX to the PHP file:

<?php
$q=$_GET['q'];
// check what has been passed as "q"
echo "parameter". $q;

So if you have a message "parameter " and nothing in it - this means that the q parameter was not passed to the PHP file. Please check the whole chain of getting the value into q and properly passing it to php.

For debugging purposes, you can test your PHP files separately to see if your table and the KEY search field work in the SELECT statement. For this just start your PHP file, where you can comment $q out:

// $q=$_GET['q'];

And after that your SELECT statement  formed with WHERE clause and directly inserted field value should return a record corresponding to that value. Just use your own table name after the connection to your database works correctly:

$sql="SELECT * FROM user WHERE id = 'your key/unique field name'";

If  $result = mysqli_query($con,$sql); will not return anything  - you can check the same SELECT command manually from the SQL section of phpMyAdmin interface to see if the database, table, and key field names where spelled properly.

Wednesday, November 16, 2016

Simple PHP security

Although PHP security is outside of this course, I want to say a few words about it.
There are a number of JS and PHP attacks possible. Code injection is only one of them. Everybody is solving it differently (yes, usually checking the string for suspicious characters) since all possible inputs have different possible dangers. If you want something simple and you have a string input like "name" then you can check for the existence of various tags that shouldn't be there but might redirect the code if placed into the input doing something like:

$name = strip_tags( trim( $_POST[ 'name' ] ) );

The functions functions strip_tags() strips all HTML and PHP tags from a variable. Since we know that name is just the name of a person, and does not need links, or possibly malicious code, we don’t need any tags. So if a person was to add <a href=”http://www.mysite.com”>Mary</a>, it would only let the string ‘Mary’ to be assigned to the variable. The trim() function just strips any white space from beginning and end of the string ( actually it can do more - just google it for the future).

Monday, November 7, 2016

SQL Exercises

After reading the recommended materials about relational databases you can learn/try the use of SQL language for table manipulation. A simple way of trying SQL out  is shown in this video.

Monday, October 31, 2016

Simple PHP form explained

Creation of  a pair of programs dealing with forms is very simple. The first program can be just an HTML file with the form and a reference to the second program processing this form on the server (in our case using PHP). Please watch the video on how to do this.

Wednesday, October 26, 2016

Code explanation for Ajax with XML lab

The required work with Ajax and XML using examples from w3schools  might require some clarifications on how each line of code there works. Understanding this clearly you can somehow reuse the code dynamically creating HTML code for certain parts of the page (like a table) for presenting XML data. Explanations in this video will also allow you to make the examples more complicated and thus learn more.

Ajax code made simple

An HTTP request consists of four parts:


the HTTP request method or "verb" (GET or POST)
the URL being requested
an optional set of request headers, which may include authentication information
an optional request body

The "GET" and "POST" methods are universally supported. "GET" is used for most "regular" requests, and it is appropriate when the URL completely specifies the requested resource, when the request has no side effects on the server, and when the server’s response is cacheable. The "POST" method is what is typically used by HTML forms. The parts of an HTTP request have a specific order: the request method and URL must come first, then the request headers, and finally the request body. XMLHttpRequest implementations generally do not initiate any networking until the send() method is called.

The HTTP response sent by a server has three parts:

a numeric and textual status code that indicates the success or failure of the request (good to check)
a set of response headers (you do not have to use these)
the response body (your information from the server)
 

Below is the code example used in this video lecture

 

 

<!DOCTYPE html>
<html>
<head>

<script>
function loadData()
{
var xhr;
xhr=new XMLHttpRequest();
xhr.onreadystatechange=function()
{
if (xhr.status==200 && xmlhttp.readyState==4 )
{document.getElementById("myDiv").innerHTML=xhr.responseText;}
}
xhr.open("GET","ajax_info.txt",true); // or just xhr.open("GET", url);
xhr.send(); // GET requests never have a body, so pass null or omit 
}
</script>

</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadData()">Change Content</button>
</body>
</html>



XMLHttpRequest Properties

onreadystatechange
An event handler for an event that fires at every state change.
readyStateThe readyState property defines the current state of the XMLHttpRequest object.
Here are the possible values for the readyState propery:


State

Description
0The request is not initialized
1The request has been set up
2The request has been sent
3The request is in process
4The request is completed and data received


readyState=0 after you have created the XMLHttpRequest object, but before you have called the open() method.
readyState=1 after you have called the open() method, but before you have called send().
readyState=2 after you have called send().
readyState=3 after the browser has established a communication with the server, but before the server has completed the response.
readyState=4 after the request has been completed, and the response data have been completely received from the server.
responseText
Returns the response as a string.
responseXML
Returns the response as XML. This property returns an XML document object, which can be examined and parsed using W3C DOM node tree methods and properties.
status
Returns the status as a number (e.g. 404 for "Not Found" and 200 for "OK").
statusText
Returns the status as a string (e.g. "Not Found" or "OK").

How Ajax changed web development

In this video lecture I will be talking not about the details in the code that uses XMLHttpRequest object but about the changes in Web development approach with the use of Ajax. This simple http technology is the foundation of switching from page-based interaction with the server to application based interaction when a number of small independent or communicating apps can create a coherent integral view seen as one page. You all saw such elements of pages as Google AdSense, Google Maps, Suggest, auto-complete, chats and IM, login portion of the page where independent functionality of such pieces does not require for the whole page to be reloaded and all client -side execution to be stopped until the server returns data in each Ajax section.

Working with smarterasp.net

See the short video on how to use folders and files on smarterasp server

Tuesday, October 4, 2016

Simple JS Debugging

In this video lecture you will learn some simple methods of HTML and JavaScript debugging. Of course, there are more powerful tools on the market, but the ones shown in the lecture are simple and easily accessible. In really big projects you can use whole studios of tools...

Commentary to Objects in JavaScript

By now you've learned/refreshed a quite standard set of flow control operations that are used in almost all programming languages.  Now we are moving to more advanced data types such as arrays and objects.
Although arrays form an important topic in any language, objects are the key to modern software development. They allow for a piece of complex software to be broken into smaller and simpler parts that can be debugged independently and then reused in various combinations.
Modern JavaScript extensively uses objects in any serious approach to the software development. Here I am offering three short lessons that are based on your use of w3schools in some creative ways and will help you understand the topic better.

Objects. Part 1

Objects are an extremely important topic in many modern programming languages, as well as in JavaScript. They dramatically increase your programming power, richness, effectiveness and efficiency. There are many tutorials on any part of JavaScript and you are encouraged to browse through some of them in order to find the ones that explain a particular topic in a way best for your learning methods and current understanding. Here I talk about something that will allow you to get into the tutorials on objects easier, compensating for often neglected efforts in letting students understand the nature of objects deep enough to be more comfortable with specific explanations.
Objects are complex data types that might contain data (properties) and a bunch of small programs (methods). Therefore they are like combinations of files with data and a library of programs in one system. Such system can be activated by just its name, can be send somewhere as one thing and then used in all its aspects, like getting data (properties) stored in it and/or running some programs that are contained in objects. In comparison with having files and programs separate – such complex systems (data types) like objects can be easily created and handled as one universal package where we can use its functional capabilities (by running the programs), its data storage capabilities by adding, changing, and retrieving data, or by both at the same time when newly obtained by an object data can be processed by its own programs (methods) either changing its own data or controlling input and output of data processing in and out of an object.
Object-oriented analysis, design and programming tends to see any real life object, process, concept, and so on as potential software objects with their structural and behavioral characteristics. Having these features, program objects can model real life objects that usually also have properties and can doo something (or something can be done to them). Examples: a car, a computer, a pen (with its size and weight, as well as an ability to touch paper, leave a line of ink, etc.) and so on. Once you are trained in such vision – you can quickly create models of real situations (or virtual and game situations)  and make them interact with each other using their properties and behaviors in response to initiatives of other objects. Thus you can create real  virtual/game worlds that react to actions of their own objects or physical objects like players.
Since your software can activate many different objects for communication with each other – anything that you want object to store, retrieve or do requires the use of a particular object name because otherwise it will be unclear who you are talking to (in your command).  This can be achieved by calling first the name of a particular object followed by the operation on its data or invoking one of its methods (small programs).


ExampleA: myCar. CurrentMileage = 2000;


ExampleB: myCar.showYourCurrentMileage(); 


Here the first example shows how to store data in one of the properties of myCar object (CurrentMileage), while the second shows how to run a small program (showYourCurrentMileage()) that might be programmed to get that property and show it on the page. See below an example from w3schools of an object “person” and a link allowing to experiment with it by adding and retrieving more properties.


Example 1. Properties:


<body>


<article id="demo"></article>


<script>
var person = {

    firstName : "John",

    lastName  : "Doe",

    age       : 50,

    eyeColor  : "blue"

};

document.getElementById("demo").innerHTML =

person.firstName + " is " + person.age + " years old.";


</script>

</body>

</html>
Experiment with it live (http://www.w3schools.com/js/tryit.asp?filename=tryjs_create_object1 ) by adding and retrieving new properties, like making it say: “John is 50 years old and 4 feet tall.”


Then create more interesting objects with properties and something printed  out about that object. Later you will be adding code for changing the properties and adding new properties dynamically.


Objects. Part 2. Methods

After you watch Lecture 1 (What are objects?) we can continue to the discussion of the second part of objects - programs that are stored in them. They are called methods. In this video lecture I will be talking about ways of using w3schools as a debugging and development platform

Objects. Part 3. More Advanced Stuff (optional reading)

First read http://www.w3schools.com/js/js_object_prototypes.asp about prototypes and experiment with them in included exercises. Important to understand that compared to the old typical object-oriented languages (VB, C++, C#, Java, etc.) that are strongly typed and have such forms as objects being created during the compilation time – dynamic languages (such as Perl, Ruby, Smalltalk, and… JavaScript, along with the number of others) allow to change the program and its data types during the execution depending on the situation. For example var x = 5; dynamically becomes and integer, but if later you use x=”hello”; then it becomes a string. You saw  in the examples from w3schools how it is possible to change, add, delete properties and methods in objects. Same is possible to do in constructors using prototypes. This allows to change whole groups (types of objects) like instead of changing properties of a student Bob – you can change properties of the constructor which changes properties of ALL students that were derived (using “new”) from that constructor. For example in games, objects operating on the screen might change properties (like colors, shapes, etc.)  and behaviors under various conditions DURING the game. In general program can change itself depending on the situation and an old saying that computer can do ONLY what it was programmed to do is incorrect. Software systems can LEARN (using various learning algorithms) and evolve to become more adequate to the situation when after a while the creators might not even know how and why the system does some new tricks.

This leads to the situation when in systems that were intended to be dynamic – the programmers do not know what properties and how many of them their objects will have after a while  depending on various situations. This leads to the need in using safer forms of handling objects where their properties are treated as arrays and are accessed in a loop like is shown in http://www.w3schools.com/js/tryit.asp?filename=tryjs_object_for_in where the code uses it:

 var txt = "";

var person = {fname:"John", lname:"Doe", age:25};

var x;

for (x in person) {

    txt += person[x] + " ";} 

Here x (better would have been to use conventional i, j as indexes) is just an index reflecting the position of an attribute in the object “person”. Using a tricky construction (for (x in person)) we can enumerate the properties and then treat them like an array using their relative number in the enumerated sequence treating it as person[x] instead of giving a name of each property as you did before. 

An example of how useful objects are in making your code  more compact and logic more clear can be seen in operating whole objects as variables by passing them to other objects or functions:

var father = {

    firstname:"John",

    lastname:"Doe",

    age:65,

    eyecolor:"blue"

};


function canRetire (person){

if (person.age > 62) {
  return true;

} else {

  return false;

}

 Here, assuming that object father is an instance (derived from) of the type (class) person, we are passing the whole object to the function checking if that particular person (particular object) can retire. In a similar fashion once a function gets an object as a parameter – it can internally use all its properties and functions. Notice that instead of sending a bunch or parameters to a function we are sending just one (of type person) that can have a very complex and rich structure.





Thursday, September 29, 2016

Using External Templates

In this video I will show you how to use an external template for your project. Remember that you should author it, meaning use your own text, some of your art (some can be theirs) and some changes in the CSS. W3Sschools and your textbook are always there to refresh your memory on how to use html and css.

How to use the OSWD site if there is no clear zip download

In this video, I am showing the way of using simple templates from OSWD site  (not Wix) that are similar to those that I recommended in Q&A. If there is no option of downloading the whole zipped directory/folder where the HTML and CSS are located for the chosen template then use a few simple steps from the video.

Simple start with JavaScript

This lecture supplements reading the appropriate sections of JavaScript on w3schools. Our approach is not in exhaustive learning of each command and feature which can take a couple of semesters but get initially a simple introduction to the main features of the language allowing to start programming your web pages. Later you will be getting more confidence in the use of these features, will periodically reread various web tutorials or google specific problems. But this will be much easier when working on some live code and having in mind some web project.

Working with SFTP (WinSCP)

This video lecture shows how to set your secure file transfer client and how to move files and folders between your local station and remote server (pages.ramapo.edu in our case).

JavaScript on one page

The best way of combining  JS examples from the tutorial on one page is creating special placeholders (like paragraphs with id) that can be referred in the script by these ids. You can use functions to structure examples or just JS operations for a specific id, or mixing both. In the example below I am showing how to use a function with some calculation and just an expression assigned to the part of the document specified by an id (f.e using:

document.getElementById("demo").innerHTML )



<!DOCTYPE html>
<html>
<body>
<p>This example calls a function which performs a calculation, and returns the result:</p>
<p id="demo"></p>
<p>This example shows string concatenation:</p>
<p id="concat"></p>

<script>
function myFunction(a, b) {
    return a * b;
}
document.getElementById("demo").innerHTML = myFunction(4, 3);


var carName1 = "Volvo XC60";
var carName2 = 'Volvo XC60';
document.getElementById("concat").innerHTML =
carName1 + " " + carName2;

</script>
</body>
</html>


You can copy the whole text and paste it in one of the w3schools examples (f.e
http://www.w3schools.com/js/tryit.asp?filename=tryjs_strings) substituting ALL their text with the one above.
You can do such trials by copying code into w3schools example, rearranging it and running.
After it works you can copy the whole page to your Ramapo server.

Wednesday, September 21, 2016

Simple introduction to CSS

Before watching this video you have to view the previous one about screen organization!


 A simple gentle introduction to some important concepts of CSS working together with HTML can be found in this video.
Here you will also see the continuation of the previous video lecture on best screen organization for work with html, css, and the chosen browser on one screen.
For best viewing, you might want to download the video and then view it locally.
Additional explanation on internal and external ways of using CSS can be found here

Wednesday, September 14, 2016

Working with text editors in Mac OS

Make sure that you save the file with .html extension (like index.html). TextEdit might automatically save files by adding a .txt extension. Then browsers will not open it as an html file, but as a text file. To see what your extension really is CTRL + click on the file then select get info - under the general section  it should say Kind: HTML document.

If despite your attempts to save as html it adds a .txt extension (as .html.txt)
then go in finder and change the extension to html.
For more info on working with HTML files in textedit you can see http://computers.tutsplus.com/tutorials/quick-tip-configure-textedit-for-coding-html--mac-44786
Another possible source of problems is described in http://www.askdavetaylor.com/how_do_i_save_html_files_from_textedit/
Some people say that TextWrangle works better for them...

Thursday, September 8, 2016

How to Organize Your Screen for Work with HTML and Notepad

The following video shows how to start working on your HTML, how to save it, how to view it in the browser, and how to modify it using a comfortable screen organization with several windows side-by-side.

Purpose of this blog

Since the course is hands-on, dynamic, and in an online format - I will be running a blog that will substitute professor's commentary that you might get in face-to-face classes. It will allow making such comments more timely (whenever they have to be done and not only during class sessions) and more tailored to the current class performance and activities. Here you will find my current comments on the tasks, grades, additional help materials, etc.
The additional and help material will be published separately and linked to from this blog. Check this blog often since I assume that you've read it and consider it in my evaluation of your course work, task creation, and quiz questions. Additional advice, requirements, or modifications in the weekly tasks will also be posted here.

Watch for the new titles of posts arriving in the blog section (right-bottom corner of the page) on Moodle.