Basics of AJAX

Welcome to the next article where we will discuss the basics of this, what changed JavaScript for ever.

Basics of AJAX

The AJAX (Asynchronous JavaScript and XML) — is a technology of web application development, in which the user can interact with the server without reloading the entire document. Operations are done asynchronously.

AJAX technology consists of several elements:

– XMLHttpRequest — an object allowing asynchronous transmission of data over the network. During processing the user can perform other tasks, also retrieve data from multiple sources.

– JavaScript — the language well known to us, although in the assumption it could be a different client-side language with DOM support, e.g. VBScript.

– XML  — markup language as data carrier of sent and/or received information. In addition to the XML also other formats are used, such as JSON, although the data carrier can also be plain text or HTML snippets. For the Ajax with JSON there is even a special term: AJAJ.

Practical AJAX

Below we presented a basic example of using AJAX. Classical, in pure JavaScript i.e. without frameworks.

var httpRequest;
if (window.XMLHttpRequest) { // Mozilla, Safari, …
    httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
    httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}

httpRequest = new XMLHttpRequest();
httpRequest.overrideMimeType('text/xml');

// define a getter function:
httpRequest.onreadystatechange = name;

// or another way:
httpRequest.onreadystatechange = function() {
    // definition
    alert('Test');
};

The open() method:

// true in the 3rd parameter = the request is asynchronous
httpRequest.open('GET', 'http://www.example.org/some.file', true);

Examples of using the open() method:

r.open('GET', 'mysite.jsp', true);
r.open('GET', 'myfile.jpg', true);
r.open('GET', 'http://www.example.net/get.php?id=123', true);

Sending the data — send():

httpRequest.send(null);

The send() method has one parameter: data appended to the query. This parameter must be used for the POST method. We use null if the method used is GET.

Cookies in JavaScript

In this article we will talk about working with cookies in JavaScript. And no, it’s not about eating.

Working with cookies in JavaScript

Cookies — small information sent by a web server and stored on the user side (typically on the hard disk).

Cookies are most commonly used for counters, probes, online stores, sites that require login, advertising and to monitor the activity of visitors. They are just a way of maintaining “communication” between the user and the server.

The syntax of the HTTP header for cookie:

Set-Cookie: name=x; expires=date; path=mypath; domain=mydomain; secure

Description of parameters:

name=value — in fact cookie name is the only required parameter. It consists of any characters except colons, commas, whitespace and slashes (/). If you need to use them, they are usually encoded in a format suitable for URL (%XX), where XX is the ASCII code (e.g. %2F is encoded slash, %20 — encoded space char).

expires=date — this attribute tells the browser the expiration date of the cookie. It will be deleted from the disk when its expiration date is exceeded. If no expiration date specified, the cookie will be deleted when the session ends. The date must be entered in the correct format — for example: “Tuesday, 11-Nov-2007 08:39:09 GMT”.

domain=mydomain — this parameter specifies the visibility of cookie. When checking the cookie file on the client’s computer, the browser compares the stored domain with the domain server, which sends the headers.

path=mypath — the path attribute is applied to reduce the visibility of cookies. All pages included in this directory and its subdirectories will be able to use them.

secure — a parameter without a value, if specified, the cookie will be visible (sent) only when the connection is encrypted (currently possible using HTTPS).

A basic example — setting the cookie:

document.cookie = "myLang=DE";

Reading the cookie:

var cookies = document.cookie.split(/; /g);

When accessing, JavaScript gets a list of all the cookies, but as a string, not as an array. So we need to split a string, using a semicolon as the separator.

A toolbox

The code below is a comprehensive set of functions for handling cookies in pure JavaScript.

Create a cookie:

function writeCookie(cookieName, cookieValue, expires, domain,
    path, secureFlag) {
    if (cookieName) {
        var cookieDetails = cookieName + "=" +
            escape(cookieValue);

        cookieDetails += (expires ? "; expires=" +
            expires.toGMTString(): '');

        cookieDetails += (domain ? "; domain=" + domain: '');
        cookieDetails += (path ? "; path=" + path: '');
        cookieDetails += (secureFlag ? "; secure": '');
        document.cookie = cookieDetails;
    }
}

Math, numbers, calculations. The Math object in JavaScript.

Well, other JavaScript objects we have discussed already, or we will discuss in next articles.

Today we will focus on numbers and the Number object in JavaScript, take a look closer at calculations and Math object in JavaScript.

