How to view error from AJAX, Javascript – Laravel

When you are calling an AJAX in Laravel, you will see a “500 – Internal Server Error” if there is an error in your PHP code. To see the actual error, kindly follow this article. We will teach you in this tutorial, how you can view error from your AJAX request.

Suppose I am calling an AJAX request in Laravel using core Javascript (no jQuery), then your code will be like this:

Javascript AJAX

var ajax = new XMLHttpRequest();
ajax.open("POST", document.getElementById("base-url").value + "/ajax-test", true);

ajax.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
        console.log(this.responseText);
    }

    if (this.status == 500) {
        console.log(this.responseText);
    }
};

var formData = new FormData();
formData.append("_token", document.querySelector("meta[name=_token]").content);
ajax.send(formData);

Line #1: I have created an AJAX object.

Line #2: I have opened the AJAX request with the POST method and the URL where the request will be sent. The third parameter (true, false) is the asynchronous boolean.

Note: All modern browsers recommend this value to be true.

Line #4: An event listener that will be called each time the status of request is changed.

#5: Check if the request is successful and the response has been received from server.

#6: Display the response from the server in browser console.

#9: Check if there is an internal server error. If yes, then display that error in line #10.

#14: New form data object is created that will send the data with an AJAX request.

#15: A CSRF (cross-side request forgery) token is appended in the form data object. We will create that meta tag later in this article.

Note: Every POST request in Laravel requires a CSRF token to be sent along with request.

Line #16: Sending the AJAX request along with form data object values.

You can create the hidden base URL and CSRF token tags as follows:

<input type="hidden" id="base-url" value="{{ url('/') }}">
<meta name="_token" content="{{ csrf_token() }}">

Now, whatever the error you are having on your server-side, in route, or in the controller, you will see that in your browser console window.

jQuery AJAX

If you are using jQuery to send an AJAX request and not seeing the actual error from your server-side, then change your jQuery AJAX function to the following:

$.ajax({
    url: document.getElementById("base-url").value + "/ajax-test",
    method: "POST",
    data: formData,
    processData: false,
    contentType: false,
    success: function (response) {
        console.log(response);
    },
    error: function (xhr) {
        console.log(xhr.responseText);
    }
});

Now, if you have an error in your AJAX request, you can view it in the “error” callback. Learn how to convert a simple POST request into an AJAX request following this tutorial.

[wpdm_package id=’938′]

Dynamic custom carousel – HTML & Javascript

In this article, we are going to teach you how you can create a dynamic custom carousel. If you are a web developer, you might have already came across with bootstrap carousel, which is basically a slider. Although, it shows you the functionality to show slides, move next/previous and many more. But nothing gives you more control than writing the code by yourself. Sometimes, you just want to learn the algorithms that how these sliders are created. So we will create a dynamic custom carousel using HTML, Javascript & PHP. If you do not want to fetch the slider images from database, you can skip the PHP part and jumps to the Javascript part.

What we are going to do ?

We will be fetching data from database and display in slides, thus makes our custom carousel dynamic. The database we will be using is named “tutorials” and the table whom we will be fetching data is “posts”. It has 3 fields (id, title, image). We will not be using ID attribute, it is just for unique identification and relationship between different tables. We will be displaying title and image in each slide.

First, create a database named “tutorials”. Create a table named “posts” and insert data in it using the following query:

CREATE TABLE `posts` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `title` text NOT NULL,
  `image` text NOT NULL
);

--
-- Dumping data for table `posts`
--

INSERT INTO `posts` (`id`, `title`, `image`) VALUES
(1, 'image 1', 'https://i.pinimg.com/originals/f8/d9/a7/f8d9a791ed9cd56f4970513d8797459d.png'),
(2, 'image 2', 'https://i.pinimg.com/564x/32/93/81/32938198ee16b5b2339a9071c8eb454f.jpg'),
(3, 'image 3', 'https://i.pinimg.com/564x/f3/ac/41/f3ac41a686ceff77bf9473827df5476c.jpg');

Slides

