Load content when scrolled – AJAX, Javascript, PHP & MySQL

In this tutorial, we are going to teach you how you can load the content of div only when user scrolled to that section. For example, you have a lot of dynamic sections in your website, loading them all using PHP is very costly since server has to get a lot of data from database and it will make your website load slower.

Get data using AJAX

Second option was to load all data using AJAX, this will solve the first problem because the website will be loaded instantly and all the sections where dynamic data needs to be displayed will send an AJAX request to get that data and display in relevant section using Javascript.

However, take this example, if your website has 10 sections and users mostly use the first 3 sections. This means that the server is serving 7 extra requests which are not commonly being used by client. It will slowdown the server, possibly crash your website if you have a lot of users. What if we find a way of optimization such that the relevant section will only be loaded when required by user.

How it works

Simply means, request of section will be sent to server only when asked by client to get that data. If user is on first 3 sections, then the ajax will be called only 3 times and server will be serving only 3 requests. Request for section 4 will only be served if user moved or scrolled to that section, otherwise it will not be loaded. It will greatly optimize your website and make it load faster and more responsive.

This tutorial is written in pure Javascript, no jQuery or any other external library has been used. So you can use this tutorial under all Javascript and PHP frameworks.

We have created a sample database called “classicmodels” from where we are going to load the data from 4 tables:

  1. customers
  2. employees
  3. offices
  4. products

The important question here is “How am I going to know when user has scrolled to some div ? And how can I tell the server to get data required in that div ? And how to display it in relevant div ?”. For this, we are going to use Javascript built-in IntersectionObserver object, basically it observes all the nodes in the intersection.

Intersection Observer

Intersection is a visible area in browser, when you open any website, the content which is visible to you is in Intersection. So we are going to add all divs which needs to be loaded dynamically under observation. Once that div intersects, we are going to send a simple AJAX request using Javascript (no jQuery), telling the server what type of data we need and then display the data in that div.

Server side (PHP)

Paste the following code in your server side or back-end PHP file, we have named it “Http.php“. Make sure to change the database credentials.

<?php
	// File name = Http.php

	// Get data from database

	if (isset($_GET["type"]))
	{
		// Connecting with database
		$conn = mysqli_connect("localhost", "root", "", "classicmodels");

		// Just for testing, set a delay for 2 seconds
		sleep(2);

		// Getting all results from relevant table
		// you can perform different queries for each div using $_GET['type'] variable

		$type = $_GET["type"];

		$result = mysqli_query($conn, "SELECT * FROM " . $type);
		$data = array();

		while ($row = mysqli_fetch_object($result))
		{
			array_push($data, $row);
		}

		// Sending response back
		// we also need to send the type back
		echo json_encode(array(
			"data" => $data,
			"type" => $type
		));
		exit();
	}
?>

Client side

Paste the following code in your client side or front-end. Make sure to change the IDs of divs as per your project. Also set server file name as per yours at line 13.

<!-- Create divs which needs to be loaded by ajax -->
<div id="customers" class="loaded-by-ajax"></div>

<div id="employees" class="loaded-by-ajax"></div>

<div id="offices" class="loaded-by-ajax"></div>

<div id="products" class="loaded-by-ajax"></div>
<script>
	// Create observer
	var ajaxObserver = new IntersectionObserver(function (items, self) {
		// Loop through all items in visible area
		for (var a = 0; a < items.length; a++) {
			// Check if div under observation is in visiable area
			if (items[a].isIntersecting) {
				// Get ID
				var id = items[a].target.id;
				
				// Call ajax to get data
				var ajax = new XMLHttpRequest();
				ajax.open("GET", "Http.php?type=" + id, true);

				// Show loading in relevant div before ajax
				document.getElementById(id).innerHTML = "Loading..." + id;

				// This event will be called for each request change status
				ajax.onreadystatechange = function () {
					// Response is received when ready state is 4 and status is 200
					if (this.readyState == 4 && this.status == 200) {
						// Convert JSON string into arrays and objects
						var response = JSON.parse(this.responseText);

						var data = response.data;
						var type = response.type;

						var html = "";
						// Each div might have different layout

						if (type == "customers") {
							html += "<h1>Customers</h1>";

							// Loop through all items
							for (var b = 0; b < data.length; b++) {
								html += "<p>" + data[b].customerName + "</p>";
							}
						} else if (type == "employees") {
							html += "<h1>employees</h1>";

							// Loop through all items
							for (var b = 0; b < data.length; b++) {
								html += "<p>" + data[b].firstName + " " + data[b].lastName + "</p>";
							}
						} else if (type == "offices") {
							html += "<h1>offices</h1>";

							// Loop through all items
							for (var b = 0; b < data.length; b++) {
								html += "<p>" + data[b].city + "</p>";
							}
						} else if (type == "products") {
							html += "<h1>products</h1>";

							// Loop through all items
							for (var b = 0; b < data.length; b++) {
								html += "<p>" + data[b].productName + "</p>";
							}
						}

						// Render the relevant div
						document.getElementById(type).innerHTML = html;
					}
				};

				// Sending the ajax request
				ajax.send();

				// Prevent the div from being observed again
				self.unobserve(items[a].target);
			}
		}
	});

	// Add all loaded-by-ajax divs in observation list
	var loadedByAjax = document.getElementsByClassName("loaded-by-ajax");
	for (var a = 0; a < loadedByAjax.length; a++) {
		ajaxObserver.observe(loadedByAjax[a]);
	}
