Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Saturday, September 15, 2018

JsonX APIs

Note: This library is now part of WebFiori Framework. Updated API Docs can be found at https://programmingacademia.com/webfiori/docs/jsonx/.

This page contain APIs descriptions of the library JsonX, A library that can be used to create JSON strings in PHP. The library consist of two files only, JsonX.php and JsonI.php. The first file contains the class 'JsonX' which is the core component. The other file contains an interface which can be implemented by other classes to create a custom JSON strings.

Basic Usage Example

The next lines of code shows how to use the library in very simple way.

<?php
include 'JsonX.php';
include 'JsonI.php';

//create new instance of JsonX
$json = new JsonX();

//add attributes to JSON object.
$json->add('a-string', 'This is a string.');
$json->add('a-number', 44);
$json->add('a-boolean', FALSE);
$json->add('null-value', NULL);

//send Json object as response
header('content-type:application/json');
echo $json;

Class JsonX

Version: 1.2

Author: Ibrahim BinAlshikh

const TYPES

  • Type: Array
  • Description: An array of supported JOSN data types. The array has 7 values: 'integer', 'string', 'double', 'boolean', 'NULL' and 'object'.
  • Since: 1.0

const SPECIAL_CHARS

  • Type: Array
  • Description: An array which contains JSON special characters that can be a part of a string. The array has the following characters: \\, /, ", \t, \r, \n and \f.
  • Since: 1.0

const SPECIAL_CHARS_ESC

'
  • Type: Array
  • Description: An array which contains escaped JSON special characters that can be a part of a string.
  • Since: 1.0

public function add($key, $value, $options=array())

Adds a new value to include in the generated JSON string.

Parameters:

  • $key:
    • Type: string
    • Description: The name of the attribute that the given value will be stored in. Usually called the "name" of the "value".
  • $value:
    • Type: mixed
    • Description: The value of the key. It can be an integer, a double, a string, an array or an object. If NULL is given, the method will set the value at the given key to 'null'.
  • $options: [Optional]
    • Type: Array
    • Description: An associative array of options. Currently, the array has the following options:
      • string-as-boolean: A boolean value. If set to TRUE and the given string represents a boolean value (like 'yes' or 'no'), the string will be added as a boolean value. Default is FALSE.
      • array-as-object: A boolean value. If set to TRUE, the array will be added as an object. Default is FALSE.

Returns:

  • boolean: TRUE if the value is set. If the given value or key is invalid, the function will return FALSE.

Since: 1.1

public function addNumber($key, $value)

Adds a number to include in the generated JSON string.

Parameters:

  • $key:
    • Type: string
    • Description: The name of the attribute that the given value will be stored in. Usually called the "name" of the "value"
  • $value:
    • Type: integer | double
    • Description: The number which will be added. Note that if the given number is INF or NAN, The method will add them as a string.

Returns:

  • boolean: TRUE if the value is set. If the given value or key is invalid, the function will return FALSE.

Since: 1.0

public function addBoolean($key, $value)

Adds a boolean value (true or false) to include in the generated JSON string.

Parameters:

  • $key:
    • Type: string
    • Description: The name of the attribute that the given value will be stored in. Usually called the "name" of the "value"
  • $value: [Optional]
    • Type: boolean
    • Description: TRUE or FALSE. If not specified, The default will be TRUE.

Returns:

  • boolean: TRUE if the value is set. If the given value or key is invalid, the function will return FALSE.

Since: 1.0

public function addString($key, $value, $asBoolean)

Adds a string to include in the generated JSON string.

Parameters:

  • $key:
    • Type: string
    • Description: The name of the attribute that the given value will be stored in. Usually called the "name" of the "value"
  • $value:
    • Type: string
    • Description: The value of the string. Note that if the given string is one of the following and the parameter $asBoolean is set to TRUE, it will be converted into boolean (case insensitive).
      • yes => TRUE
      • no => FALSE
      • y => TRUE
      • n => FALSE
      • t => TRUE
      • f => FALSE
      • true => TRUE
      • false => FALSE
      • on => TRUE
      • off => FALSE
      • ok => TRUE
  • $asBoolean: [Optional]
    • Type: boolean
    • Description: If set to TRUE and the string represents a boolean value, then the string will be added as a boolean. Default is FALSE.

Returns:

  • boolean: TRUE if the value is set. If the given value or key is invalid, the function will return FALSE.

Since: 1.0

public function addArray($key, $value, $asObject)

Adds an array to include in the generated JSON string.

Parameters:

  • $key:
    • Type: string
    • Description: The name of the attribute that the given value will be stored in. Usually called the "name" of the "value"
  • $value:
    • Type: Array
    • Description: The array that will be added. If the given array is indexed array, all values will be added as single entity (e.g. [1, 2, 3]). If the array is associative, the values of the array will be added as objects.
  • $asObject: [Optional]
    • Type:
    • Description: If this parameter is set to TRUE, the array will be added as an object in JSON string. Default is FALSE.

Returns:

  • boolean: TRUE if the value is set. If the given value or key is invalid, the function will return FALSE.