Then you need to connect with its database using PHP and fetch all the images for slider. Again, you can create a simple PHP array and enter the URL of all the images and their titles which you wanted to be displayed in each slide. But in most of the cases, there are images which are added from admin panel. In this case, you need to simply fetch all images from that table and display them in slides.

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

    $result = mysqli_query($conn, "SELECT * FROM posts");

    $count = 0;
    $posts = array();
    while ($row = mysqli_fetch_object($result)):
        array_push($posts, $row);
        ?>

        <div class="post <?php echo $count == 0 ? 'active' : ''; ?>">
            <p><?php echo $row->title; ?></p>
            <img src="<?php echo $row->image; ?>" style="width: 500px;">
        </div>

        <?php
        $count++;
    endwhile;
?>

You have seen that we created a <div> tag and it has 2 classes, post & active. But active class will be given only to the first div element. This is because we want to show the first slides first. To display other slides we will create 2 buttons next & previous. We have also created a PHP array $posts which will have all the slides. Use this variable to move next and previous slides. We will also teach you how you can convert a PHP variable, object or an array into a Javascript variable. For each slide, we are displaying its title and an image. Now we will apply some CSS to hide the slides which does not have a class “active”. And display the only slide which has an “active” class.

<style>
    .post {
        display: none;
    }
    .post.active {
        display: block;
    }
</style>

Slide indicators

Now we will create a <div> which will hold the next and previous slides indicators. If you have ever used bootstrap carousel then you might already be familiar with it. If you are not, indicators are the buttons which are used to show the next or previous slide. The basic algorithm is, if the next indicator is clicked, then you get next slide <div> element, hide the currently active <div> and show the next slide. Same goes for previous indicator, only different is, you have to get the previous <div> element instead of the next. We will also be displaying next slide’s name so the user can know which slide will be displayed next. It will be treated just as a reference.

<div class="links">
    <div class="previous-post" onclick="showPrevious();">
        <div style="display: contents; cursor: pointer;">
            <p>
                <b>previous post</b>
            </p>

            <p id="previous-post-title"></p>
        </div>
    </div>

    <div class="next-post" onclick="showNext();" style="margin-left: 100px;">
        <div style="display: contents; cursor: pointer;">
            <p>
                <b>next post</b>
            </p>

            <p id="next-post-title"></p>
        </div>
    </div>
</div>

Using PHP variable in Javascript

Now we will come to the part where we promised that we will teach you how you can convert a PHP variable into a Javascript variable. If you have followed the tutorial so far, you might already have a $posts PHP array. Now you want to use this in your Javascript code. Simply we will create a hidden input field, give it an ID so we can get it in Javascript. And set the value to that PHP array. But since $posts is an array, so we have to convert that into JSON format. We can do that simply by calling a PHP built-in function json_encode. Now when the array is converted into JSON, some characters might create trouble for you while setting it as a value of input field. So you have to wrap your function inside another PHP built-in function htmlentities.

<input type="hidden" id="posts" value="<?php echo htmlentities(json_encode($posts)); ?>">

Next and previous slide

Now when the page loads, we will get this input field value using its ID. Since we converted that into JSON, now we have to parse it in Javascript objects or array. We can do that by simply calling a function JSON.parse. It will convert the PHP variable into a proper Javascript variable. Now you can use this array anywhere in your Javascript code. The following code will show the next indicator only if there is a slide afterwards. Similarly it will show the previous indicator only if there is a slide before.

<script>
    var currentIndex = 0;

    window.addEventListener("load", function () {
        postsArray = document.getElementById("posts").value;
        postsArray = JSON.parse(postsArray);

        renderTitle();
    });

    function showPrevious() {
        currentIndex--;

        var previous = document.querySelector(".post.active").previousElementSibling;
        document.querySelector(".post.active").className = "post";
        previous.className = "post active";

        renderTitle();
    }

    function showNext() {
        currentIndex++;

        var next = document.querySelector(".post.active").nextElementSibling;
        document.querySelector(".post.active").className = "post";
        next.className = "post active";

        renderTitle();
    }

    function renderTitle() {
        document.querySelector(".previous-post").style.visibility = "hidden";
        document.querySelector(".next-post").style.visibility = "hidden";

        if (postsArray[currentIndex + 1] != null) {
            document.querySelector(".next-post").style.visibility = "visible";
            document.getElementById("next-post-title").innerHTML = postsArray[currentIndex + 1].title;
        }

        if (postsArray[currentIndex - 1] != null) {
            document.querySelector(".previous-post").style.visibility = "visible";
            document.getElementById("previous-post-title").innerHTML = postsArray[currentIndex - 1].title;
        }
    }