</script>

That’s how you can load content only when scrolled using Javascript’s “IntersectionObserver”.

Learn how to do the same for images.

Lazy load images – Javascript

[wpdm_package id=’251′]

Deploy Node JS app on Heroku

When it comes to deploy Node JS app, Heroku is by far the most feasible choice for beginners and startups. In this tutorial, we are going to teach you how you can deploy your Node JS application on Heroku and make it accessible from everywhere.

It is very common when we start building our Node JS apps, we mostly work on our localhost for faster testing. But when there is a time to make it live or connect it with your android or iOS application, you definitely need to publish it on some hosting provider. Heroku in this regard will help us to publish our Node JS app on their server.

Let’s get started

We are going to create a simple “Hello world” app in Node JS and publish it on Heroku.

First create a new folder where we will place all our Node JS files. If you are already working on some Node JS project, then you can use your existing folder too. Create a file named “server.js”, this will be our main server file. Open the command prompt in your project and initialize NPM in it, make sure you have Node JS installed in your computer. You can download Node JS from here:

cd "your_project_root_folder"
npm init

Install modules

Install express and Http modules in your project, they will be used to start the server at a specific port. After installation, we are going to start the server using nodemon command. If you do not have nodemon, you can install it by running “npm i nodemon” in your terminal. Run the following command in your terminal to install express & Http modules and start the server:

npm install express http
nodemon server.js

Now we will create instances of express and Http modules and start the server at port 3000. Specifying the port will work on the localhost, but when we deploy any app on Heroku, Heroku automatically assigns some port number from itself and save that port number in the “process” object’s “env” object. So we will add an OR operator to set port number if it is being received from Heroku, otherwise (if in localhost) start at 3000. Paste the following code in your server.js file:

var express = require("express");
var app = express();
var http = require("http").createServer(app);

http.listen(process.env.PORT || 3000, function () {
	app.get("/", function (request, result) {
		result.send("Hello world !");
	});
});

If you test the app now at URL “http://localhost:3000/” you will see a “Hello world !” message. Now we need to deploy on Heroku, goto Heroku and login or signup if you have’nt already created an account.

Deploy Node JS on Heroku

Now download and install the Heroku CLI. Run the following command in your terminal to login, it will open the browser, just hit “Login” in opened web page. Also make sure that you have Git installed too, you can download it from here:

heroku login

// Initialize a Git repository
git init

// Point remote address towards your Heroku app
heroku git:remote -a your-app-name

// Add all files in Git
git add .

// Commit all files
git commit -am "Initial commit"

// Deploy all files on Heroku
git push heroku master

After the final command, you will see a link of your app which you can use to run directly in the browser. Moreover, in your Heroku dashboard, you can click on “Open app” button and it will take you to your app’s home page.

Learn how to deploy Node JS app with Mongo DB and Vue JS from here.

Disable scroll on input type number – Javascript

Ever come across a problem where you enter some value in input type number and while you scroll down or up, you will see that the value of that input field is changed. It is because of the default behavior of the browser, it increments or decrements the value of input fields having “type” attribute valued as “number” as long as the user is scrolling inside that input field. So, let’s learn how to disable scroll on input type number for these situations.

However, there are multiple ways to prevent this behavior. But the simplest solution we came across is by removing the focus from that input field as long as the user is scrolling inside that input field. We are calling it “simplest” because it does not even need jQuery.

yes NO JQUERY !!!

Just paste the following code at the end of the file where you want to disable this scrolling behavior:

var inputTypeNumbers = document.querySelectorAll("input[type=number]");
for (var a = 0; a < inputTypeNumbers.length; a++) {
	inputTypeNumbers[a].onwheel = function (event) {
		event.target.blur();
	};
}

Explanation

querySelectorAll will return all the nodes that matches the selector passed in as an argument. We are selecting all input fields which have a field attribute having value as “number”. This will return an array which we can use to loop through all nodes.

Next, we are looping through all input type numbers and inside this loop. We can perform a specific action on each node. We are overriding onwheel event, which is called whenever we move the mouse wheel inside the input field. In this event, we are receiving a variable from parameter named as “event”. It contains all the functions and attributes of this event.

We have an object named “target” in this event object which holds the actual input field node. Although we can use the “inputTypeNumbers[a]” inside the function event, it is better to use the event.target object. All input fields in HTML5 have a function named “blur()” which removes the focus from that input field. Calling this function will remove the focus from that input field and thus the scrolling of numbers will not occur.

That’s how you can disable scroll on input type number using Javascript’s “onwheel” event.

Detect page leave – HTML & Javascript

Preview image from input type file before upload – Javascript

In this article, we will learn how to preview image before upload from input type file using Javascript. A FileReader object is used.

The following code will display an input type file from where the user can select an image file. As soon as he selects the image, it’s preview will be displayed in an image tag. This is useful when you want to show the user the image he selected, before saving it in the database. So the user must know that he has picked the correct image.

<script>
	function previewImage() {
		var file = document.getElementById("file").files
		if (file.length > 0) {
			var fileReader = new FileReader()

			fileReader.onload = function (event) {
				document.getElementById("preview").setAttribute("src", event.target.result)
			}

			fileReader.readAsDataURL(file[0])
		}
	}
</script>

