Saturday, June 24, 2017

JavaScript: AJAX Response


Introduction

In the last post, we have learned how to send AJAX request to the server. After sending the request to the server, the server will send back a response. The response is processed using the property "XMLHttpRequest.onreadystatechange". There are more properties that we will be using to handle the response:
  • The property XMLHttpRequest.readyState
  • The property XMLHttpRequest.status
  • The property XMLHttpRequest.responseText


The property "XMLHttpRequest.readyState"

The "XMLHttpRequest.readyState" is a number that can have 5 values:
  • Request not initialized = 0.
  • Connection Established = 1.
  • Request received = 2.
  • Processing = 3.
  • Finished = 4.
The next code example can be used to show the status of the request each time the value of "XMLHttpRequest.readyState" changes.

var xmlhttpReq = new XMLHttpRequest();
xmlhttpReq.onreadystatechange = function(){
    switch (xmlhttpReq.readyState) {
        case 0:{
            console.log('Request not initialized');
            break;
        }

        case 1:{
            console.log('Connection Established');
            break;
        }

        case 2:{
            console.log('Request received');
            break;
        }

        case 3:{
            console.log('Processing');
            break;
        }
        case 4:{
            console.log('Finished');
            break;
        }
    }
}
xmlhttpReq.open('GET', '', true);
xmlhttpReq.send();



The property "XMLHttpRequest.status"

The value of this property can change at any time. It is basically a code that can be used to identify the status of the request. The value of this property can be any value that is used to identify the status of HTTP request. For example, the value 200 means OK. the value 500 means server error and so on.
If the value of "XMLHttpRequest.status" is 200 and the value of "XMLHttpRequest.readyState" is 4, then the request was successful.

var xmlhttpReq = new XMLHttpRequest();
xmlhttpReq.open('GET', '', true);
xmlhttpReq.onreadystatechange = function(){
    if(xmlhttpReq.status == 200 && xmlhttpReq.readyState == 4){
        //request succeeded
    }
}
xmlhttpReq.send();



The property "XMLHttpRequest.responceText"

This property is used to access the data that was sent by the server. It can be a simple text, A JSON object or XML document or any thing else. The following example shows how to access the value of this property.

var xmlhttpReq = new XMLHttpRequest();
xmlhttpReq.open('GET', '', true);
xmlhttpReq.onreadystatechange = function(){
    if(xmlhttpReq.status == 200 && xmlhttpReq.readyState == 4){
        //print response body
        console.log(xmlhttpReq.responseText);
    }
}
xmlhttpReq.send();

This is all what you need to know about AJAX in order to use it.

Friday, June 23, 2017

JavaScript: AJAX Request


Introduction

In the previous post, we have talked about the basic idea behind AJAX. Before we continue with how to create a fully functional AJAX request, we need to understand some properties and methods of the XMLHttpRequest class. At minimum, we have to worry about the following:
 
  • The property XMLHttpRequest.onreadystatechange
  • The method XMLHttpRequest.open()
  • The method XMLHttpRequest.send()
There are other properties that we will use when we need them.


The property "XMLHttpRequest.onreadystatechange"

The value of this property is set to a function. The function will handle the event that will be fired when the value of the property "XMLHttpRequest.readyState" is changed. There are 5 values that the property can have. We will come to them later when we start talking about handling response.


The method "XMLHttpRequest.open()"

The method "open()" is used to initialize the request. This method can accept 4 parameters at most, two of them is a must and the others are optional.

//The first two must be provided
XMLHttpRequest.open(requestMethod,requestedURL,userName,password);

The request method is a string. The most common values of this field are the following:
MethodWhen to use
GETUsed to retrieve data such as files
POSTThis method is used to submit data to the server. Usually it causes some changes on the state of the server.
HEADWe use this method to get the response headers only.


The method "XMLHttpRequest.send()"

This method is used to send the request. It takes one parameter which is the content that we would like to send on the body of the request. We only need to provide the body content only if we will use the method 'POST'.


AJAX Request Example 1

Suppose that the URL of our server is "https://mysite.com" and suppose that on the server we have the directory "/posts" and inside that directory we have a file named "getPost.php". The file "getPost.php" will return a post based on its ID. The ID must be provided as query string. What we will do is to build a method that has the ID of the post as parameter. The method then display the result of the response.