</script>

Explanation

You can also see the renderTitle() function, we will come back to that later. First we created a variable named currentIndex and initialize it with 0. That is the index of current slide visible to the user.

When the next or previous indicator is clicked, we are calling a function which will increment the value of currentIndex if next indicator is clicked. And decrement the value if previous indicator is clicked.

Then we are getting the next slide’s <div> using nextElementSibling and removing the “active” class from currently active slide. Finally we are setting the “active” class to next slide. That’s how current slide will be hidden and next slide will be displayed.

renderTitle()

Now come to the renderTitle() function. It is called 3 times, one when the page loads, one when next slide indicator is clicked. And one when previous slide indicator is clicked. This function has 3 purposes: first to hide both next and previous slide indicators. Second is to show the next indicator only if there is a slide next. Similarly show the previous indicator only if there is a slide before.

We already have a postsArray array which holds all the slide elements so we can check easily. Third purpose of this function is to show the title of next and previous slide. So, the user can know on which slide he is going to see next.

Hope this tutorial helps you create your own dynamic custom carousel which you can customize and design as per your need. You can add more features to it if you want. Try adding CSS animations, like making the slide move left or right when next and previous is clicked.

Also try to change the slide automatically after 5 seconds. The list of features can go on because it is a dynamic custom carousel and anyone can add more features in it as per needs. If you a minimalism lover, then you can also remove elements from it which you do not like. For example, you can remove the next and previous slide title to make space and make it more minimal.

Movie ticket booking website – PHP and MySQL

A movie ticket booking website is created in PHP and MySQL following the principles of Object-Oriented Programming (OOP) and Model-View-Controller (MVC). Google Adsense supported. CSRF (Cross-site Request Forgery) is protected.

FeaturesFreePremium
User authenticationYesYes
Admin loginYesYes
Add, edit, and delete categoriesYesYes
Add, edit, and delete moviesYesYes
Add, edit, and delete cinemasYesYes
Add, edit, and delete celebritiesYesYes
Set cast of each movieYesYes
Show currently playing movies in all cinemasYesYes
Show biography and filmography of celebritiesYesYes
Book tickets onlineNoYes
SeasonsNoYes
Receive payments from Stripe & PayPalNoYes

Demo

Free version:

https://drive.google.com/file/d/16fmMA5tDe6VqzhDmJ_KvwvaDvrojKscJ/view?usp=sharing

Feature list:

  1. Admin login.
  2. Add, Edit, and Delete categories.
  3. CRUD operation on movies.
  4. Add, Edit, Delete cinemas.
  5. Play movies in cinemas.
  6. Add, Edit, Delete celebrities.
  7. Add cast in movies.
  8. Show currently playing movies in all cinemas.
  9. Login and registration.
  10. User home.
  11. Movie detail.
  12. Show biography and filmography of celebrities.
  13. Seasons
  14. Receive payments online (Stripe & PayPal)

How to setup:

Our TrustPilot reviews

TrustPilot-reviews
TrustPilot-reviews

Difference between onload and addEventListener – Javascript

Learn the difference between onload and addEventListener event listeners in Javascript. If you are creating a website and you want to perform some action in Javascript when the page is fully loaded, there are 2 ways to do this:

  1. window.onload
  2. window.addEventListener

Both are the events which are called when the page is fully loaded. But there is a big difference that matters when you are creating large projects. Difference is that, window.onload event will only be called once, and it will override the previously attach onload event. While on the other hand, using window.addEventListener you can add as many functions as you want and they will all be called in parallel.