<form method="POST" action="/" enctype="multipart/form-data">
	<input type="file" name="file" id="file" accept="image/*" onchange="previewImage();">

	<img id="preview">
</form>

Explanation

Form encoding type will be used to upload the file on the server-side (PHP). Give your input type file a unique ID so it can be accessed in Javascript. We have created an image tag where a preview of the selected file will be displayed. Give a unique ID to this image tag too. A function on onchange event on input type file will be called whenever user select some file from dialog. We are also adding an attribute accept=”image/*” that will make sure that the user selects only the image files like JPEG, PNG etc.

In this function, first we are checking if the user has selected any file. We are creating a FileReader object, it is used to read the file. With this file reader object, we are calling a function named readAsDataURL, it will read the content of a file as URL. That URL will be used to set the “src” attribute of our image tag.

onload event will be called when the file is fully read by file reader object. In this function, we are simply setting the “src” attribute of our image tag. event.target refers to the original file reader object and “result” is the actual URL of selected file.

Since you have learned how you can preview an image before upload from input type file using Javascript. Learn also how to upload, download and delete files in PHP.

[wpdm_package id=’247′]

Upload file along with other input fields – Node JS

So we are going to teach you how you can upload the file from HTML form along with other input fields in Node JS. We will be using NPM’s formidable, fs (file system) and EJS modules. We will create an input type file to select a file from computer and input type text, the file will be store in server with the name I enter in text box.

Let’s get started

Open command prompt in your project’s root folder and run the following command to install necessary modules:

npm install express http formidable fs ejs
  • Express and HTTP will be used to start the server
  • formidable will be used to handle the input file
  • fs (file system) will be used to save the file
  • EJS will be used to render the HTML page

Now create a file named index.js and paste the following code in it:

var express = require("express");
var app = express();
var http = require("http").createServer(app);
var formidable = require("formidable");
var fs = require("fs");

app.set("view engine", "ejs");

http.listen(4000, function () {
	app.get("/", function (request, result) {
		result.render("index");
	});
});

It will start the server at port number 4000 and creates a default route which when access will render the index.ejs page. We will create that file in a moment. We are setting the default template engine to EJS, don’t worry if you are using any other engine, the core login will remain the same.

Start the server

To start the server, simply run the following command in your command prompt which should be opened in your project’s root folder:

npm install -g nodemon
nodemon index.js

Now you can access your server by running the following URL in your browser:
http://localhost:4000/

Display input type file

Now create a folder in your project named “views”. Your all HTML files should be placed inside this folder and all files must end with an extension .ejs. Create a file named index.ejs inside this views folder. The name of the file must be the same as in render function above, along with .ejs extension at the end. Paste the following code in that file. It will create a form with an input field to select a file and an input field to enter text. We will save the uploaded file with the name entered in text box.

<form method="POST" action="/upload" enctype="multipart/form-data">
	<input type="file" name="file">
	<input type="text" name="fileName" placeholder="File name">

	<input type="submit">
</form>

Save file on server

Make sure the method is POST and encoding type must be attached, otherwise, the file will not be sent. Action attribute will specify the route where data should be sent. So paste the following code in your index.js file right below the “/” route:

app.post("/upload", function (request, result) {
	var formData = new formidable.IncomingForm();
	formData.parse(request, function (error, fields, files) {
		var extension = files.file.name.substr(files.file.name.lastIndexOf("."));
		var newPath = "uploads/" + fields.fileName + extension;
		fs.rename(files.file.path, newPath, function (errorRename) {
			result.send("File saved = " + newPath);
		});
	});
});

Now you just need to create a folder named “uploads” and when you select the file. Enter the name, the file will be saved with the name you enter in the text field. That’s how you can upload a file on Node JS server.

[wpdm_package id=’245′]

PHP – Subscribe to Newsletter and send Bulk Emails using PHPMailer

A newsletter is a printed or electronic report containing news concerning the activities of a business or an organization that is sent to its members, customers, employees or subscribers. Newsletters generally contain one main topic of interest to its recipients. In this article, we will discuss you how can send bulk emails using the PHP Mailer library.

Newsletter

Newsletters in websites are used in the form of E-mails and they are the most common type of emails in email marketing. They often contain news and updates, aiming to keep the audience engaged. At the same time, they are also designed to gently push users towards the conversion.

We are going to create a form that will help users to subscribe to the newsletter on your website and you will be able to send bulk emails to all those users. You can send promotional emails to promote your product or you can mail to them whenever you have a new post or news regarding your business, organization or website.

<form onsubmit="return doSubscribe();">
	<input type="email" id="subscriberEmail" placeholder="Subscribe to newsletter" required>

	<input type="submit" value="Subscribe">
	<p id="subscribe-message"></p>
</form>

This will create a form with an input field to type email and a submit button which when clicked will submit the form. We are preventing the default behavior of form submission by attaching an event listener called “onsubmit”. This function will be called when the user hits the submit button. We need to prevent the form from submitting and call our AJAX function to save this email in the MySQL database using PHP. At the end we have a paragraph, it will be used to display a message when the email has successfully been stored in the database.

Send an ajax request

<script type="text/javascript">
	function doSubscribe() {
		var subscriberEmail = document.getElementById("subscriberEmail").value;
		
		var ajax = new XMLHttpRequest();
		ajax.open("POST", "subscribe-newsletter.php", true);
		ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		
		ajax.onreadystatechange = function () {
			if (this.readyState == 4 && this.status == 200) {
				document.getElementById("subscribe-message").innerHTML = "You have been subscribed to our newsletter.";
			}
		};

		ajax.send("subscriberEmail=" + subscriberEmail);
		return false;
	}
</script>

Here first we have created a Javascript function and we are returning false from it, this will prevent the form from submitting. We are getting the input field value for email using the input field’s unique ID. Then we have created an AJAX object that can be used to send an asynchronous AJAX request. Next, we are calling open function and setting method to “POST”, the second parameter is the name of the file where data needs to be sent and the third parameter is whether the request is asynchronous.

Asynchronous

All modern browsers support asynchronous, so we are setting this to true. As the request is POST, so we also have to attach headers to this request. For application/x-www-form-urlencoded, the body of the HTTP message sent to the server is essentially one giant query string — name/value pairs are separated by the ampersand (&), and names are separated from values by the equals symbol (=).

Before actually sending the request, we are attaching an event listener which will be called when a response is successfully been received from the server. The request is successful if the readyState is 4 and status has a value of 200. When the request is completed, we are simply displaying a message in the paragraph so the user can know that his email has been added in the subscriber’s list.

Save email in MySQL using PHP

Next, we need to create a PHP file that will store this email in MySQL database. First, create a table in your MySQL database and name it “subscribers”. It will have 1 column as auto-increment primary key whose value be unique for each subscriber and its data type should be an integer. It will also have another column for email whose value will be subscriber’s email and its data type should be text.

Save data in MySQL database

Create a new file named “subscribe-newsletter.php” and paste the following code in it. Make sure to change the database credentials as per your database.

<?php

	$conn = mysqli_connect("localhost:8889", "root", "root", "tutorials");
	$subscriberEmail = $_POST["subscriberEmail"];

	mysqli_query($conn, "INSERT INTO subscribers (email) VALUES ('$subscriberEmail')");

?>

Send bulk emails using PHP Mailer

Many PHP developers need to send email from their code. The only PHP function that supports this is mail(). However, it does not provide any assistance for making use of popular features such as encryption, authentication, HTML messages, and attachments.

The PHP mail() function usually sends via a local mail server, typically fronted by a Sendmail binary on Linux, BSD, and macOS platforms, however, Windows usually doesn’t include a local mail server; PHPMailer’s integrated SMTP implementation allows email sending on Windows platforms without a local mail server.

Install PHPMailer

Open command prompt (Windows) or Terminal (Mac OS) in your project’s root folder and run the following command:

composer require phpmailer/phpmailer

It will install the PHPMailer library in your project. You will see a folder named “vendor” will be created at the root folder of your project. Open the file from where you want to send emails to all your subscribers. And paste the following code in it:

<?php

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

$conn = mysqli_connect("localhost:8889", "root", "root", "tutorials");

$result = mysqli_query($conn, "SELECT * FROM subscribers");
while ($row = mysqli_fetch_object($result))
{
	$mail = new PHPMailer(true);

	try {
	    $mail->SMTPDebug = 0;
	    $mail->isSMTP();
	    $mail->Host       = 'smtp.gmail.com';
	    $mail->SMTPAuth   = true;
	    $mail->Username   = 'adnan@gmail.com';
	    $mail->Password   = '';
	    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
	    $mail->Port       = 587;

	    $mail->setFrom('adnan@gmail.com', 'Adnan');
	    $mail->addAddress($row->email);     // Add a recipient
	    $mail->addReplyTo('adnan@gmail.com', 'Adnan');

	    // Content
	    $mail->isHTML(true);
	    $mail->Subject = 'Here is the subject';
	    $mail->Body    = 'This is the HTML message body <b>in bold!</b>';
	    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

	    $mail->send();
	    echo '<p>Message has been sent to ' . $row->email . '</p>';
	} catch (Exception $e) {
	    echo "<p>Message could not be sent. Mailer Error: {$mail->ErrorInfo}</p>";
	}
}

Here first we are importing PHPMailer library files. Then we are including our “autoload.php” file, it should be automatically created when the composer command is executed. Then we are connecting with the database and fetching all the subscribers from the table. In each loop iteration, we are creating an object of PHPMailer class. Setting the host as Gmail and username and password as one of our Gmail account’s credentials. You need to enter the correct email and password of one of your Gmail account.

Enable google less secure apps

Make sure to enable “less secure apps” for your corresponding Gmail account. You can do that from this link or by tapping the screenshot below.

Set the port number to “587” it is the default for Gmail. Set your email address from where the email should be sent. And the recipient address which we will be receiving from the database. Then we are setting the subject and body of email, the body of the email can contain HTML content. But you can also specify non-HTML content in “AltBody” if the user switches to simple text format. Or if the user has a slow internet connection. Finally, we send the mail and display a confirmation message that an email has been sent. If there is any error, it will be handled in the catch block. We are also displaying an error message if there is any problem in sending en E-mail.

Apply CSS on form

Although your subscription form design will be different for everyone else as per your website’s existing design. But for the sake of simplicity, we are applying some CSS styles just to make it look a little bit good. First, change your form layout and enclose your input field and submit button inside div tag having class as “container”. We will apply styles based on this class.

<form onsubmit="return doSubscribe();">
	<div class="container">
		<h2>Subscribe to our Newsletter</h2>
		<p>Lorem ipsum..</p>
	</div>

	<div class="container" style="background-color:white">
		<input type="email" id="subscriberEmail" placeholder="Subscribe to newsletter" required>
	</div>

	<div class="container">
		<input type="submit" value="Subscribe">
	</div>

	<p id="subscribe-message"></p>
</form>

Next we are going to use the CSS to apply styles on those divs and classes.

<style type="text/css">
	/* Style the form element with a border around it */
	form {
		border: 4px solid #f1f1f1;
	}

	/* Add some padding and a grey background color to containers */
	.container {
		padding: 20px;
		background-color: #f1f1f1;
	}

	/* Style the input elements and the submit button */
	input[type=text], input[type=email], input[type=submit] {
		width: 100%;
		padding: 12px;
		margin: 8px 0;
		display: inline-block;
		border: 1px solid #ccc;
		box-sizing: border-box;
	}

	/* Add margins to the checkbox */
	input[type=checkbox] {
		margin-top: 16px;
	}

	/* Style the submit button */
	input[type=submit] {
		background-color: #4CAF50;
		color: white;
		border: none;
		cursor: pointer;
	}

	input[type=submit]:hover {
		opacity: 0.8;
	}