function getPost(id){
    //get the post that has the given id
    var query = '?id='+id;
    var url = 'https://mysite.com/posts/getPost.php';
    var xmlhttpReq = new XMLHttpRequest();
    xmlhttpReq.open('GET', url+query, true);
    xmlhttpReq.onreadystatechange = function () {
    //display response result. we will do that on the next post
    }
xmlhttpReq.send();
}

Since we are using PHP, the file "getPost.php" might have something like this:

if($SERVER['REQUEST_METHOD'] == 'GET'){
    if(isset($_GET['id'])){
        $postID = $_GET['id'];
        //get the post from the database
        //and send it back using 'echo' command.
    }
    else{
        //the id parmeter is messing
        http_response_code(422);
    }
}
else{
    //method is not GET
    http_response_code(405);
}



AJAX Request Example 2

In this example, we want to implement a basic login system. We will be using the same URL in the previous example. But this time, we will be assume that we have another file. The file will be "login.php" that is located in the main directory of the server. Usually, the request method "POST" is used in such as situation. In this example, the username and password must be sent in the Request body since we are using "POST".

function login(username,password){
    var requestBody = 'username='+username+'&password='+password;
    var url = 'https://mysite.com/login.php';
    var xmlhttpReq = new XMLHttpRequest();
    xmlhttpReq.open('POST', url, true);
    //we must set this header to send data on the body
    xmlhttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xmlhttpReq.onreadystatechange = function (){
        //display response result. we will do that on the next post
    }
    //sending the login string with the request body
    xmlhttpReq.send(requestBody);
}

The file "login.php" might have something like this:

if($SERVER['REQUEST_METHOD'] == 'POST'){
    if(isset($_POST['username'])){
        $username = $_POST['username'];
        if(isset($_POST['password'])){
            $password = $_POST['password'];
            //check database for the login info
        }
        else{
            //password is messing
            http_response_code(422);
        }
    }
    else{
        //Username is messing
        http_response_code(422);
    }
}
else{
    //method is not POST
    http_response_code(405);
}


In the next post, we will be learning how to handle the response that the server will give back after the request.


Thursday, June 22, 2017

JavaScript: Introduction to AJAX


What is AJAX?

AJAX (Asynchronous JavaScript and XML) is a technique used to update the content of a web page dynamically. It updates some content of the page asynchronously by sending small amount of data to the server. This means that you don’t have to reload the whole page to update the contents of the web page.


How it Works?

In JavaScript, when an event is accrued, the browser initiates an XMLHttpRequest object. After that, the request is sent to the server for processing. The server creates a response and sends it back to the browser. Finally, the browser processes the given response using JavaScript and updates the content of the page. The next image illustrates the process.




XMLHttpRequest Object

XMLHttpRequest is a JavaScript object used to send a request to the server. The name of the object is usually misleading. Although it contains the letters “XML”, you don’t have to know XML to use the object. All what you have to know is JavaScript and some basics of HTTP request. All modern web browsers support the object. IE5 and IE6 have something else that is called ActiveXObject. ActiveXObject is the same as the XMLHttpRequest.



Using XMLHttpRequest Object

In order to send a request to the server, first we have to create an instance of XMLHttpRequest. After that, we must open the connection using the method open(method,UR,boolean_async). Finally, we send the request using the send() method.

The open() method takes 3 parameters, the first one is the “method”. It takes two values: GET and POST. We can use other methods such as DELETE or HEAD but the given two are the most common.

Most of the time, GET is used. But for sending large amount of data or updating a database on the server, using POST is better by including data on the body of the request. Also POST is more secure. Use it for sending user sensitive information such as username and password or bank account number.

The URL parameter is used to specify a file location on the server. The file can be of any type. It can be a simple text file or a server scripting file such as PHP for performing server side tasks. If the parameter boolean_async is set to true, JavaScript does not have to wait for the response to continue executing. This is the main benefit of using AJAX.