For example, take the following code:

// Using window.onload event twice
window.onload = function () {
    console.log("onload 1");
};

window.onload = function () {
    console.log("onload 2");
};

// Using window.addEventListener event twice
window.addEventListener("load", function () {
    console.log("addEventListener 1");
});

window.addEventListener("load", function () {
    console.log("addEventListener 2");
});

We are attaching first onload event and are displaying “onload 1” in browser console. Second onload event will display the message “onload 2” in console. Similarly, we added 2 events but this time using addEventListener function. The first parameter will be the name of event which is “load”, and second will be the function that will be called.

Results

You will see that we are calling both events 2 times to see which one called twice. If you run the above code in your Javascript file, you will see the following lines in your console:

This is because the window.onload is an attribute, like a variable. When you use this event 2nd time, then its previous function is replaced by the new one. Same as like you update the variable’s value. You can notice that the syntax is window.onload = function () {} which means that it is an attribute whose value can be replaced.

On the other hand, window.addEventListener you can see that it is a function. You can tell because it has parenthesis () and we know that if there is an parenthesis at the end of any name then it must be a function. You can also see that it has 2 parameters, functions does has parameters too. So when you call this event and pass your function in the second parameter, it will be placed in a stack of “load” events. That is why all functions of addEventListener are called without overriding.

Conclusion

We highly recommend that you should make your habit of using the window.addEventListener as it is more reliable. Because it happens sometimes that your window.onload function was not being called and you wonder why it is not being called, and the reason is simple: “Somewhere else in the code this attribute is being overriden by another function”.

Hopefully you would have known the difference between onload and addEventListener now.

If you find this article helpful, please do share with others. So, if someone else is having this problem or confusion, then it can be solved.

PHP vs Javascript – Performance test

We are going to do a performance test on getting the data from MySQL database using PHP vs getting data from MySQL database using AJAX in Javascript. We have a database named classicmodels and a table named orderDetails.

In both the cases, we are fetching data from MySQL database with the help of PHP. But in 1st case, we load the data directly via PHP. And in 2nd case, we load the data via AJAX. It is basically loading the data PHP vs Javascript.

Following is a code that will get the data from database using PHP:

<table>
    <tr>
	    <th>Order number</th>
	    <th>Product code</th>
	    <th>Quantity ordered</th>
	    <th>Price each</th>
	    <th>Order line number</th>
    </tr>
 
    <?php
        $conn = mysqli_connect("localhost:8889", "root", "root", "classicmodels") or die(mysqli_connect_error());
    
        $sql = "SELECT * FROM orderdetails";
        $result = mysqli_query($conn, $sql);

        $data = array();
        while ($row = mysqli_fetch_object($result))
        {
            ?>

            <tr>
                <td><?php echo $row->orderNumber; ?></td>
                <td><?php echo $row->productCode; ?></td>
                <td><?php echo $row->quantityOrdered; ?></td>
                <td><?php echo $row->priceEach; ?></td>
                <td><?php echo $row->orderLineNumber; ?></td>
            </tr>

            <?php
        }
    ?>
</table>

We have created a table with 5 columns. Then we are making a connection with the MySQL database. Then we are getting all the data from orderDetails table. We are using a while loop to loop through all records and mysqli_fetch_object function will return the next row in each iteration. When we use PHP to get data from the database, we get the following results in performance:

performance test php
performance test php

Now we use the same database, same table, the same number of records, and the same output. In order to get the data using Javascript, we need to create an HTML tag for the table. No need to run any PHP query, not even connection with the database. Give a unique ID to the tag where you want to display all data, in this case, we want to show the data in the table so we have given an ID to tbody tag. Then we are sending an AJAX (no jQuery needed) to test.php file and when the response is received from that file, then we display that data in tbody tag. The response sent from test.php is JSON string so we have to decode that using Javascript JSON.parse function.

index.php

<table>
    <tr>
	    <th>Order number</th>
	    <th>Product code</th>
	    <th>Quantity ordered</th>
	    <th>Price each</th>
	    <th>Order line number</th>
    </tr>
 
    <tbody id="data"></tbody>