</style>

Now you have learned how you can send bulk emails using PHP Mailer library. You can also learn how to send email with attachments in PHP from here.

[wpdm_package id=’243′]

PHP – Add Dynamic Rows in Table Tag

Learn how to add dynamic rows in a table tag in HTML and Javascript. And also save the data in MySQL database using PHP.

Introduction

Suppose you are trying to generate an invoice for your customers. You wanted to have a functionality where you will be able to add multiple items in an invoice. A simple table tag will be created from where the user will be able to add multiple items. You have added a button labeled as “Add Item” which when clicked will create a new row to add an item.

Now it might sound easy but technically you have to create rows dynamically. Whenever a user clicks on the “Add Item” button, a new row inside table tag should be created and it must be an array as items can be multiple. Then these arrays should be stored in the database using a loop iteration. Following this tutorial, you will be able to do so.

We will be creating 2 tables, although to explain this tutorial only 1 table would be enough but teaching with 2 will help to understand better when you are working on existing projects. We will have 1 table for storing invoices basic data, for example, customer name, etc, and the second table for storing items in that invoice.

“invoices” table

Our first table name is “invoices” and it will have just 2 fields, unique auto-increment ID and customer name. And the second table will be named “items” and have the product name, quantity, etc and also a foreign key that reference for invoice ID.