JavaScript Number Object

It is a primary object to handle numbers, and has properties for numerical constants:

var maxNumber = Number.MAX_VALUE;
var minNumber = Number.MIN_VALUE;
var infinity = Number.POSITIVE_INFINITY;
var minusInfinity = Number.NEGATIVE_INFINITY;
var isNotANmber = Number.NaN;

Methods of the Number object:

Scientific notation, digits parameter determines decimal places:

number.toExponential([digits]);

Decimal notation:

number.toFixed([digits]);

Determination of precision:

number.toPrecision()

Example — precision after the decimal point:

var number = new Number(51.967654321);
number.toPrecision(5); // result: 51.968

The next method returns a number as a string. The ‘base’ parameter specifies the number system (default, 2, 8, 16):

number.toString([base])

The valueOf method returns a fundamental value represented by the Number object (stored value):

number.valueOf()

Gets a float value from expression (string):

number.parseFloat(string)

OOP in JavaScript part 2. Summary.

Part 2. of the OOP in JavaScript. Today we will show some more advanced examples.

OOP in JavaScript — techniques

For a good start, let’s take a closer look at arrays.

Arrays as objects

A simple array, e.g.:

var t = new Array("a","b","c");

can be written in a concise form:

var t = ["a","b","c"];

And certainly we can operate on arrays in the same way as we operate on other objects, by using methods and properties.

Examples of typical operations for arrays in JavaScript:

tab.push("x"); // adding an element

alert(tab.pop()); // getting an element

// deleting the element at a given index
var index = 0;
delete tab[index];

Associative arrays

Well-known in PHP, associative arrays can be created in JavaScript in create a fairly pleasant way:

var numbers_object = {
    '0': 'zero', '1': 'one', '2': 'two',
    '3': 'three', '4': 'four', '5': 'five',
    '6': 'six', '7': 'seven', '8': 'eight',
    '9': 'nine'
};

alert(numbers_object[7]);

Objects management

I don’t mean that the Garbage Collector will be replaced by us, rather about the opportunities that we have, if we want to control our objects.

Object-oriented programming in JavaScript. OOP part 1.

Welcome to the first part of the articles about object-oriented programming (OOP) in JavaScript. It is actually necessary to explore of the language secrets.

Object-oriented programming in JavaScript

JavaScript is an object-oriented language, although there is a lack of certain elements typical for object-oriented languages, at least in the current implementations of JavaScript.

But let’s get to the specifics.

Almost everything in JavaScript can be treated as an object (arrays, dates, strings, etc).

We can write either:

var text = "Hello World";

and:

var text = new String("Hello World");

In short, objects are data (specific type), which have properties and methods.

Properties are values ​​associated with the objects, whereas methods are related actions (functions) that can be performed on those objects.

Examples of properties:


text.length; // get

myCar.name = 'VW'; // set

Examples of methods:


text.indexOf("World");

myCar.drive();

Creating objects

Now we will create an object of a new type. We will do this by defining a function, where we implement the properties and methods for the objects of our new type.

Classes? I deliberately didn’t want to use the term. In typical object-oriented languages, ​​class is something like a recipe for creating objects. Usually a class is defined using the class keyword.

As mentioned in basics of JavaScript, there is a reserved keyword class — for future compatibility.

Then would be possible for following “class”:

function Employee() {
    this.name = "";
    this.dept = "IT";
}

could be written in Java style:

public class Employee {
    public String name;
    public String dept;

    public Employee() {
        this.name = "";
        this.dept = "IT";
    }
}

But for now, let’s back to the current JavaScript language. Function shown below can be considered as a class (or rather the class equivalent). It is a way to simplify the course of thinking.

Example — definition of a function (“class”) and creating an object:

function niceCar() {
  // properties
  this.name = '';
  this.speed = 0;

  // a method
  this.getSpeed = function() {
    return this.speed;
  };

  // another way to write
  this.accelerate = Accelerate;

  function Accelerate() {
    this.speed++;
  }
}

var myCar = new niceCar();
myCar.name = 'VW';

alert(myCar.name); // VW
alert(myCar.getSpeed()); // 0

Thus, it looks like the creation of a standard function: function myClass() {}.

The difference lies in the fact, that it will be called for the creation of a new object: the new operator.

Regular expressions in JavaScript

Today we will discuss one of the slightly more difficult topics, namely regular expressions. Of course, really difficult are the most powerful and advanced expressions. However, possibilities offered by this tool are really huge.