We can specify what happen after the response is received by setting the property "onreadystatechange" of the object to a function. We will learn more about the "onreadystatechange" next. When the boolean_async is set to false, the code will stop executing till the server sends a response. Also in this case, We don’t have to write any code for the “onreadystatechange” property. The following code shows how to create a basic XMLHttpRequest object.

var xmlhttpReq = new XMLHttpRequest();

xmlhttpReq.open('GET', '', true);

xmlhttpReq.onreadystatechange = function () {

//do something after the response is received.

}
xmlhttpReq.send();

In the next post, we will learn about how to use AJAX request with some server side functionality.


Thursday, June 15, 2017

Java Basics: Variable Naming Rules and Conventions

One of the important things to learn regarding java programming language is what is allowed and not allowed in choosing the name of a variable. Basically there are rules for choosing the name of a variable and there are conventions. In this post, we will be learning about the rules that govern variable naming in java language in addition to the conversions that is used by any java developer. We will include code examples to illustrate naming rules.

Naming Rules

1 - Variable name can start only with a letter, underscore (_) or dollar sign ($).

//This is allowed
int firstNum;

//This is allowed
int FirstNum;

//This is allowed
int _firstNum;


//This is allowed
int $firstNum;


//This is not allowed
int !firstNum;



2 - Variable name can contain numbers after the first letter.

//This is allowed
int burger1;


//This is not allowed
int 1burger;

//This is allowed
int burger2;


3 - Variable name cannot contain spaces or special characters.

//This is not allowed
int burger 1;

//This is not allowed
int burger-2;

//This is not allowed
int burger(3);


4 - Uppercase name differ from lower case.

//This one variable
int burger;


//This one is another one
int BURGER;

//Also this one is not same as above
int BURGer;


5 - Java keywords cannot be used for variable name (e.g. void).

//not allowed
int void;



6 - The length of the variable can be of any length.

Naming Conventions

Naming conventions are used by the developers to understand the meaning of a variable. For example, if you wrote a code and someone else reads that code, he will be able to understand your code easier if you use naming conventions. I my self follow the given conversions when I write Java code.

The following naming conventions are good to follow when you start writing your code:

  • Do not use dollar sign or underscore in the name of your variables.
  • Use meaningful names.
  • Use uppercase letters for the constant variables(e.g. PI = 3.14).
  • If the constant has two words, use underscore to separate words (e.g. MAX_SIZE = 4).


Tuesday, June 6, 2017

Java Basics: Type Casting



What do we mean by "Type Casting"?
Type casting is basically the process of changing or converting one variable from one data type to other different data types. For example, we may want to convert an integer variable data type to a long data type. For the primitive data types, The type casting can be performed only on the numbers. We can think of a char data type as a number since it is one of the Integral Data Types. We cannot perform casting on boolean.

What is an Integral Data Type?
An integral data type is a data type that represents a subset of the infinite integer set (such as byte, short, int, char, long in Java Language).
For the primitive data types, we have two types of conversion:
  • Narrowing primitive conversion
  • Widening primitive conversion
Before we continue with the meaning of each one, we have to know few things. Java data types are grouped into 3 groups, The Integral Types, Floating and the boolean. The integral group contains the types that does not have a decimal point. It includes the int, byte, short, long and the char. The floating group contains the types that has a decimal point. The floating group contains two data types, the double an the float. The boolean group contains only the boolean data type. Each data type has a specific size. The double is 64 bits, the long is 64 bits, the float is 32 bits, the int is 32 bits, the short is 16 bits, the char is 16 bits and the byte is 8 bits.

The next table shows the summary of data types sizes.

GroupData TypeSize
Floatingdouble64 bits
float32 bits
Integrallong64 bits
int32 bits
short and char16 bits
byte8 bits


Widening Primitive Conversion

Sometimes called Automatic Type casting. It can happen when we try to cast a small size type to a larger size type. For example, we may want to convert from a short to an int. Also we can cast from Integral type to floating type in widening primitive conversion.

GroupData TypeSize-
Floatingdouble64 bits
Widening Primitive Conversion 1
float32 bits
Integrallong64 bits
int32 bits
short and char16 bits
byte8 bits
This type of casting does not require any special thing in order to be completed. The next code example shows how it can be done.