</table>
 
<script>
    var ajax = new XMLHttpRequest();
    ajax.open("POST", "test.php", true);
    ajax.send();
 
    ajax.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {

        	console.log(this.responseText);
            var data = JSON.parse(this.responseText);
            console.log(data);
 
            var html = "";
            for(var a = 0; a < data.length; a++) {
                html += "<tr>";
                    html += "<td>" + data[a].orderNumber + "</td>";
                    html += "<td>" + data[a].productCode + "</td>";
                    html += "<td>" + data[a].quantityOrdered + "</td>";
                    html += "<td>" + data[a].priceEach + "</td>";
                    html += "<td>" + data[a].orderLineNumber + "</td>";
                html += "</tr>";
            }
            document.getElementById("data").innerHTML += html;
        }
    };
</script>

Now we need to create a file that will handle that AJAX request. This code will be almost same as we did in simple PHP, but instead of displaying all data, we are adding all data in an array and sending that array as a JSON string to AJAX response using PHP built-in json_encode() function.

test.php

<?php

	$conn = mysqli_connect("localhost:8889", "root", "root", "classicmodels") or die(mysqli_connect_error());
	
	$sql = "SELECT * FROM orderdetails";
	$result = mysqli_query($conn, $sql);

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

And these are the results we get when we fetch data from database using Javascript and AJAX:

performance test PHP
performance test javascript
performance test javascript

Conclusion

PerformancePHPJavascript
Page speed74%93%
Time to load page8.6 seconds5.5 seconds
Page size1.24 MB966 KB
Requests14062

[wpdm_package id=’475′]

Count words as user type – Textarea & Javascript

Demo

In this tutorial, we are going to teach you how you can count the number of words in textarea as user type in it. The first thing you need to do is to attach an onkeyup listener to your textarea tag. This function will be called whenever user pressed the key. Specifically, when the user’s finger is moving upwards after pressing the key, then this event is called. In this function, we are passing a parameter this means current node, which is textarea tag.

<textarea onkeyup="countWords(this);"></textarea>
<span id="words-counter"></span>

Then we created a span tag, you can create a div or paragraph as well. Give that span tag a unique ID so it can be accessible in Javascript. We will be displaying the number of words in this span tag.

Then we create this function in Javascript, first, we are getting the current text inside textarea field using the value attribute. Then we are applying a regular expression which states that:

Count the number of words
separated by spaces.

This will return an array, we simply have to calculate the length of that array. We are using a ternary operator to get value as 0 if the spaces array is null. Finally, we are displaying that length in the span tag using plain Javascript.

function countWords(self) {
	var spaces = self.value.match(/\S+/g);
	var words = spaces ? spaces.length : 0;

	document.getElementById("words-counter").innerHTML = words + " words";
}

That’s how you can count the number of words as user type in an input field using plain HTML and Javascript.Specifically in a <textarea> tag.

Shuffle an array of objects – Javascript

To shuffle an array of objects or single values in Javascript, use the following function:

for (var a = 0; a < data.length; a++) {
	var x = data[a];
	var y = Math.floor(Math.random() * (a + 1));
	data[a] = data[y];
	data[y] = x;
}

First, we are looping through all array elements. data is our array of objects. First, we are saving the current array element in a separate variable named x. Then we are generating a random number. Math.random() will return a random number between 0.0 and 0.9. As our loop start from 0, so we are multiplying that random number by loop iteration number + 1. Since the number will be in floating points, so we can convert that into an integer by calling Math.floor() function. The floor function will round the number downwards and return it as an integer. That is now the index of the random element in the array.

Then we are replacing the current array element with this random array element. And finally, replace this random array element with the current element of loop.

This is the simplest way to shuffle an array of objects using vanilla Javascript. For more Javascript tutorials, please follow here.

Confirmation dialog before deleting data – Javascript, PHP