Regular expressions in JavaScript

Regular Expressions are a way to save a pattern, which can be compared with strings, to check whether a string matches the specified pattern (also for searching substrings, replacing matched elements, verification, etc).

For example, you can specify a list of characters that may appear in some position:

// after "a" letter must appear a digit from 0 to 7:
a[01234567]

So if after “a” letter one of listed digits will appear, then the pattern will be matched.

There are also short versions i.e. with specifying ranges: a[0-7], [a-z], [A-Z], etc.

The list can be negated using the “^” char:

[^0-9a-zA-Z]

Special sequences

There are special sequences, replacing the predefined character sets:

– \d — any digit: [0-9]
– \D — any char (not a digit): [^0-9]
– \w — any digit, a letter (lowercase or capital) or underscore: [0-9a-zA-Z_]
– \W — any character which is not a digit, a letter, and an underscore: [^0-9a-zA-Z_]
– \s — any whitespace: [ \t\r\n\v\f]
– \S — any non-whitespace: [^ \t\r\n\v\f]

Special chars:

– \t — horizontal tab character (0x09)
– \v — vertical tab character (0x0B)
– \r — “carriage return” (0x0D)
– \n — new line (0x0A)
– \f — page break (0x0C)

Repetition of pattern

Sometimes a piece of the pattern should be repeated. And there are special qualifiers for this, and they determine how many times the pattern can (or must) repeat.

Date and time in JavaScript

The time flies, and we will write about date and time in JavaScript. Today less theory, more practical examples.

Date and time in JavaScript. The Date object.

To handle dates in JavaScript there is an object called Date.

Basic example:

var data = new Date();
document.write(data.getDate());

The Date object — methods

Methods of the Date object:

data.getDay(); // day number 0-6
data.getFullYear(); // 1000-9999
data.getHours(); // current hours on the computer
data.getMiliseconds(); // the number of milliseconds
data.getMinutes(); // minutes
data.getMonth(); // months (0-11)
data.getSeconds(); // seconds

// conversion into a readable string:
data.toDateString();
data.toLocaleDateString();
data.toLocaleString();
date.toString();

Tip: use instanceof

With this operator we can check whether we are dealing with an object of some type. For example let’s check if we are operating on the Date object instance:

var my_date = new Date();
alert(my_date.getDate());

// is the 'my_date' an instance of Date?
alert(my_date instanceof Date);

Setting the date

By creating a Date object, we can specify (to set) the date, and this in several ways:

var today = new Date();
var birth = new Date("March 27, 1986 05:24:00");
alert(birth);

// or
var birth = new Date(1986,03,27);
var birth = new Date(1986,03,27,5,24,0);

As you can see, we can set only the date, or date and hour. We can also set the date through dedicated methods:

var dt = new Date();
dt.setFullYear(2012,02,12);

This code sets: year, month and day.

In contrast, here:

var dt = new Date();
dt.setDate(dt.getDate() + 10);

… we set a future date (10 days ahead).

Other examples

Example — measuring the execution time:

var start = Date.now();
// … code to measure…
alert('test');
// … end: code to measure…

var stop = Date.now();
var diff = stop — start; // time in milliseconds

Example — comparison of dates using the Date object:

var cmpDate = new Date();
cmpDate.setFullYear(2020,2,25);
var today = new Date();

// comparing
if (cmpDate > today) {
  alert("Future");
} else {
  alert("Past");
}

Simple and effective way.

Example — current time:

function getTime() {
    var now = new Date();
    var result = now.getHours() + ":" + now.getMinutes();

    return(result);
}
alert("It's " + getTime());

Example — building a readable date:

var tm = new Date();
var resTxt = '';
resTxt += "We have now " + tm.getHours() + ":"
  + tm.getMinutes() + ":" + tm.getSeconds() + ", ";

resTxt += " of day: " + tm.getDate() + "." + (tm.getMonth() + 1)
  + "." + tm.getFullYear();

alert(resTxt);

Mastering bitwise operators in JavaScript. Like a boss!

Bitwise operators in JavaScript

Today we will try to present bitwise operators in JavaScript language, in an accessible form.

The overall concept of the bitwise operators’ work in JavaScript is as follows:

– arguments are converted to 32-bit integer and expressed by a sequence of bits,

– each bit in the first argument is matched to the corresponding bit in the second operand,

– operator is used for each pair of bits, and the result at this level is bitwise.