public class Main{
  public static void main(String [] arguments){

    //the original value
    byte myByte = 65;

    //changing from byte to short
    short byteAsShort = myByte;

    //changing from byte to integer
    int byteAsInt = myByte;

    //changing from byte to double
    double byteAsdouble = myByte;

    //from long to double. Notice the 'L'
    double longAsDouble = 77L;

    //from float to double. Notice the 'F'
    double floatAsDouble = 67F

    System.out.println("byte = "+myByte);
    System.out.println("byte as short = "+byteAsShort);
    System.out.println("byte as integer = "+byteAsInt);
    System.out.println("byte as double = "+byteAsdouble);
    System.out.println("byte as double = "+byteAsdouble);
    System.out.println("long as double = "+longAsDouble);
    System.out.println("float as double = "+floatAsDouble);
  }
}

Widening Primitive Conversion 2










One thing to notice about widening primitive conversion is when we try to cast a byte or a short to a char. In order to cast from byte to char, we have to till the compiler that we are changing from byte to char. Same thing apply when we are casting from short to char. The following code example shows how to do that.





public class Main{
  public static void main(String [] arguments){

    //the original value
    byte myByte = 65;
    //changing from byte to short
    short byteAsShort = myByte;
    //changing from byte to character. Notice the '(char)' thing that we have added
    char byteAsChar = (char)myByte;
    System.out.println("byte = "+myByte);
    System.out.println("byte as short = "+byteAsShort);
    System.out.println("byte as char = "+byteAsChar);
  }
}

Widening Primitive Conversion 3









Narrowing Primitive Conversion

Narrowing primitive conversion is the opposite of Widening primitive conversion. What we do is we convert a larger size data type to a smaller one. To complete this task, we have to tell the compiler explicitly about the conversion. We do that by doing the same thing when we wanted to convert from byte to char.

GroupData TypeSize-
Floatingdouble64 bits
Narrowing Primitive Conversion 1
float32 bits
Integrallong64 bits
int32 bits
short and char16 bits
byte8 bits

The following code example shows how it is done.





public class Main{
  public static void main(String [] arguments){

    //the original value 
    double myDouble = 65.3456;
    //changing from double to float 
    float doubleAsFloat = (float)myDouble;

    //changing from double to long
    long doubleAsLong = (long)myDouble;

    //changing from double to int 
    int doubleAsInt = (int)myDouble;
     
    //from double to short 
    short doubleAsShort = (short)myDouble;

    //from double to char
    char doubleAsChar = (char)myDouble;

    //from double to byte 
    byte doubleAsByte = (byte)myDouble;
    System.out.println("double = "+myDouble);
    System.out.println("double as float = "+doubleAsFloat);
    System.out.println("double as long = "+    doubleAsLong);
    System.out.println("double as int = "+doubleAsInt); 
    System.out.println("double as short = "+doubleAsShort);
    System.out.println("double as char = "+doubleAsChar);
    System.out.println("double as byte = "+doubleAsByte);

  }
}

Narrowing Primitive Conversion Example Output










What Happened to the Decimal Point when We cast from float or double to a type that has no Decimal Point? When we cast from floating type to integral type, the number will be always truncated (the numbers after the decimal point will be cut down).





public class Main{
  public static void main(String [] arguments){

    //the original values
    double firstDouble = 88.49;
    double secondDouble = 88.50;
    double thirdDouble = 600.90;
    double fourthDouble = 600.0001;

    //changing from floating to integral type
    int firstDoubleAsInt = (int)firstDouble;
    int secondDoubleAsInt = (int)secondDouble;
    int thirdDoubleAsInt = (int)thirdDouble;
    int fourthDoubleAsInt = (int)fourthDouble;

    System.out.println("first double = "+firstDouble);
    System.out.println("first double as int = "+firstDoubleAsInt);
    System.out.println("second double = "+secondDouble);
    System.out.println("second double as int = "+secondDoubleAsInt);
    System.out.println("third double = "+thirdDouble);
    System.out.println("third double as int = "+thirdDoubleAsInt);
    System.out.println("fourth double = "+fourthDouble);
    System.out.println("fourth double as int = "+fourthDoubleAsInt);
  }
}

Narrowing Primitive Conversion Example Output