To add dynamic rows, we are using a <table> tag that will create a table layout so we will add rows in <tbody> tag. As discussed earlier, all rows will be in an array that needs to be stored in the database, so we will create a <form> tag that will help to do this. We are setting the method to POST as the data might be sensitive and long, and action attribute as current file name, you can change this if you want to send data to a different page.

Customer field

We are creating a simple input field for customer name that will be stored in the “invoices” table, you can place your other fields here. Then we are creating a <table> tag and inside it, we will be displaying the number of items, item name, and item quantity. Make sure to give <tbody> tag a unique ID so we can append new rows in it using Javascript.

Below them, we are creating a button which when clicked will call a Javascript function from where we can add a new row inside that table. And finally, a submit button which when clicked will submit the form and we have to save that data in database.

<form method="POST" action="index.php">
	<input type="text" name="customerName" placeholder="Enter customer name" required>

	<table>
		<tr>
			<th>#</th>
			<th>Item Name</th>
			<th>Item Quantity</th>
		</tr>
		<tbody id="tbody"></tbody>
	</table>

	<button type="button" onclick="addItem();">Add Item</button>
	<input type="submit" name="addInvoice" value="Add Invoice">
</form>

Add/delete row

Now we need to create a function which when clicked will add a new node in the <tbody> tag. We have created a variable for the number of items and we are incrementing it on each click. Whenever this function called we are creating a <tr> tag and adding input fields for name and quantity in <td> tags. Notice the “[]” with the input name attribute, this tells that this field will be an array. Lastly, we are creating a new row using tbody function called insertRow() and appending the <tr> HTML in it.

<script>
	var items = 0;
	function addItem() {
		items++;

		var html = "<tr>";
			html += "<td>" + items + "</td>";
			html += "<td><input type='text' name='itemName[]'></td>";
			html += "<td><input type='number' name='itemQuantity[]'></td>";
            html += "<td><button type='button' onclick='deleteRow(this);'>Delete</button></td>"
		html += "</tr>";

		var row = document.getElementById("tbody").insertRow();
		row.innerHTML = html;
	}

function deleteRow(button) {
    items--
    button.parentElement.parentElement.remove();
    // first parentElement will be td and second will be tr.
}
</script>

Style the table

Now we are going to apply some styles on our table just to make it look a little bit good.

<style type="text/css">
	table {
		width: 100%;
		border-collapse: collapse;
	}
	table tr td,
	table tr th {
		border: 1px solid black;
		padding: 25px;
	}
</style>

Add record in database

Now we just need to store this data in our database. The following code must be put at the top of your file. Our database name is “tutorials” but it will be different in your case, make sure to change the DB name accordingly. Next, check if the form is submitted, the if block will only run after the user submits the form. Get the customer name and insert that in the “invoices” table, it is rather simple.

Remember we added “invoiceId” as a foreign key in “items” table. So, we have to get the newly inserted AUTO-INCREMENT ID. Then we are looping through all the added items. You can either use the “itemName” input field or “itemQuantity” and insert them in “items” table with same invoice ID.