Among the bitwise operations we distinguish:

– bitwise product (and, operator &),

– bitwise sum (or, operator |),

– negation (not, operator ~),

– symmetric difference (xor, operator ^).

We can see similarities to the logical operators.

The difference is that bitwise operators works not on logical values, or even on the values ​​directly, but at lower level — on the individual bits of a number.

Bitwise operators treat their arguments as a set of 32 bits (ones and zeros), and not as decimal or hexadecimal.

For example, a binary representation of the decimal number of 10 is 1010.

Bitwise operators perform their operations on such binary representations, but they return standard JavaScript numerical values​​.

JavaScript bitwise operators — a cheatsheet

ANDa & bOnly 1 and 1 gives a score of 1, the rest 0
ORa | b1 anywhere gives a score of 1, 0 and 0 gives the result 0
XORa ^ bReturns 1 in a position where only one of the arguments is equal 1, 1 and 1, 0 and 0 gives 0
NOT~ aReverses (negate) bit operand
<<a << bBitwise left shift
>>a>> bBitwise right shift
>>>a>>> bZero-fill right shift

Interesting issues and good practices in JavaScript

Welcome to the first, but certainly not the last topic of this type, which touches interesting features of JavaScript, tricks and less common structures, like the with instruction.

Interesting issues and good practices in JavaScript

For a good start: Tip #1 — the ‘with’ instruction

The with instruction, being a part of JavaScript language, allow us to determine the object, to which we will refer inside a “body” defined for this instruction. This can greatly simplify the code.

This is illustrated by the following example:

var a, b, c;
var r = 5;

with (Math) {
    // here by default are called methods and properties
    // of the Math object
    a = PI * r * r;
    b = r * cos(PI);
    c = r * sin(PI / 2);
}

alert(a + " - " + b + " - " + c);

Thus, in this example we don’t need to specify name of the Math object, each time a property or method of the object is called. For example sin() instead of Math.sin().

Tip #2 — escape and unescape functions

These functions encodes and decodes string values:

escape — returns the hexadecimal encoding of an argument for special characters; in other words encodes the string to a portable form, that can be freely transmitted through the network,

unescape — returns the string as ASCII; decodes the values encoded by the escape function.

These functions are often used on server side. JavaScript encodes and decodes names / value pairs in the URL.

var str = 'JS? Go to https://javascript-html5-tutorial.com/';
alert(escape(str));
// JS%3F+Go+to+http%3A%2F%2Fjavascript-html5-tutorial.com%2F

Tip #3 — Fast testing

With the help of logical operators, we can perform a quick test expressions:

false && some_expression is an acronym for executing the false expression;

true || some_expression is an acronym for executing the true expression;

For example:

var x = 1;
if (false && x > 0) alert('Debug: 0');
if (true || x > 0) alert('Debug: 1');

// -> Debug: 1

Tip #4 — select the text box

So it’s a simple implementation of the ‘Select all’ function. In this case for the textarea field.

<form>
  <textarea name="text" cols="30" rows="2">Here is the text
  </textarea>

<input onclick="java_script:this.form.text.focus();
  this.form.text.select();" type="button" value="Select">

</form>

JavaScript DOM. Next step — we explore DOM and BOM.

It’s time to take a step forward. We explore DOM and BOM (Browser Object Model, don’t confuse with Byte Order Mark).

JavaScript DOM

We will meet with DOM many times. The topic is extensive, but definitely it’s one of the most interesting things in JavaScript.

Moreover, thanks to the operations of the DOM we have big possibilities at the level of our code.

DOM (Document Object Model) — presents the document (current page) so that JavaScript sees document as an object. DOM is a set of methods and fields that allow you to add, delete, find and change the items.

The document object — collections:

anchors[]forms[]
images[]links[]

The document object — properties:

cookiedocumentMode
domainlastModified
readyStatereferrer
titleURL

The document object — methods:

close()getElementById()
getElementsByName()getElementsByTagName()
open()write()
writeln()

BOM (Browser Object Model) — it’s much less common term than DOM. In this sense we have objects related with the browser window.

So DOM refers to the document in browser window, and BOM refers to the browser (the window object in JavaScript).

JavaScript — window object properties:

closedouterWidth
defaultStatuspageXOffset
documentpageYOffset
framesparent
historyscreen
innerHeightscreenLeft
innerWidthscreenTop
lengthscreenX
locationscreenY
nameself
navigatorstatus
openertop
outerHeight