Sprite is a computer graphics term for a two-dimensional bitmap that is integrated into a larger scene, most often in a 2D video game. Which means that small images are combined into one large image to reduce the number of requests on your server. Sprites helps a lot to reduce the number of HTTP requests.
In CSS sprites, we combine multiple images into a single image. So, if you are using 12 small images in your CSS, it will take 12 requests without sprite. Now if you combine all these images into one image, you will need only 1 request.
The basic principle is, you will combine multiple images into one large image. When you try to access it, the web server will not fetch the new copy of each image everytime you request it. Instead it will fetch just one image which contains all images and you can display them by specifying their position. Same as the image above.
So we will first combine all necessary images into one image and save it as a “sprite.png”. Then we will display the image by telling it’s position. We will be using two files, 1st for combining multiple images into one (save-sprite.php) and 2nd to display the images from sprite.
Generate sprites
First we create an HTML5 canvas tag where all images will be drawn. Give it unique ID to be accessible in Javascript and give it appropriate width and height.
Then we create an array of images which holds width, height and path (src) of each image. We will be looping through this array to automatically draw image on canvas. Also a counter variable to tell the number of current image under process.
Then we get the canvas object and 2D context of canvas. Create a variable named marginLeft to automatically draw the image after the previous one. If this is not specified, then all images will be placed on top of other.
After that, you will create a recursive function that will draw all images inside the array. Inside this function, create a new Image() object and set the image path in src attribute. Call onload function with this image object to wait for the image to fully loaded. The draw the image using drawImage(imageObj, x, y, width, height) function that will render the image on canvas.
Increase margin from left for next image, increment the counter. If there is more images in array then recursion occurs by calling the function itself inside the function. Otherwise if all images are rendered then we will convert that canvas into image and call an AJAX function to save this image data as a sprite.
<!-- Canvas where all images will be drawn -->
<canvas id="myCanvas" width="1000" height="500"></canvas>
<script>
// An array where all images should be entered
var images = [{
width: 308,
height: 183,
src: "image1.png"
}, {
width: 206,
height: 260,
src: "image2.png"
}];
// A variable used to get the number of current image
var count = 0;
// Get canvas element
var c = document.getElementById("myCanvas");
// Get canvas context used for drawing
var ctx = c.getContext("2d");
// Give margin to each image so they will be aligned horizontally
var marginLeft = 0;
// A recursive function which will keep calling itself
// until all images are drawn on canvas
function loadImage() {
// Create new image object
var imageObj = new Image();
// Set the path of image
imageObj.src = images[count].src;
// Wait till image fully loaded
imageObj.onload = function() {
// Draw image on canvas given image object, x, y, width & height
ctx.drawImage(imageObj, marginLeft, 0, images[count].width, images[count].height);
// Increase margin from left
marginLeft += images[count].width;
// Increment to next image
count++;
// If there is more image to draw
if (count < images.length) {
// Recursive occur here
loadImage();
} else {
// All images has been drawn on canvas
console.log("All images loaded");
// Convert the canvas into PNG image
var image = c.toDataURL("image/png", 1);
// Create AJAX request object
var ajax = new XMLHttpRequest();
// Set method to POST, file name and asynchnronous
ajax.open("POST", "save-sprite.php", true);
// Set headers in POST request
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Send the request and pass image data
ajax.send("image=" + image);
// Listen for server request changes
ajax.onreadystatechange = function () {
// Request is successful if ready state is 4 and status is 200
if (this.readyState == 4 && this.status == 200) {
// Print response sent from server
console.log(this.responseText);
}
};
}
}
}
loadImage();
</script>
Save sprite image
Create a new file named “save-sprite.php” and paste the following code in it. This will give the image data from client and remove the “base64” part from it as that is not necessary. When using AJAX post request we should also convert all spaces into plus sign and then decode the base64 string. Finally you can save the image as separate file.
To display an image we will create a <div> tag and set the background image as sprite. Given the background position allow you to display specific portion of sprite image. For example, if your sprite has 3 images of 100px width each, then your total sprite will be of 300px in width. To display the second image you have give the background position as -100px so it will move the image from left to right.
Sprites are very useful specially in video games where optimization and performance is very important. So instead of loading all car’s types (Lamborghini, Bugatti, Ferrari, Mclaren) as 4 images they create a single sprite named “cars-sprite.png” which holds all the images of cars. This is just an example, you can categories the sprites as much as required. The point is to send minimum requests on the server.
Hope that helps you in your upcoming or legacy projects to reduce the number of HTTP requests using sprites. If you face any problem, feel free to ask in the comment’s section below.
We will teach you how you can convert your <div> into an image using html2canvas library.
Download html2canvas library
First, you need to download the library called Html2Canvas and paste in your project folder. You can download it from here. After that, paste the JS file in your project and include it via script tag.
<script src="html2canvas.js"></script>
Then give a unique ID to the div tag whose screenshot you wants to take. After that, create a function in Javascript which will be called when you want to take the screenshot. We will be calling that function on some button press, but you can use it as per your needs.
<script>
// A function to convert the required div to image
function doCapture() {
//
}
</script>
<button onclick="doCapture();">Capture</button>
Scroll to top
In order to make this library works, your scroll position should be on header of your site. Even if you want to take the screenshot of footer or any other section in the middle. Your header must be visible before converting the div to image. So we will move the scroll to top by simply calling the window.scrollTo(x, y) function. And pass the x, y coordinates as 0 both.
function doCapture() {
// Move the scroll on top of page
window.scrollTo(0, 0);
}
Calling html2canvas function
Now we need to call the html2canvas function, it’s first parameter will be the tag which needs to be converted as image. As we already would have given it some unique ID attribute, so we can get it easily by calling document.getElementById(id) function. Lastly the library provides a function called then() which sends a callback when the div has been converted to image successfully. Basically it sends a canvas object and we can get the image data from that canvas. We can call the toDataURL(imageType, quality) function to get the image type. Possible image types are “image/jpeg” or “image/png” and the value of quality parameter ranges from 0 to 1. By setting the value to 0.9 we can get the minimum compression and maximum quality on image.
function doCapture() {
window.scrollTo(0, 0);
// Convert the div to image (canvas)
html2canvas(document.getElementById("capture")).then(function (canvas) {
// Get the image data as JPEG and 0.9 quality (0.0 - 1.0)
console.log(canvas.toDataURL("image/jpeg", 0.9));
});
}
Call AJAX with base64 image
In order to save this image in our server, you need to call an AJAX request and pass this image data as parameter.
function doCapture() {
window.scrollTo(0, 0);
html2canvas(document.getElementById("capture")).then(function (canvas) {
// Create an AJAX object
var ajax = new XMLHttpRequest();
// Setting method, server file name, and asynchronous
ajax.open("POST", "save-capture.php", true);
// Setting headers for POST method
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Sending image data to server
ajax.send("image=" + canvas.toDataURL("image/jpeg", 0.9));
// Receiving response from server
// This function will be called multiple times
ajax.onreadystatechange = function () {
// Check when the requested is completed
if (this.readyState == 4 && this.status == 200) {
// Displaying response from server
console.log(this.responseText);
}
};
});
}
Save file on server
Now create a server file named save-capture.php and paste the following code to save the incoming data as image.
<?php
// Get the incoming image data
$image = $_POST["image"];
// Remove image/jpeg from left side of image data
// and get the remaining part
$image = explode(";", $image)[1];
// Remove base64 from left side of image data
// and get the remaining part
$image = explode(",", $image)[1];
// Replace all spaces with plus sign (helpful for larger images)
$image = str_replace(" ", "+", $image);
// Convert back from base64
$image = base64_decode($image);
// Save the image as filename.jpeg
file_put_contents("filename.jpeg", $image);
// Sending response back to client
echo "Done";
You can also resize the saved image without stretching.
There is a jQuery ratings plugin called “Starrr”. It allows you to get feedback input from the user by displaying him stars. Lower stars means they didn’t liked your product or service. And higher stars means they liked your product or services.
Let’s get started
First you need to download and integrate a small and lightweight Javascript library in your project. The name of library is Starrr and you can download it from here. You may get the downloaded file in ZIP format so unzip it (of course). In the unzipped folder, you will find a folder named “dist”. You will find 2 files, one is CSS and second will be of JS. You need to copy both these files and place them in your project folder. To setup the star ratings in your website, you need to include 3 CSS files and 2 JS files.
CSS
Bootstrap
Font Awesome
Starrr
JS
jQuery
Starrr
So paste the following code at the top of file where you want to show ratings. We have used the CDN for Bootstrap, Font Awesome and jQuery for direct integration. But you can download them in your project and give relative path if you want. If you are already working on some project, then most probably you already have those CSS & JS files. Because they are used mostly in design part.
You might already have a database with all the data and you just want to integrate this star ratings in it. So you might have an E-commerce site where you want to give ratings to products, or may have an online Job Portal where you want to give ratings to Clients or Freelancers etc. So for the sake of simplicity we are are creating simple products with just 2 fields, you might have a lot of other fields too but it will give you enough idea how to implement in your project. Create a new database in your phpMyAdmin named tutorials and run the following queries to create 1 table named products and other ratings where all ratings of each product will be stored:
--
-- Database: `tutorials`
--
-- --------------------------------------------------------
--
-- Table structure for table `products`
--
CREATE TABLE `products` (
`id` int(11) NOT NULL,
`name` text NOT NULL
);
--
-- Dumping data for table `products`
--
INSERT INTO `products` (`id`, `name`) VALUES
(1, 'Macintosh'),
(2, 'iMac'),
(3, 'iPod'),
(4, 'Apple II');
-- --------------------------------------------------------
--
-- Table structure for table `ratings`
--
CREATE TABLE `ratings` (
`id` int(11) NOT NULL,
`product_id` int(11) NOT NULL,
`ratings` int(11) NOT NULL
);
Display all products
Now you need to display all products stored in your database. We are just displaying product name but surely you will be displaying other details too. Along with each product we will create a form to get product ID and show 5 stars from where user can give ratings and a submit button.
Run the project now and you will be able to see all products stored in your database along with 5 stars to give ratings. Now you need to save ratings in ratings table when user click on submit button.
Save ratings
Our form creates a hidden input field where it is storing product ID, so now we first need to get the ratings and save those ratings in that particular product. This jQuery ratings plugin will return the value as an integer. You need to change the starrr() function to attach an change event that will be fired when user change his ratings and we will save that in a variable. Then we will attach an submit event in form and call an AJAX request and send the product ID and rating of user.
Creates a new file named save-ratings.php that will store the ratings in database. You can also store user ID if you have login & registration system in your website, by getting the user ID from session or from cookies. So make the following changes in your above code and it will be able to save ratings in database:
index.php
var ratings = 0;
$(function () {
$(".starrr").starrr().on("starrr:change", function (event, value) {
ratings = value;
});
});
function saveRatings(form) {
var product_id = form.product_id.value;
$.ajax({
url: "save-ratings.php",
method: "POST",
data: {
"product_id": product_id,
"ratings": ratings
},
success: function (response) {
// whatever server echo, that will be displayed here in alert
alert(response);
}
});
return false;
}
save-ratings.php
<?php
$product_id = $_POST["product_id"];
$ratings = $_POST["ratings"];
$conn = mysqli_connect("localhost", "root", "", "tutorials");
mysqli_query($conn, "INSERT INTO ratings (product_id, ratings) VALUES ('$product_id', '$ratings')");
// whatever you echo here, will be displayed in alert on user side
echo "Saved";
Go ahead and give ratings to some products and check your ratings table in your database, you will see your ratings along with product ID. This is where you can store user ID too from session or cookies if you are using login or sign up features.
Display average rating
We are already creating a loop to display all products, this is where we will get all ratings of each product and calculate it’s average and display as stars. jQuery “starrr” ratings plugin also allows you to initialize the stars widget with an integer valule. So go ahead and paste the following code in your product’s while loop block:
while ($row = mysqli_fetch_object($result)) {
// Getting ratings of current product using ID
$result_ratings = mysqli_query($conn, "SELECT * FROM ratings WHERE product_id = '" . $row->id . "'");
// Adding total ratings from each user
$ratings = 0;
while ($row_ratings = mysqli_fetch_object($result_ratings))
{
$ratings += $row_ratings->ratings;
}
// Calculating average from all ratings
$average_ratings = 0;
$ratings_count = mysqli_num_rows($result_ratings);
if ($ratings_count > 0)
{
$average_ratings = $ratings / $ratings_count;
}
?>
<!-- This is where product stars will be displayed -->
<!-- data-rating attribute will be used in Javascript below -->
<div class="ratings" data-rating="<?php echo $average_ratings; ?>"></div>
<!-- Product name and other fields -->
<!-- Form goes here -->
<?php
}
?>
<script>
// Getting all div with ratings class
var rating = document.getElementsByClassName("ratings");
// Loop through all divs
for (var a = 0; a < rating.length; a++)
{
// Display star on each div based on data-rating attribute value
// readOnly will prevent the user changing it's value
$(rating[a]).starrr({
readOnly: true,
rating: rating[a].getAttribute("data-rating")
});
}
<script>
That’s it, you have successfully added a star rating widget in your website. Everyone will be using this according to his project requirements and everyone will have different scenarios based on his needs. So if you have any problem, feel free to ask in the comments section below.
Another jQuery ratings plugin
You can also get the feedback from your users by displaying them emojis. User can select an emoji to describe his experience with your product or service. You can learn how to integrate that in your website from here.
Following this tutorial, you will be able to do realtime chat in Firebase in your website. We will be using Javascript in this tutorial.
Firebase
Firebase provides the ability to use non-relational database which means data will be stored in objects and arrays. It uses JSON format to save data in database. The structure of data is similar to as stored in Mongo DB where each table is known as collection. Each row is resembled with documents inside collection.
By default, Firebase provides 15 GB of data where you can store text, images and documents too. One of the biggest advantage of using Firebase is that it has built-in support for realtime notifications. That means that when a new item is added or removed it will automatically be notified in respective events. So Firebase ease the process of setting up Socket, Node JS and Mongo DB.
Firebase console
Goto Firebase Console and create a new project. Set the name of project and click “Continue”, you can disable the analytics for now. After that, click on “web” icon to integrate Javascript API in your project. Set the name of your project again and DO NOT set Firebase hosting. Because you will be running on your own localhost or hosting server. Then you will be displayed a code which you can copy and paste at the top of your project.
In your firebase console, goto “Database” tab from left menu and click on “Realtime Database”. For now, you can setup the database in test mode. The code you copied from Firebase console will only have firebase-app.js. But you will also need firebase-database.js in order to use database. We will be using file named “index.php” where all chat operations are performed. Below code has some empty values but when you copy from Firebase console then they will be filled automatically as per your project.
index.php
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/6.6.1/firebase-app.js"></script>
<!-- include firebase database -->
<script src="https://www.gstatic.com/firebasejs/6.6.1/firebase-database.js"></script>
<script>
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: ""
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
</script>
Sending chat message in Firebase
Open your browser console by right click on empty area of page and select “Inspect Element” from context menu and open the “Console” tab. Make sure your internet is connected and check if there is any error. When it comes to sending message, for the sake of simplicity we will be saving username and message in the database. First we need to get the name of user when page opens. We can use Javascript built-in prompt() function to do that. Then we need to create a simple form with an input field to send message. When that form submits then we will call a function that will save the data in Firebase database.
The autocomplete field will make sure not to display old entered values in this field. At the end of sendMessage() make sure to return false. Otherwise the form will submits to itself and the page refreshed. firebase.database() will return an instance of Firebase database. You can either store it in a separate variable to re-use it or you can call it every-time you need to perform some action in database. When the data is saved then Firebase will fire an event that will be called when a new child is added. We will discuss that in details in next step.
The code below will create a new node named “messages”. It will give it a unique ID and save username and message in it. The nodes in database are called as “Childs” in Firebase database.
<script>
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: ""
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
var myName = prompt("Enter your name");
</script>
<!-- create a form to send message -->
<form onsubmit="return sendMessage();">
<input id="message" placeholder="Enter message" autocomplete="off">
<input type="submit">
</form>
<script>
function sendMessage() {
// get message
var message = document.getElementById("message").value;
// save in database
firebase.database().ref("messages").push().set({
"sender": myName,
"message": message
});
// prevent form from submitting
return false;
}
</script>
Display messages from chat in Firebase
To display database data from Firebase we need to attach a listener called “child_added”. The main benefit of using this listener is that it simplifies the process of fetching the old messages from database. It is also used to listen to new incoming messages. So this event will be called in 2 situations.
When the page loads it will get all messages saved in database.
And second, when a new child is added in Firebase database.
Code below will create a list where all messages needs to be displayed and attach a listener which will be called automatically when the page loads. On each iteration it will return a snapshot object which is a Firebase database object and it contains child’s key and value.
On each iteration we are creating a new list and appending at the end of UL tag. As the child’s key is unique throughout the database, so we will be adding this as an ID to list item. This will be used when we try to delete message, it will be covered in detail in next step. We will be displaying delete button only if the message is sent from current user which means you can delete only those messages which are sent by you.
Button tag will have an attribute data-id which will be used to get the unique ID of message and an onclick event is attached which will be called when that button is pressed. At the end we are displaying sender’s name and message content.
<!-- create a list -->
<ul id="messages"></ul>
<script>
// listen for incoming messages
firebase.database().ref("messages").on("child_added", function (snapshot) {
var html = "";
// give each message a unique ID
html += "<li id='message-" + snapshot.key + "'>";
// show delete button if message is sent by me
if (snapshot.val().sender == myName) {
html += "<button data-id='" + snapshot.key + "' onclick='deleteMessage(this);'>";
html += "Delete";
html += "</button>";
}
html += snapshot.val().sender + ": " + snapshot.val().message;
html += "</li>";
document.getElementById("messages").innerHTML += html;
});
</script>
Delete messages from chat in Firebase
Since we have already created a button to delete message, now we need to create a function that will be called when that button is pressed. We are going to delete the message from database and notify all other users that, that message has been removed. You can either remove that message node from list item or you can simply change the text of message to “This message has been removed” like WhatsApp does.
Next time you refresh the page, that message will be removed altogether. First we are getting the unique ID of message from the data-id attribute of button. Then we call the remove() function of Firebase instance and it will remove that message child from database. As soon as the child is removed, Firebase has an event named “child_removed” which will be called with deleted child key and value. So we are attaching that listener which will return the deleted child key and value which can be used to remove or alter that node from list item.
Now a delete button will be displayed along with your sent messages, when clicked it will be removed from Firebase database and a message will be displayed saying “This message has been removed”.
function deleteMessage(self) {
// get message ID
var messageId = self.getAttribute("data-id");
// delete message
firebase.database().ref("messages").child(messageId).remove();
}
// attach listener for delete message
firebase.database().ref("messages").on("child_removed", function (snapshot) {
// remove message node
document.getElementById("message-" + snapshot.key).innerHTML = "This message has been removed";
});
That’s how you can do real-time chat in Firebase using Javascript. If you do not want to use Firebase and do chat with your own server. You need to follow this tutorial.
You can get your YouTube channel statistics using YouTube Javascript SDK. You can also get comments of each video by providing its ID.
YouTube Data API allows you to get statistics from your YouTube channel. You can get all videos from your channel and you can get individual video detail. Video detail will contain video title, description, thumbnails, tags, views, likes, dislikes and comments. Comments section will include name of author, thumbnail image of user. Also, the comment he has posted and the time that comment was posted. Google provides an API which uses GET method to send requests and it can be used with Javascript and PHP.
YouTube channel statistics – Javascript SDK
When it comes with Javascript, you can use jQuery AJAX request to get the data. And when it comes to PHP, you can use built-in CURL method to send that request. Today, we will be using Javascript API to first list at-least 50 videos from your YouTube channel. Every video will have a button which when clicked will show the details of that video.
The detail of video includes video title, description, thumbnails, tags, published date, date when last time the video was updated. You can also get comments of individual video. You will get name of person who commented, his profile image, comment text and the date the comment was published.
Goto Google Developers Console and enable YouTube Data API. YouTube Data API is running on version 3 at the time of writing this. After that you need to get your API key which you can get from left menu. There was an option labeled as “Credentials”. You will see a list of all API keys already created and you use any old API key.
Create new API key
You can create a new API too by simply clicking the button at top right corner, it will be labeled as “Create Credentials”. Copy that API, we will need that later. Also goto youtube.com and click on your profile icon on top right and goto “My channel” and you can get your channel ID from URL, copy that too. Download jQuery from here and paste in your project folder. Create a file named “index.php” this will be the only file that we will be using in whole tutorial.
First you need to include jQuery in your file because we will be sending an AJAX request to call Google Api. To get videos you will need API key and your channel ID whose videos needs to be fetched. Replace variables apiKey and channelId with your API key and channel ID respectively. These will be send as parameter in the API along with some other parameters.
Part parameter specifies which fields needs to be fetched, here we wanted each video ID so that we can get it’s further details later and snippet will contain title which will be visible in the list. An ul list is created and all videos are appended in it with a clickable button which when clicked should send the video ID so we can get details of video using that ID.
index.php
<!-- include jquery -->
<script src="js/jquery.js"></script>
<ul id="videos"></ul>
<script>
var apiKey = "";
var channelId = "";
var url = "https://www.googleapis.com/youtube/v3/search?key=" + apiKey + "&channelId=" + channelId + "&part=id,snippet&maxResults=50";
// call ajax to get the videos
$.ajax({
url: url,
method: "GET",
success: function (response) {
console.log(response);
var html = "";
for (var a = 0; a < response.items.length; a++) {
html += "<li>";
html += "<button onclick='videoSelected(this);' data-id='" + response.items[a].id.videoId + "'>";
html += response.items[a].snippet.title;
html += "<button>";
html += "</li>";
}
$("#videos").html(html);
}
});
</script>
Now a list will be displayed with 50 videos from your channel with their title inside a button. When you click the video title it will call the function videoSelected and pass the clicked button as a parameter. As we have set an attribute data-id with video ID so we can get the video ID easily and display it’s details by sending another API request.
Get video detail
Now we can get each video ID separately and by sending another API request we can get it’s detail. This time we will be calling videos API from googleapis.com and sending the video ID as a parameter whose details needs to be fetched. We will be creating a separate div to show video detail. We will be displaying title, description, thumbnail, views, likes and dislikes but you can show other details too as per your needs.
Regarding the thumbnail you will have 4 options in quality of thumbnail image (low, normal, high, maximum resolution). Although it depends on the actual video thumbnail quality, if the video does not have maximum resolution quality thumbnail then only 3 fields will be returned.
index.php
<div id="video-detail"></div>
<script>
function videoSelected(self) {
// get video ID
var videoId = self.getAttribute("data-id");
// call ajax to get video detail
var url = "https://www.googleapis.com/youtube/v3/videos?key=" + apiKey + "&id=" + videoId + "&part=statistics,snippet";
$.ajax({
url: url,
method: "GET",
success: function (response) {
console.log(response);
var html = "";
// display title
html += "<p>" + response.items[0].snippet.title + "</p>";
// description
html += "<p>" + response.items[0].snippet.description + "</p>";
// display thumbnail
html += "<img src='" + response.items[0].snippet.thumbnails.maxres.url + "'>";
html += "<p>Views: " + response.items[0].statistics.viewCount + ", Likes: " + response.items[0].statistics.likeCount + ", Dislikes: " + response.items[0].statistics.dislikeCount + "</p>";
$("#video-detail").html(html);
showComments(videoId);
}
});
}
</script>
Get video comments
Displaying comments require only video ID and API key in the parameters. Please keep that in mind that all API calls to googleapis.com requires an API key to be provided. Without that, even if everything else was provided correctly, data will not be returned from API. Here we are displaying name of person who commented along with his profile image and the comment that he has posted.
<ul id="comments"></ul>
<script>
function showComments(videoId) {
var url = "https://www.googleapis.com/youtube/v3/commentThreads?key=" + apiKey + "&videoId=" + videoId + "&part=snippet&maxResults=50";
// call ajax to get comments
$.ajax({
url: url,
method: "GET",
success: function (response) {
console.log(response);
var html = "";
for (var a = 0; a < response.items.length; a++) {
html += "<li>";
// show image
html += "<img src='" + response.items[a].snippet.topLevelComment.snippet.authorProfileImageUrl + "'>";
html += response.items[a].snippet.topLevelComment.snippet.authorDisplayName;
// comment text
html += "<p>" + response.items[a].snippet.topLevelComment.snippet.textDisplay + "</p>";
html += "<br>";
html += "</li>";
}
$("#comments").html(html);
}
});
}
</script>
Conclusion – YouTube channel statistics
Since this post is about using YouTube Data API using Javascript but you can also use it in PHP, Node JS or any other language of your choice. As most of the programming languages today supports Http requests. The URL of API will remain same except the API key and channel ID (of course). If you are using Node JS then you can Express JS, if you are using PHP then you can use Curl module and so goes for other languages too.
We will create a simple and real-time chat module in Node JS and MySQL. We will be using socket IO for real-time communication.
Why chat in Node JS ?
Node JS is a web server that runs under the most famous and widely used programming language, Javascript. As Javascript is asynchronous, so Node JS server can fulfil client requests without having to wait for previous instruction to execute. Node JS runs in non-blocking event, which means that if there is any statement that takes too much time then Node JS will not get stuck at that point rather it will move to the next statement. Node JS can generate dynamic content of a website so user does not have to refresh the page in order to see updated data. This is very useful in realtime applications such as chat apps and google maps etc.
That is why most of the chat apps are developed in Node JS.
Node JS server runs on a single executable file, that file can include other multiple files too. But the server will be executing just the main file. Typically, that file named as “server.js” or “main.js” and that depends if you wanted to have different servers in same folder. That file will be executed just once and then will keep listening to incoming events, as soon it receives a new event it will send it back to other clients. Every time you run the Node JS file, all previous variables, arrays, objects will be destroyed. That is why it is recommended to store that data in some database.
Database for Node JS
When it comes to the database, Node JS has multiple options. You can use MySQL which is famous relational database structure and it is widely used in web development all over the world. Tech giants like Facebook uses MySQL as backend database. Or you can use Mongo DB which is a relation-less data structure, here data is stored in collections and documents. Collection will be name of entity and document is a single record exist in some collection. For example, you will have a collection of user and whenever a new user registered, a new document will be created inside this collection. It is much faster than MySQL.
Or you can use a file system where everything will be saved in file, it is the least recommended method but you can use this for exporting data in external formats. You can have .CSV format which is Comma Separated Values and this type of file usually gets opened in Microsoft Excel (Windows) or Numbers (Macintosh). Similarly, you can use JSON format to store data in files and this type of files holds data in forms of arrays and objects, they are typically used for statistics, for example:
First you need to download and install Node JS server in your system. You can download it from it’s official site. After installation, you need to create a folder anywhere in your system and create a file named “server.js”. Make sure the extension of file must be “.js” because the code will be in Javascript. Write the following simple line inside this file, it will show “Hello world !” when the server runs:
server.js
console.log("Hello world !");
Open terminal (CMD) and change the directory to your project folder (cd /path/to/project/). Run the following command in the terminal:
> npm init
> npm install -g nodemon
The first command will start your project folder as Node JS project and it will ask several questions like author (your) name, version etc. Just keep hitting enter if you wanted to skip these. Second command will install nodemon module globally in your system. This is helpful because nodemon allows you to make changes in server file without having to worry to restart the server. Whenever you made any changes in server file, nodemon will automatically restart the server. Otherwise, you have to restart it manually every time you make any change in server file. Now go ahead and run the following command in your terminal, make sure your project’s directory is opened in terminal:
nodemon server.js
When you run the above command, you will see a message saying “Hello world !”. Now install the Express and Http modules in your project by running the following commands, you may need to stop the nodemon running command by hitting Ctrl + C:
> npm install express
> npm install http
After installation you need to create an instance of these modules in your “server.js” file:
// use express
var express = require("express");
// create instance of express
var app = express();
// use http with instance of express
var http = require("http").createServer(app);
To start the server, call the listen function from http object and pass the port number as a parameter. Second parameter is a function that will be called when the server starts running:
// start the server
var port = 3000;
http.listen(port, function () {
console.log("Listening to port " + port);
});
After pasting these lines in “server.js” you need to run “nodemon server.js” again in the terminal so that the server will keep running on this port.
Socket for incoming connections
Install socket module in your project by running the following command:
> npm install socket.io
And in your “server.js” create an instance of it:
// create socket instance with http
var io = require("socket.io")(http);
To receive incoming connections, you need to attach “connection” event listener on IO object:
// add listener for new connection
io.on("connection", function (socket) {
// this is socket for each user
console.log("User connected", socket.id);
});
Whenever a new user connects, this function will be called and we will get it’s socket object in the function argument. We can use the socket ID to send event to specific users. Following is a list of useful functions that you can perform using these IO and socket objects:
Event
Purpose
socket.to(socket.id).emit(“name”, “value”)
Sends the value to specific user.
io.emit(“name”, “value”)
Sends the value to all connected users.
socket.emit(“name”, “value”)
Sends the value back to the user who called this event.
socket.broadcast.emit(“name”, “value”)
Sends the value to all users except the one who called this event.
Sending chat message event in Node JS
Download and save the socket.io.js file in your project, create a folder named “js” where all JS files will be saved. You can download socket IO from here. Create a file named “index.html” at the root of your project’s folder and include this socket file as Javascript.
<script src="js/socket.io.js"></script>
Then you need to create an instance of socket IO with the same port number as specified in “server.js”. Paste the following code in “index.html”:
<script>
var server = "http://localhost:3000";
var io = io(server);
</script>
When you run the index.html in your browser, you will see in your terminal a message for new user connection with a unique socket ID. Paste the following line in your “index.html” inside script tag, it will send the event to server:
// sending message from client
io.emit("new_message", "New message");
And paste the following line in “server.js”, it will receive the event sent from server. This line must be inside IO connection event:
// server should listen from each client via it's socket
socket.on("new_message", function (data) {
console.log("Client says", data);
});
Run the “nodemon server.js” command again to start the server and refresh the index.html page in your browser and you will see “Client says New message” in your terminal. So now you can create a form where user will enter his desired message and upon hitting submit button, that event will be fired to server. Paste the following code in “index.html” file:
<form onsubmit="return sendMessage();">
<input id="message" placeholder="Enter message">
<input type="submit" value="Send">
</form>
<script>
function sendMessage() {
// get message
var message = document.getElementById("message");
// sending message from client
io.emit("new_message", message.value);
// this will prevent the form from submitting
return false;
}
</script>
Emit event to all connected users
Now if you refresh the index.html file, you will see a form with an input field to enter message and a button. Write any message you want and click send button and you will see that message in your terminal window. Now server needs to respond back to all users that a new message has been received. First send the message from server to all connected clients:
// change in server.js inside IO "connection" event
// server should listen from each client via it's socket
socket.on("new_message", function (data) {
// server will send message to all connected clients
// send same message back to all users
io.emit("new_message", data);
});
It will send the same message back to all connected clients. Now all clients must be listening from server for that event, once that event is triggered from server then all clients will show the new message. Paste the following code in “index.html” inside script tag:
// client will listen from server
io.on("new_message", function (data) {
console.log("Server says", data);
});
Now refresh the page and open a new browser window or you can use different browsers if you have multiple browsers installed in your computer. Then open both browsers side by side. Send message from 1 browser and you will see the message in console of other browser. You can open console by right clicking in empty area and selecting “Inspect Element” option. Create a <ul> tag to display all incoming messages in a list in “index.html”:
<!--list where all messages will be displayed-->
<ul id="messages"></ul>
And paste the following code in the “new_message” event in the “index.html” file:
// client will listen from server
io.on("new_message", function (data) {
// display message
console.log("Server says", data);
// creates a new DOM element for li tag
var li = document.createElement("li");
// show message in li item
li.innerHTML = data;
// append the message at the end of list
var messages = document.getElementById("messages");
messages.appendChild(li);
});
Refreshing the page and you will be able to send message from a form and it will be display on the other browser in a list. Send multiple messages and all will be displayed at the end of list. When you refresh the page you will see an empty page because the server only listens to incoming messages. In order to see old messages you can either create an array or store all messages in database. Creating an array will remove all messages when the server restarted. So we are going to save in database.
Connect chat app in Node JS, with MySQL
First you need to install a module named mysql, stop the server and run the following command in your terminal. You can stop the server by pressing Ctrl + C.
npm install mysql
Make sure to run “nodemon server.js” again to start the server.
Create a database in your phpMyAdmin named “web_chat” and inside this database create a table named “messages”. This table can have only 2 fields just for the sake of simplicity, auto increment integer “id” and TEXT “message”. ID will be used when deleting the message. Your table structure should be . Create mysql module instance in “server.js” file and start a new connection with database:
// use mysql
var mysql = require("mysql");
// create connection
var connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "web_chat"
});
connection.connect(function (error) {
// show error, if any
});
Save messages in MySQL
In “server.js” change the “new_message” event to save the incoming message in database before notifying to all other clients:
// server should listen from each client via it's socket
socket.on("new_message", function (data) {
console.log("Client says", data);
// save message in database
connection.query("INSERT INTO messages (message) VALUES ('" + data + "')", function (error, result) {
// server will send message to all connected clients
io.emit("new_message", {
id: result.insertId,
message: data
});
});
});
This will save the incoming message in database and return the new row inserted ID which can be used to delete the message. Similarly, change your “new_message” event in “index.html” to display the message as:
li.innerHTML = data.message;
If you try to send a message now, you will see that message will also get saved in database table. Now you need to display all previous messages to a client when connected.
Reading messages from MySQL
Download and save the jquery.js file in your project’s js folder. You can download jQuery from it’s official site and include it in your “index.html” file.
<script src="js/jquery.js"></script>
Paste the following code anywhere in the script tag in “index.html”. It sends an API request to Node JS server and display all messages returned from server. Since the data returned from server will be in JSON string, so we have to convert it back to Javascript object by parsing.
$.ajax({
url: server + "/get_messages",
method: "GET",
success: function (response) {
console.log(response);
var messages = document.getElementById("messages");
// parse JSON to javascript object
var data = JSON.parse(response);
for (var a = 0; a < data.length; a++) {
// creates new DOM element
var li = document.createElement("li");
// add message content as HTML
li.innerHTML = data[a].message;
// append at the end of list
messages.appendChild(li);
}
}
});
Now in “server.js” you need to set header to allow API requests from unknown sources. Since you are testing it from localhost and that is not known for Node JS so you can add a header for “Access-Control-Allow-Origin” and allow all origins by setting it’s value to “*”. Paste the following code outside of IO “connection” event:
next() is a callback function that will attach these headers with incoming API requests. And you need to create an API for “get_messages” that will return all the saved messages in database. Paste the following code in “server.js” outside of IO “connection” event:
// create API for get_message
app.get("/get_messages", function (request, result) {
connection.query("SELECT * FROM messages", function (error, messages) {
// return data will be in JSON format
result.end(JSON.stringify(messages));
});
});
Since “result.end” can only send string data in response, so you can convert your objects into JSON string and can parse this JSON string back to Javascript objects at client side. Refresh the page and now you will see all previous messages sent in this chat using Node JS API. If you send or receive a new message it will be appended at the end of same list and upon refreshing it will not be removed, because it will already get saved in database.
Delete message
If you have used WhatsApp then you probably know about the delete message feature. Your friend sends you a message and you saw it, then he deletes it and suddenly a message appeared to you “This message has been deleted”. This can be done via Node JS where deleting message from sender will make that message removed from all other users all of a sudden. First you need to create a delete button in 2 functions, when all messages are fetched from database and when a new message has been received. Change the for loop inside “get_messages” AJAX call in “index.html” file:
// give it unique id
li.id = "message-" + data[a].id;
li.innerHTML = data[a].message;
// add delete button
li.innerHTML += "<button data-id='" + data[a].id + "' onclick='deleteMessage(this);'>Delete</button>";
Above code should be pasted inside for loop before appending the child. In your “new_message” event in “index.html”, paste the following code before appending the child:
// same here
li.id = "message-" + data.id;
li.innerHTML = data.message;
// display delete button here too
li.innerHTML += "<button data-id='" + data.id + "' onclick='deleteMessage(this);'>Delete</button>";
Now inside your <script> tag create a new function that will get the message ID and send the delete event to the server with selected message ID:
function deleteMessage(self) {
// get message id
var id = self.getAttribute("data-id");
// send event to server
io.emit("delete_message", id);
}
In your “server.js” that event will be listened and delete the message from database. After deleting, an event will be sent to all users to remove that message from list. Paste the following code in your IO “connection” event:
// attach listener to server
socket.on("delete_message", function (messageId) {
// delete from database
connection.query("DELETE FROM messages WHERE id = '" + messageId + "'", function (error, result) {
// send event to all users
io.emit("delete_message", messageId);
});
});
Now all clients must be listening continuously for delete event and you can remove that list item as soon as user receives that event. We are making it to show “This message has been deleted” similar to WhatsApp when delete event is received from server. So paste the following code in your “index.html” script tag:
// attach listener on client
io.on("delete_message", function (id) {
// get node by id
var node = document.getElementById("message-" + id);
node.innerHTML = "This message has been deleted";
});
Refresh both browsers and try to send message from one browser to anther. You will see a delete button along with message text. When you click that button from one browser, that message will gets deleted from both browsers and instead you will see a message “This message has been deleted”.
Display name with message
At this point, when you send or receive a message you only see the content of message but you also wanted to know WHO sends that message. So first create a form where user can enter his name and then that name will be sent along with his message. In your “index.html” file before send message form, create a simple form like below:
In the same file inside the <script> tag create a function that will create a global variable named “username”:
var username = "";
function setUsername() {
username = $("#username").val();
// this will prevent the form from submitting
return false;
}
Now change the “sendMessage” function to the following so that it will send the username along with message to the server:
function sendMessage() {
// get message
var message = document.getElementById("message");
// sending message from client
io.emit("new_message", {
message: message.value,
username: username
});
// this will prevent the form from submitting
return false;
}
Now in “new_message” event in same file, change the line which append the message content in <li> tag to the following:
The above line will display the name of user in bold and message in normal style. You can save the username in messages table in database too by first creating a column named “username” and it’s value must be TEXT. Then in “server.js” inside IO “connection” event change the socket’s “new_message” to the following:
// server should listen from each client via it's socket
socket.on("new_message", function (data) {
// save message in database
connection.query("INSERT INTO messages(username, message) VALUES('" + data.username + "', '" + data.message + "')", function (error, result) {
data.id = result.insertId;
io.emit("new_message", data);
});
});
Conclusion
Node JS plays a very important role in web development especially in realtime environment. Apart from just creating a chat app in Node JS, you can create a notification system where someone’s activity is monitored realtime by others, or maps that share realtime live location between friends etc. If you wanted to have the chat app in Node JS with the design as above, you can download all source files from the button below. Make sure you download them and let us know if you face any issue.
By live CRUD with AJAX, we mean that you will be able to Create, Read, Update, Delete data without having to refresh the page. This tutorial does not have any dependency on jQuery, you can implement it without having to include jQuery in it. We will be using a sample database named classicmodels and it will be included in the source files below. It has multiple tables but we will be using a table named employees to perform all 4 operations.
Live CRUD with AJAX – PHP
Let’s get started:
Create
We will be creating a simple form to input all fields and a button to insert a new row in database. Be default, the browser redirects you to the action attribute of form but we will be using onsubmit event to prevent form from redirecting. And thus, we can call our javascript function to save data via AJAX.
<form method="POST" onsubmit="return doInsert(this);">
<input name="first_name" placeholder="First name">
<input name="last_name" placeholder="Last name">
<input type="submit" value="Insert">
</form>
<script>
function doInsert(form) {
var firstName = form.first_name.value;
var lastName = form.last_name.value;
var ajax = new XMLHttpRequest();
ajax.open("POST", "Http.php", true);
ajax.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
ajax.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200)
alert(this.responseText);
};
ajax.send("first_name=" + firstName + "&last_name=" + lastName + "&do_insert=1");
return false;
}
</script>
Http.php
This file will be responsible for serving all 4 operations. We will be creating a database connection and a separate block for each request. Simple !
<?php
$connection = mysqli_connect("localhost", "root", "", "classicmodels");
if (isset($_POST["do_insert"]))
{
$first_name = $_POST["first_name"];
$last_name = $_POST["last_name"];
$sql = "INSERT INTO `employees`(`lastName`, `firstName`) VALUES ('$last_name', '$first_name')";
mysqli_query($connection, $sql);
echo "Record has been inserted successfully.";
exit();
}
Read
Display data in tabular form requires a table with unique ID to tbody tag.
<table>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody id="data"></tbody>
</table>
<script>
function getData() {
var ajax = new XMLHttpRequest();
ajax.open("GET", "Http.php?view_all=1", true);
ajax.send();
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 += "<tr>";
html += "<td>" + data[a].firstName + "</td>";
html += "<td>" + data[a].lastName + "</td>";
html += "</tr>";
}
document.getElementById("data").innerHTML = html;
}
};
}
getData();
</script>
Http.php
There are no parameters in the AJAX request so for the sake of simplicity, in this file we will just be fetching all records from database. Paste the following code right below INSERT block done in previous step in Http.php:
if (isset($_GET["view_all"]))
{
$sql = "SELECT * FROM employees";
$result = mysqli_query($connection, $sql);
$data = array();
while ($row = mysqli_fetch_object($result))
array_push($data, $row);
echo json_encode($data);
exit();
}
Delete
Removing a row from database is the simplest part of this tutorial, just enter an ID, sends an AJAX request and execute the DELETE command.
<form method="POST" onsubmit="return doDelete(this);">
<input name="employee_id" placeholder="Employee ID">
<input type="submit" value="Delete">
</form>
<script>
function doDelete(form) {
var employeeID = form.employee_id.value;
var ajax = new XMLHttpRequest();
ajax.open("POST", "Http.php", true);
ajax.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
ajax.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200)
alert(this.responseText);
};
ajax.send("employee_id=" + employeeID + "&do_delete=1");
return false;
}
</script>
Http.php
We will be using simple DELETE query to remove a row from database. Paste the following code right below VIEW ALL block done in previous step in Http.php:
if (isset($_POST["do_delete"]))
{
$employee_id = $_POST["employee_id"];
$sql = "DELETE FROM employees WHERE employeeNumber = '" . $employee_id . "'";
mysqli_query($connection, $sql);
echo "Record has been deleted";
exit();
}
Update (a)
Updating the data would require 2 forms, 1 to get data of record you want to update, and 2nd to actually update the data in database. First we are going to get the record which needs to be updated:
<form method="POST" onsubmit="return getData(this);">
<input name="employee_id" placeholder="Employee ID">
<input type="submit" value="Search">
</form>
<script>
function getData(form) {
var employeeID = form.employee_id.value;
var ajax = new XMLHttpRequest();
ajax.open("POST", "Http.php", true);
ajax.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
ajax.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var data = JSON.parse(this.responseText);
var form = document.getElementById("form-update");
/* Show data in 2nd form */
form.first_name.value = data.firstName;
form.last_name.value = data.lastName;
form.employee_id.value = employeeID;
form.style.display = "";
}
};
ajax.send("employee_id=" + employeeID + "&get_data=1");
return false;
}
</script>
Http.php
This query will be almost same as for VIEW ALL function. Paste the following code right below DELETE block done in previous step in Http.php:
In this step, we will actually be updating the record in database. This step is almost similar to the INSERT section.
<form method="POST" onsubmit="return doUpdate(this);" id="form-update" style="display: none;">
<input type="hidden" name="employee_id">
<input name="first_name" placeholder="First name">
<input name="last_name" placeholder="Last name">
<input type="submit" value="Update">
</form>
<script>
function doUpdate(form) {
var firstName = form.first_name.value;
var lastName = form.last_name.value;
var employeeID = form.employee_id.value;
var ajax = new XMLHttpRequest();
ajax.open("POST", "Http.php", true);
ajax.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
ajax.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200)
alert(this.responseText);
};
ajax.send("first_name=" + firstName + "&last_name=" + lastName + "&employee_id=" + employeeID + "&do_update=1");
return false;
}
</script>
Http.php
Paste the following code right below GET DATA block done in previous step in Http.php:
if (isset($_POST["do_update"]))
{
$first_name = $_POST["first_name"];
$last_name = $_POST["last_name"];
$employee_id = $_POST["employee_id"];
$sql = "UPDATE `employees` SET `lastName` = '$last_name', `firstName` = '$first_name' WHERE employeeNumber = '" . $employee_id . "'";
mysqli_query($connection, $sql);
echo "Record has been updated successfully.";
exit();
}
That’s how you can implement a complete live CRUD operation with AJAX, PHP and MySQL. If you want to get more advanced. You can check our tutorial on doing a CRUD operation in Vue JS.
Learn how you can show a “Load more” button using AJAX, PHP and MySQL. No external library has been used in this tutorial.
What is “Load more” button ?
By “Load more” we mean creating a button that allows you to show only 10 or 20 records and on clicking that button will fetch next 10 records from database without having to refresh the page. This function is heavily used in tech giant Facebook where older posts are fetched by scrolling without refreshing the page.
We will be using a sample database called classicmodels, it is attached in the source files below.
Create layout
We will be using employees table and displaying employeeNumber, firstName, lastName and email fields. A unique ID should be provided to <tbody> which will be used to append data using Ajax.
We are displaying 10 records in each step and we will need just 1 variable for this. start to tell the starting position of fetching data and it will be incremented in each step.
<script>
// Starting position to get new records
var start = 0;
// This function will be called every time a button pressed
function getData() {
// Creating a built-in AJAX object
var ajax = new XMLHttpRequest();
// Sending starting position
ajax.open("GET", "Http.php?start=" + start, true);
// Actually sending the request
ajax.send();
// Detecting request state change
ajax.onreadystatechange = function () {
// Called when the response is successfully received
if (this.readyState == 4 && this.status == 200) {
// For debugging purpose only
console.log(this.responseText);
}
};
}
// Calling the function on page load
getData();
</script>
At this point if you run the program, you will see an empty table and a button, now you need to create Http.php file to handle each request.
Handling AJAX request – PHP
Create a new file and name it Http.php, in this file we will simply get the offset (start variable) and display the records based on that value.
<?php
// Connecting with database
$connection = mysqli_connect("localhost", "root", "", "classicmodels");
// Getting offset to show next records
$start = $_GET["start"];
// Executing the query based on $start variable
$sql = "SELECT * FROM employees LIMIT $start, 10";
$result = mysqli_query($connection, $sql);
// Storing all returned records in an array
$data = array();
while ($row = mysqli_fetch_object($result))
array_push($data, $row);
// Sending response back to AJAX
echo json_encode($data);
Now if you view your browser console, you will see some JSON string data when the page loads.
Appending records in table
Now you need to convert that JSON string into Javascript array and append in <tbody> tag. Paste the following code back in your index.php file:
ajax.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
// Converting JSON string to Javasript array
var data = JSON.parse(this.responseText);
var html = "";
// Appending all returned data in a variable called html
for (var a = 0; a < data.length; a++) {
html += "<tr>";
html += "<td>" + data[a].employeeNumber + "</td>";
html += "<td>" + data[a].firstName + "</td>";
html += "<td>" + data[a].lastName + "</td>";
html += "<td>" + data[a].email + "</td>";
html += "</tr>";
}
// Appending the data below old data in <tbody> tag
document.getElementById("data").innerHTML += html;
// Incrementing the offset so you can get next records when that button is clicked
start = start + 10;
}
};
So for example, first time you will get employees from 1 to 10 and next time you hit load more button you will get employees from 11 to 20 and so on.
That’s how you can show a “Load more” button using AJAX, PHP and MySQL. You can also create a load more button in Node JS and Mongo DB. Learn from here how you can do that.
In this article, we will teach you how you can view detail of user selected record in PHP. We will display detail in Bootstrap modal.
For example, you are displaying a list of users or products or anything that has so much attributes that you cannot display them all in 1 table. That is where you will display only 2 or 3 attributes in a table and display every other detail in a pop-up.
Start off, by creating a simple index.php, it is the only file where we will be working on. You can download bootstrap library from the link below and paste them in your project directory, all files have also being attached in the source files at the end of this page (along with jQuery):
First you have to display 2 or 3 attributes of records from database and create a button to view details. We will be using a sample database called classicmodels, you can find it in the source files below. And we will be displaying records from table named customers.
At this point, you will be able to view the records from database in a table. Now, you have to create a button which upon clicking will show the detail of that particular record. Change the following line in the table tag:
We have created a custom attribute named data-id and assigned it the value of customer ID, we will be using this to get all record.
onclick event will call the function loadData and we are passing current customer ID as a parameter this.getAttribute(‘data-id’). This will get the value of data-id attribute in this button tag.
After that, you have to create a function and call an AJAX to get that customer’s data. We are using POST method, url will be same as current file name. In data object, we will be using get_data to check when user has requested to view the detail:
Now, at the start of this file index.php, get the ID of customer and provide the customer’s detail:
<?php
// Check if user has requested to get detail
if (isset($_POST["get_data"]))
{
// Get the ID of customer user has selected
$id = $_POST["id"];
// Connecting with database
$connection = mysqli_connect("localhost", "root", "", "classicmodels");
// Getting specific customer's detail
$sql = "SELECT * FROM customers WHERE customerNumber='$id'";
$result = mysqli_query($connection, $sql);
$row = mysqli_fetch_object($result);
// Important to echo the record in JSON format
echo json_encode($row);
// Important to stop further executing the script on AJAX by following line
exit();
}
?>
At this point, click on any customer’s detail button and in your browser console you will see it’s detail in JSON(string) format.
View detail of user selected record
Convert this JSON data in Javascript object on your AJAX success function. You will also need to create a custom HTML layout like in the following:
success: function (response) {
response = JSON.parse(response);
console.log(response);
var html = "";
// Displaying city
html += "<div class='row'>";
html += "<div class='col-md-6'>City</div>";
html += "<div class='col-md-6'>" + response.city + "</div>";
html += "</div>";
// And now assign this HTML layout in pop-up body
$("#modal-body").html(html);
// And finally you can this function to show the pop-up/dialog
$("#myModal").modal();
}
I have displayed only city name, try displaying every other column in the table too. That’s how you can view the detail of user selected record in PHP.
Calculating difference between 2 dates requires 2 calendars to pick dates or you may want to calculate difference based on some database values. For example, say you have a project management site and when you create a project you also set it’s deadline too. Now you may want to know how many days are remaining till deadline, you will something like this:
$remaining_days = $deadline – $today;
So we will be using 2 different methods to calculate difference. 1st is by creating two input fields for the user to select the dates and 2nd method is by calculating difference from database datetime value.
From datetime picker
Start off by downloading the datetimepicker from the link below, you can also find this too in the source files at the end of this page:
At this point, you will be able to select 2 dates from 2 input fields. Now you have to implement the calculateDifference() inside <script> tag to actually perform the difference:
function calculateDifference() {
// Get both values from input field and convert them into Javascript Date object
var date1 = new Date($("#date1").val());
var date2 = new Date($("#date2").val());
// Difference can be calculated by subtracting the first date timestamp from second date timestamp
var timeDifference = date2.getTime() - date1.getTime();
// Just for debugging purpose
console.log(timeDifference);
}
At this point, when you click the button, you will be able to see the difference in timestamp in your browser console. You can open the browser console by right clicking in empty area and select “Inspect element”. The 2nd tab should be named “Console”.
Now you have to convert this timestamp in days. As the timestamp is in milliseconds, you first have to convert them in seconds, then in hours, then finally in days.
// There are 1000 milliseconds in 1 second
var milliSecondsInOneSecond = 1000;
// There are 3600 seconds in 1 hour
var secondsInOneHour = 3600;
// And we all know there are 24 hours in 1 day
var hoursInOneDay = 24;
We have to divide this timestamp by the product of these 3 variables:
var days = timeDifference / (milliSecondsInOneSecond * secondsInOneHour * hoursInOneDay);
console.log(days);
If you check your browser console now, you will be able to view the difference of your 2 selected dates in days.
From database MySQL value
We are using a sample database called classicmodels, it will be included in the source files at the end of this page. We have a table called orders and 2 columns requiredDate and shippedDate. Subtracting shipped date from required date to know how many days it will take to send the product.
$days = $requiredDate – $shippedDate;
First we have to connect with database and get the record:
Now you have to convert these 2 datetime values in timestamp by using the PHP built-in function strtotime(). Then you can apply the same formula as above to convert milliseconds to days.
// Converting both values in timestamp milliseconds
$date1 = strtotime($row->shippedDate);
$date2 = strtotime($row->requiredDate);
// Calculating the difference in milliseconds
$date_difference = $date2 - $date1;
// Converting milliseconds into days
$days = round($date_difference / (60 * 60 * 24));
echo $days;