<?php

	$conn = mysqli_connect("localhost:8889", "root", "root", "tutorials");

	if (isset($_POST["addInvoice"]))
	{
		$customerName = $_POST["customerName"];

		$sql = "INSERT INTO invoices (customerName) VALUES ('$customerName')";
		mysqli_query($conn, $sql);
		$invoiceId = mysqli_insert_id($conn);

		for ($a = 0; $a < count($_POST["itemName"]); $a++)
		{
			$sql = "INSERT INTO items (invoiceId, itemName, itemQuantity) VALUES ('$invoiceId', '" . $_POST["itemName"][$a] . "', '" . $_POST["itemQuantity"][$a] . "')";
			mysqli_query($conn, $sql);
		}

		echo "<p>Invoice has been added.</p>";
	}

?>

That’s it, the job is done. At this point, you will be able to select multiple items. And add dynamic rows in table tag and inserting them in the database as well. Complete source file along with SQL exported file which will help you to understand the structure of database.

[wpdm_package id=’239′]

Custom auto complete view – Vanilla Javascript

Learn how to create a custom auto complete view in vanilla Javascript. Auto complete view is a feature in which an input field predicts the rest of a word a user is typing. In most frequently fields like city names, users can typically enter some words. And wait for seeing the suggestions to accept one of several cities.

Auto complete view speeds up human-computer interactions. It correctly predicts the word a user intends to enter after only a few characters have been typed into a text input field. It works best in domains with a limited number of possible words (such as in command-line interpreters). When some words are much more common (such as when addressing an e-mail), or writing structured and predictable text (as in source code editors).

Google

In search engines like Google, auto complete view provide users with suggested queries or results as they type their query in the search box. This is also commonly called autosuggest or incremental search. This type of search often relies on matching algorithms that forgive entry errors. Such as phonetic Soundex algorithms or the language-independent Levenshtein algorithm. The challenge remains to search large indices or popular query lists in under a few milliseconds. So, that the user sees results pop up while typing.

Nothing gives you more control than writing code by yourself.

Unknown

Auto complete view can have an adverse effect on individuals and businesses when negative search terms are suggested. Autocomplete has now become a part of reputation management as companies linked to negative search terms such as scam, complaints and fraud seek to alter the results. Google in particular have listed some of the aspects that affect how their algorithm works. But this is an area that is open to manipulation.

Example

Suppose you have a list of values that you want to populate in an input field as user types. Give users an ability to select an item from that list and store the data. For example, if you have a list of products, you can display product title. But once any value is selected, you can send the product ID in database. Although there are many libraries on the internet to do this job. But they are limited in customizations and you have to remember their function names and parameters and options etc.

Lets get started

First we are going to create an input field that will have an ability to call a Javascript function as soon as user types something in it. We are attaching the “onkeyup” attribute on that field which will be called for every key pressed by the user. We are also giving this field an ID and name attribute:

  • ID will be use in Javascript to populate suggestions based on this field value.
  • Name will be use in PHP where form data will be sent. You can handle this as per your project.

Form’s method and action attribute depends on your project, you can adjust them as per your needs. We have also created a hidden field which will set the ID of selected product. So we will be displaying product title in suggestions. Also, when user select one product, it’s ID will be put in this hidden field. Lastly, we have a div where all suggested products will be displayed.

<form method="POST" action="send-data.php">
    <input type="text" id="product" name="product" onkeyup="onKeyUp();">
    <input type="hidden" id="productCode" name="productCode">
    <div id="products-list"></div>
</form>

Send HTTP request

First we will create a function for “onkeyup” event that we attached on previous step. In this function, we are getting value from product’s input field. We will get the suggested products only if the input field has at-least 3 words in it. Because sending HTTP request on each word would be very costly and it does not make sense at all. When you search for some product you already know first 4 or 5 characters of it. Even in case of cities, most people know at-least 3-4 characters of what they want to search. Displaying suggestions on each word would be really annoying for users.

Then in div where we wanted to show the suggested products, we will first show a loading message. So that the user knows that it is searching for products and the location where suggested products will be displayed. Then we are sending an AJAX request, the request method is GE. So it does not require any headers in the request.

URL of AJAX request

Second parameter in open function is the name of file, we will create that file in next step. In same parameter, we are sending user entered words in the URL so we can get them in that PHP file. At the end of this function we are sending the request. But before sending, we are attaching an event which will be called when the response is successfully received from server.

From get-products.php file which we will create in next step, we will receive all the suggested products based on value of input field. The response sent from PHP to Javascript will be in JSON string format, so we have to convert (parse) that string to Javascript objects and arrays. Then we will loop through all the suggested products and display them in paragraph. A separate variable is created which will store all the HTML content of the autocomplete view. Finally, we are setting this HTML variable value to div using its unique ID.

<script>
    function onKeyUp() {
        var product = document.getElementById("product");

        if (product.value.length >= 3) {
            document.getElementById("products-list").innerHTML = "Loading...";

            var ajax = new XMLHttpRequest();
            ajax.open("GET", "get-products.php?product=" + product.value, true);

            ajax.onreadystatechange = function () {
                if (this.readyState == 4 && this.status == 200) {
                    var data = JSON.parse(this.responseText);
                    var html = "";

                    for (var a = 0; a < data.length; a++) {
                        html += "<p>" + data[a].productName + "</p>";
                    }

                    document.getElementById("products-list").innerHTML = html;
                }
            };

            ajax.send();
        }
    }