In this tutorial, we are going to teach you how you can show a confirmation dialog before deleting any data using Javascript. Suppose you are displaying a lot of data in tabular form in the admin panel, and you have a delete button at the end of each row. Now when someone clicks on it, you may be submitting a form with POST request or redirecting to a page where that data will be deleted. But what if someone accidentally clicks on any row, or clicks the wrong row? Then that row will be deleted from the database.

Alternative

One alternative thing you can do is to put the deleted data in the trash. That will add extra work on the developer side as well as on the user side. Because you have to create a table where trashed data will be stored, then create another page on the admin panel to display trashed data and also the ability to delete or restore the trashed data. You can see that there are 6 or 7 more functions that you have to write. Moreover, there will be extra work for users too, they also have to delete the trashed data regularly.

A simple approach

A simple approach displays a confirmation dialog when the delete button is clicked. Show simple 2 buttons, “Cancel”, “Delete”. When the delete button is clicked from confirmation dialog, then send the request to delete that data from the database. You may encounter yourself in 2 minor problems in this approach. First is “how can I display a confirmation dialog ?”, you can either display javascript native function confirm() but it may not look good with your website design.

People want a more personal look, whenever you are displaying a dialog box, whether it is alert dialog or confirmation dialog, make sure that it goes with the look and feel of your website design. Or you can use external libraries like Sweetalert, so you have to download that library, include in your project, and use their functions. But sometimes you do not have your project flooded with external libraries. You may ask yourself “why to include an external library when I can do it in my design framework ?”

As we know that today almost every website is using Bootstrap and your project will also be using a large portion of the Bootstrap framework. So we are going to use Bootstrap to display a confirmation dialog. In Bootstrap, they are called “modal”.

Bootstrap modal

Bootstrap modal can be created by creating a <div> tag and give it a unique ID, also a class named “modal”. There will be 2 inner nested divs, one with class “modal-dialog” and second having class “modal-content”. Modal content div will have 3 sections:

  1. modal-header
  2. modal-body
  3. modal-footer

What we are going to do is to show heading in modal-header div, and create a form in modal-body div, in this form we will create a hidden input field which will be the unique ID of row which needs to be deleted from database. Set the form action attribute to the page where you will handle to perform the delete action. In modal-footer, we will simply create a submit button which will be linked with that form using form attribute. Make sure the form attribute on submit button will be same as form id attribute.

<div id="myModal" class="modal">
	<div class="modal-dialog">
		<div class="modal-content">
			
			<div class="modal-header">
				<h4 class="modal-title">Delete User</h4>
				<button type="button" class="close" data-dismiss="modal">×</button>
			</div>

			<div class="modal-body">
				<p>Are you sure you want to delete this user ?</p>
				<form method="POST" action="delete-user.php" id="form-delete-user">
					<input type="hidden" name="id">
				</form>
			</div>

			<div class="modal-footer">
				<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
				<button type="submit" form="form-delete-user" class="btn btn-danger">Delete</button>
			</div>

		</div>
	</div>
</div>

Confirmation dialog – Javascript

Now create a delete button (or change if you already have one) such that it has an attribute data-id and its value must be the unique ID of that row. Attach an onclick listener which will be called whenever that button is clicked. In this event, we are calling a function named confirmDelete. You can create this delete button inside your table row where you are displaying all data from the database (typically in while() loop).

<button type="button" class="btn btn-danger" data-id="<?php echo $row->id; ?>" onclick="confirmDelete(this);">Delete</button>

Now when the button is clicked, we want to set the value of the hidden input field inside the bootstrap modal form to the id of the selected row. Then we will show the confirmation modal. Create the following function in <script> tag:

function confirmDelete(self) {
	var id = self.getAttribute("data-id");

	document.getElementById("form-delete-user").id.value = id;
	$("#myModal").modal("show");
}

Make sure you have given a name attribute to the hidden input field. It will help you to set the value using Javascript before displaying the confirmation dialog. Also, the name attribute is used at the server-side to get the values. Now you will be asked for confirmation before deleting any data from the database WITHOUT USING ANY EXTERNAL LIBRARY other than Bootstrap.

If you are developing backend in PHP, then you can get this value using $_POST[“id”].

[wpdm_package id=’441′]