Since: 1.0

public function addObject($key, $value)

Adds a PHP object to include in the generated JSON string.

Parameters:

  • $key:
    • Type: string
    • Description: The name of the attribute that the given value will be stored in. Usually called the "name" of the "value">
  • $value:
    • Type: JsonI | Object
    • Description: The parameter can be a PHP object or an object that implements the interface 'JsonI'. If the object does not implement the interface 'JsonI', then the function will try to extract object information based on its public functions and the generated JSON will be on the format {"prop-0":"something","prop-1":"something else","prop-n":"xxx"}.

Returns:

  • boolean: TRUE if the value is set. If the given value or key is invalid, the function will return FALSE.

Since: 1.0

public function get($key)

Returns a string that represents the value at the given key.

Parameters:

  • $key:
    • Type: string
    • Description: The name of the attribute that the value is stored in. Usually called the "name" of the "value"

Returns:

  • string | NULL: A string that represents the value at the given key. If the key does not exists, the function will return NULL.

Since: 1.2

public function hasKey($key)

Checks if a key is exist or not.

Parameters:

  • $key:
    • Type: string
    • Description: The name of the key. Usually called the "name".

Returns:

  • boolean: The function will return TRUE if the key exists. FALSE if not.

Since: 1.2

public static function escapeJSONSpecialChars($str)

Escape JSON special characters from a string.

Parameters:

  • $str:
    • Type: string
    • Description: A value of one of JSON object properties. If it is NULL,the method will return empty string.

Returns:

  • string: The same string with JSON special characters escaped.
  • Since: 1.0

Interface JsonI

Version: 1.0

Author: Ibrahim BinAlshikh

public function toJSON()

This function can be implemented by any class that will be added as an attribute to any JsonX instance.It is used to customize the generated JSON string.

Parameters:

  • NONE

Returns:

  • JsonX: An instance of JsonX

Since: 1.0


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.


Monday, April 17, 2017

JavaScript: Working With Cookies


This is a simple lesson that has all what you need to know about web cookies using JavaScript. In this lesson, we will learn the following:
  • What is a Cookie.
  • How to Create them.
  • Setting Expiry Date of a Cookie.
  • View a Cookie using JavaScript.
  • Deleting a Cookie.

What is a Cookie?

The correct question to ask is 'What is a Web Cookie?'.
A web cookie is a small piece of text that is created by a web site's
and sent to the user's computer and stored temporarily. The main functionality
of the web cookie is to provide a state for the stateless web pages.

A web cookie has 3 main components:

  • Name.
  • Value.
  • Zero or more pairs of key/value.
Here is an example of a web cookie:


my_name = ibrahim

This is the most simplest cookie that can be created. It has the name 'my_name'
and a value of 'ibrahim'.

It is very simple to create cookies with JavaScript. The following syntax can
be used to create the previous cookie:


document.cookie = "my_name = ibrahim";


When a cookie is created, it is better to specify an expiry date for it.
If we do not specify an expiry date, the cookie will be deleted once the
browser window is closed. Expiry date is considered as key/value pair


document.cookie = "my_name = ibrahim; expires = Sat, 04 Feb 2017 19:43:41 UTC";

It is good practice to set the time to UTC (Coordinated Universal Time) since the visitors of a web site may have different time.

To make a cookie expire after specific time, we can use 'Date' object to to that.


//create new date object

var date = new Date();

//we want our cookie to expire after 5 days

var days = 5

var currentTime = date.getTime()

/*


note that 1 second = 1000 milliseconds

and 1 minute has 60 seconds and

one hour has 60 minutes and one day has 24 hours.

5 days = 1000*60*60*24*5 = 432000000 milliseconds

If we want from our cookie to expire after 2 hours, we set

the time to (current time + 1000*60*120)


*/

date.setTime(currentTime + 1000*60*60*24*days);

document.cookie = "my_name = ibrahim; expires = "+date.toUTCString();

In order to update the content of the cookie, we use the same syntax that is used
to create a cookie.


//this is our new cookie

document.cookie = "my_name = ibrahim; expires=Sat, 04 Feb 2017 19:43:41 GMT";



//this is the same cookie with new value

document.cookie = "my_name = ali; expires=Sat, 04 Feb 2017 19:43:41 GMT";


To view all cookies for the web site, we simply use the following:


allCookies = document.cookie;

console.log(allCookies);

What we get is actually a string of text that shows all the available cookies that
is sent by the web site. To get specific cookie value, we have to build a function
that can split cookies.

To delete a cookie, we have only to update the expiry date of the cookie to a date that'd
has been passed. But before we delete a cookie, we have to set the 'path' value of the cookie.
some browsers does not allow the deletion of a cookie with no path.



//create cookie

document.cookie = "my_name = ibrahim; expires = Sat, 04 Feb 2030 19:43:41 UTC;path=/";

//delete cookie

document.cookie = "my_name = ibrahim; expires = Sat, 04 Feb 2010 00:00:00 UTC;path=/";


Source: Programming Academia