</script>

Get suggested products

So we are sending HTTP request after 3 words entered by the user. And sending those 3 words to the server to fetch suggested products that match their title with those 3 words. Now we need to create a file that will match the product’s title with those words and return them all as an array. So we are first connecting with the database, get the user input field from URL.

Search that value in the database based on the products table’s title field (it might be different as per your need). Executing that query will return a $result object. It will have all pieces of information about the result which is received from the database. For example, number of rows, columns in each row, each row’s content, etc.

mysqli_fetch_all

You can use the mysqli_fetch_all function to return all rows at once. But this function does not work in some PHP versions. So what we are going to do, is to loop through each record and push them in our created array one-by-one. We will be using while loop to continue loop until all rows are fetched. At the end, we will have a PHP array will all the suggested products.

But we need them in Javascript, so we need to convert that array into JSON string format and in Javascript we are already converting that string back to Javascript arrays and objects.

get-products.php

<?php

	$conn = mysqli_connect("localhost", "root", "root", "classicmodels");
	$product = $_GET["product"];

	$sql = "SELECT * FROM products WHERE productName LIKE '%" . $product . "%'";
	$result = mysqli_query($conn, $sql);

	$data = array();
	while ($row = mysqli_fetch_object($result))
	{
		array_push($data, $row);
	}
	echo json_encode($data);

?>

Select product from suggestions

At this point, as the user starts typing the input field, after 3 words a list of suggested products will be displayed. Now we need to give the user an ability to select a product from this suggested list. First, we need to attach on “onclick” listener to the product’s title in a suggestions list that will call a Javascript function whenever the user selects a product from the list.

In that function we are going to need a selected product ID, so we are adding a custom attribute data-id whose value will be the product ID that should be set in the hidden input field. In that function, we are getting the selected product ID and setting this in the hidden product code field. Also, we are emptying the div so the suggestions will be removed once an item is selected from the list.

Lastly, in input field we are setting product’s title as a value because the user has only entered 3 words, once he selects some item from the list, that value will be set in his input field.

function selectProduct(self) {
	var productCode = self.getAttribute("data-id");
	document.getElementById("productCode").value = productCode;
	document.getElementById("products-list").innerHTML = "";
	document.getElementById("product").value = self.innerHTML;
}

// Inside AJAX response
for (var a = 0; a < data.length; a++) {
	html += "<p onclick='selectProduct(this);' data-id='" + data[a].productCode + "'>" + data[a].productName + "</p>";
}

Applying styles

Although this part has nothing to do with functionality, but it is always good to do some work on the design and make it look good. Add a CSS class to suggested products single paragraph, and create a <style> tag anywhere in your file and use that CSS class to applying styles as per your needs.

// Inside the loop in AJAX response, give CSS class
html += "<p class='product-list-item' onclick='selectProduct(this);' data-id='" + data[a].productCode + "'>" + data[a].productName + "</p>";

<style>
    .product-list-item {
        background: darkgray;
        color: white;
        width: 200px;
        padding: 15px;
        border-radius: 5px;
        cursor: pointer;
    }
</style>

That’s how you can create a customized auto complete view in HTML and Javascript.

[wpdm_package id=’235′]

Show realtime website users counter – Node JS

In this article, we are going to show you how you can get realtime website users counter using Node JS. Paste the following code in page where you want to display the counter:

HTML

<div class="row">
	<div id="countdown">
		<div id='tiles'>
			<span>0</span>
			<span>0</span>
			<span>0</span>
			<span>0</span>
		</div>

		<div class="labels">
			<li>Registered users</li>
		</div>
	</div>
</div>

CSS