Calculate time passed since date in days, hours, minutes and seconds – Javascript, PHP

Demo

Convert time to different timezones

Today, we will learn to calculate the time passed since date in days, hours, minutes and seconds. Either you are receiving values in PHP variable from MySQL database, or you are calling an AJAX request, this tutorial will help you in both situations. We will also display the hours, minutes and seconds in leading zeroes. So you will not see time as “7:9:3” but you will see that as “07:09:03” using leading zeroes. We already uploaded 1 more tutorial on calculating the time remaining. If you want to caclulate the remaining time in future date, you can follow our tutorial on that as well:

Calculate remaining time

Calculate time passed

Basically, we are going to get the difference between future date and current date. Then we will extract the days, hours, minutes and hours from that difference. Difference will be in seconds so we have to apply some math on it. First we assume that you are already receiving the value from your MySQL database in PHP variable. We have set the PHP variable below but you can use your own database value:

<?php
	$date = "2020-06-07 23:39:00";
?>

Then we will create a <div> where we will display the time passed and a hidden input field to get the PHP variable value in Javascript.

<div id="data"></div>

<input type="hidden" id="date" value="<?php echo $date; ?>">

JS function when page loads

Then create a Javascript function which will be called once simply when the page loads. And then in a setInterval function which will be called each second, so we will display the time passed in seconds as well. We will get 2 date objects, first will be current date and second will be date in future which we are getting from PHP variable.

Get difference in timestamps

Then we will get the timestamp from both dates in milliseconds using getTime() function. Dividing that by 1000 will convert that in seconds. But we will also get the floating numbers when dividing, we can prevent the floating number by calling toFixed(0) function. Since toFixed() function returns a string which will not be helpful in getting the difference between 2 dates, so we have to convert that in double or float. We can do that by calling Math.abs() function, it will return the absolute value. Then we subtract the future timestamp from current timestamp and save that in a variable diff as difference.

This diff variable is also in seconds, now we have to convert that value into days, hours, minutes and seconds. We know that there are 86400 seconds in each day, so dividing the difference by 86400 will return the number of days remaining. And since dividing also cause floating number, so we can prevent that by calling Math.floor() function. It will round the value to the previous number.

For example, if the value is 23.7 then it will return as 23. Time to get the remaining hours, we know that there are 3600 seconds in each hour, so we will divide that difference by 3600, round the value to floor. And since there are 24 hours in each day, so we have to take the modulus by 24. Taking modulus will divide the value and return the remainder.

Get difference in minutes

To get the minutes, we know that there are 60 seconds in each minute and 60 minutes in each hour. So we divide the difference by 60, round the value by floor, then take the modulus by 60. That will return the number of minutes passed since date. To get the seconds, is the simplest among all.

We know the limit for seconds is 60, so we simply take the modulus of difference by 60 and it will return the seconds. If you want to show the leading zeros i.e. zeroes on left if value is less than 10, then you can also put a condition on days, hours, minutes and seconds. Check if the value is less than 10, then prepend the “0” with value. And finally display that in our <div id=”data”></div>

Make sure to call the function in setInterval to update the value each second.

<script>
	function func() {
		var dateValue = document.getElementById("date").value;

		var currentDate = Math.abs((new Date().getTime() / 1000).toFixed(0));
		var futureDate = Math.abs((new Date(dateValue).getTime() / 1000).toFixed(0));

		var diff = currentDate - futureDate;

		var days = Math.floor(diff / 86400);
		var hours = Math.floor(diff / 3600) % 24;
		var minutes = Math.floor(diff / 60) % 60;
		var seconds = diff % 60;

		if (days < 10) {
			days = "0" + days;
		}

		if (hours < 10) {
			hours = "0" + hours;
		}

		if (minutes < 10) {
			minutes = "0" + minutes;
		}

		if (seconds < 10) {
			seconds = "0" + seconds;
		}

		document.getElementById("data").innerHTML = days + " days, " + hours + ":" + minutes + ":" + seconds;
	}

	func();
	setInterval(func, 1000);
</script>

[wpdm_package id=’432′]