#countdown{
    width: 465px;
    height: 170px;
    text-align: center;
    background: #222;
    background-image: -webkit-linear-gradient(top, #222, #333, #333, #222); 
    background-image:    -moz-linear-gradient(top, #222, #333, #333, #222);
    background-image:     -ms-linear-gradient(top, #222, #333, #333, #222);
    background-image:      -o-linear-gradient(top, #222, #333, #333, #222);
    border: 1px solid #111;
    border-radius: 5px;
    box-shadow: 0px 0px 8px rgba(0, 0, 0, 0.6);
    margin: auto;
    padding: 24px 0;
    position: absolute;
    top: 0; bottom: 0; left: 0; right: 0;
}

#countdown:before{
    content:"";
    width: 8px;
    height: 65px;
    background: #444;
    background-image: -webkit-linear-gradient(top, #555, #444, #444, #555); 
    background-image:    -moz-linear-gradient(top, #555, #444, #444, #555);
    background-image:     -ms-linear-gradient(top, #555, #444, #444, #555);
    background-image:      -o-linear-gradient(top, #555, #444, #444, #555);
    border: 1px solid #111;
    border-top-left-radius: 6px;
    border-bottom-left-radius: 6px;
    display: block;
    position: absolute;
    top: 48px; left: -10px;
}

#countdown:after{
    content:"";
    width: 8px;
    height: 65px;
    background: #444;
    background-image: -webkit-linear-gradient(top, #555, #444, #444, #555); 
    background-image:    -moz-linear-gradient(top, #555, #444, #444, #555);
    background-image:     -ms-linear-gradient(top, #555, #444, #444, #555);
    background-image:      -o-linear-gradient(top, #555, #444, #444, #555);
    border: 1px solid #111;
    border-top-right-radius: 6px;
    border-bottom-right-radius: 6px;
    display: block;
    position: absolute;
    top: 48px; right: -10px;
}

#countdown #tiles{
    position: relative;
    z-index: 1;
}

#countdown #tiles > span{
    width: 92px;
    max-width: 92px;
    font: bold 48px 'Droid Sans', Arial, sans-serif;
    text-align: center;
    color: #111;
    background-color: #ddd;
    background-image: -webkit-linear-gradient(top, #bbb, #eee); 
    background-image:    -moz-linear-gradient(top, #bbb, #eee);
    background-image:     -ms-linear-gradient(top, #bbb, #eee);
    background-image:      -o-linear-gradient(top, #bbb, #eee);
    border-top: 1px solid #fff;
    border-radius: 3px;
    box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.7);
    margin: 0 7px;
    padding: 18px 0;
    display: inline-block;
    position: relative;
}

#countdown #tiles > span:before{
    content:"";
    width: 100%;
    height: 13px;
    background: #111;
    display: block;
    padding: 0 3px;
    position: absolute;
    top: 41%; left: -3px;
    z-index: -1;
}

#countdown #tiles > span:after{
    content:"";
    width: 100%;
    height: 1px;
    background: #eee;
    border-top: 1px solid #333;
    display: block;
    position: absolute;
    top: 48%; left: 0;
}

#countdown .labels{
    width: 100%;
    height: 25px;
    text-align: center;
    position: absolute;
    bottom: 8px;
}

#countdown .labels li{
    /*width: 102px;*/
    font: bold 15px 'Droid Sans', Arial, sans-serif;
    color: #f47321;
    text-shadow: 1px 1px 0px #000;
    text-align: center;
    text-transform: uppercase;
    display: inline-block;
}

Display currently registered users

Paste the following code before the counter is displayed:

<?php
	$conn = mysqli_connect("localhost:8889", "root", "root", "classicmodels");
	$result = mysqli_query($conn, "SELECT COUNT(*) AS total_users FROM users");
	$row = mysqli_fetch_object($result);
	$total_users = $row->total_users;
	$total_users = substr("0000" . $total_users, -4);
?>

This will return the number of users in 4 digit format. For example, if your website has 275 users then substr(“0000” . $total_users, -4):

  • “0000” will print 4 zeroes.
  • $total_users will append 275, thus makes 0000275.
  • -4 will pick the last 4 characters, thus becomes 0275.

We need to display each character in 1 block, so we will loop through length of this digit and display single character in each iteration.

<?php for ($a = 0; $a < strlen($total_users); $a++) { ?>
	<span><?php echo $total_users[$a]; ?></span>
<?php } ?>

Setup Node JS

Download and install Node JS from here. After installation, create a new folder for Node JS and create a new file named “index.js”. Open command prompt in this folder and run the following command:

npm init

This will initialize the directory. Then you need to install 3 modules for this, you can install all 3 of them from single command:

npm install express http socket.io

When all above modules installs, open your index.js file and paste the following code in it:

var express = require("express");
var app = express();
var http = require("http").createServer(app);
var socketIO = require("socket.io")(http);

http.listen(3000, function () {
	socketIO.on("connection", function (socket) {
		socket.on("new_user", function () {
			socket.broadcast.emit("new_user");
		});
	});
});

And run the command in your command prompt:

node index.js

This will start the server and keep listen for incoming events for “new_user” event. As soon that event is received, it broadcast that event to all other connected clients. Broadcast means to send the event to all users except the one who sends it.

Send event when new user gets registered

So the server is listening for incoming events and sending to all other connected clients. Now we need to send event whenever new user gets registered. On registration form, attach an onsubmit event and call a function to send event to server. Make sure the function must returns true otherwise your action attribute will not work.

<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.js"></script>

<form action="your_action_page" onsubmit="return sendEvent();" method="POST">

JS

function sendEvent() {
	var socketIO = io("http://localhost:3000/");
	socketIO.emit("new_user");
	return true;
}

Receive event on counter page

So an event is sent from registration page to server, and sends it to all other connected clients. But there isn’t any client to receive it yet, so we will be listening to this event on our page where we want to display the counter. In this case, we are displaying counter on home page.

When the event is received we will increment the current users number and display it in 4 digit format, like we did for PHP. In order to increment the current number, we first must have the old number, so we have created an hidden field for it.

<input type="hidden" id="total_users" value="<?php echo $row->total_users; ?>">

<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.js"></script>

JS

var socketIO = io("http://localhost:3000/");
socketIO.on("new_user", function () {
	var total_users = document.getElementById("total_users").value;
	total_users++;

	var totalUsers_Str = total_users + "";
	totalUsers_Str = totalUsers_Str.padStart(4, "0");

	var html = "";
	for (var a = 0; a < totalUsers_Str.length; a++) {
		html += "<span>" + totalUsers_Str[a] + "</span>";
	}

	document.getElementById("tiles").innerHTML = html;
	document.getElementById("total_users").value = total_users;
});

This tutorial is created in core PHP and vanilla Javascript, but may be you were working in Laravel or in any other framework, so you might face minor problems to integrate this in your scenario. If you face any issue, you can always contact us and we will help you out.

That’s how you can show realtime website users counter in your website using PHP and Node JS.

[wpdm_package id=’233′]