Stripe Payment Gateway – Javascript, PHP

In this tutorial, we are going to teach you how you can receive payments online with Stripe using simple Javascript and PHP.

Video Tutorial:

Installing Stripe PHP SDK

First, you need to open the command prompt or terminal in your project’s root folder and run the following command. Make sure you have the composer installed, if not, you can download it from here.

COMPOSER_MEMORY_LIMIT=-1 composer require stripe/stripe-php

After that, you need to go to stripe.com and go to the Developers page (from the top menu) and then the API keys section. You can directly visit this page. Copy the secret key, you will need it in the next step.

Client-Side : Receive the Payment

The following code will create a payment intent for 10 USD 💰, but you can change it as per your need:

<?php

	require_once "vendor/autoload.php";

	$amount = 10;

	$stripe = new \Stripe\StripeClient("{your_secret_key}");

	// creating setup intent
    $payment_intent = $stripe->paymentIntents->create([
        'payment_method_types' => ['card'],

        // convert double to integer for stripe payment intent, multiply by 100 is required for stripe
        'amount' => round($amount) * 100,
        'currency' => 'usd',
    ]);

?>

<input type="hidden" id="stripe-public-key" value="{your_publishable_key}" />
<input type="hidden" id="stripe-payment-intent" value="<?php echo $payment_intent->client_secret; ?>" />

<!-- credit card UI will be rendered here -->
<div id="stripe-card-element" style="margin-top: 20px; margin-bottom: 20px;"></div>

<button type="button" onclick="payViaStripe();">Pay via stripe</button>

<!-- billing details is required for some countries -->
<input type="hidden" id="user-email" value="support@adnan-tech.com" />
<input type="hidden" id="user-name" value="AdnanTech" />
<input type="hidden" id="user-mobile-number" value="123456789" />

<!-- include Stripe library -->
<script src="https://js.stripe.com/v3/"></script>

<script>
    // global variables
    var stripe = null;
    var cardElement = null;

    const stripePublicKey = document.getElementById("stripe-public-key").value;

    // initialize stripe when page loads
    window.addEventListener("load", function () {
        stripe = Stripe(stripePublicKey);
        var elements = stripe.elements();
        cardElement = elements.create('card');
        cardElement.mount('#stripe-card-element');
    });
</script>

Make sure to write your secret key (line #7) and publishable key (line #20). For billing details, you can show your user’s details dynamically from the database, etc. Contact us if you face any problems in this step.

If you refresh the page now, you will see an input field to enter your debit card number, CVV, and expiry date. And a button that says “Pay via stripe“. On clicking that button, nothing happens.

So we will create a function that will be called when this button is clicked and it will make the payment. So, create the following Javascript function:

function payViaStripe() {
	// get stripe payment intent
    const stripePaymentIntent = document.getElementById("stripe-payment-intent").value;

    // execute the payment
    stripe
        .confirmCardPayment(stripePaymentIntent, {
            payment_method: {
                    card: cardElement,
                    billing_details: {
                        "email": document.getElementById("user-email").value,
                        "name": document.getElementById("user-name").value,
                        "phone": document.getElementById("user-mobile-number").value
                    },
                },
            })
            .then(function(result) {

                // Handle result.error or result.paymentIntent
                if (result.error) {
                    console.log(result.error);
                } else {
                    console.log("The card has been verified successfully...", result.paymentIntent.id);

                    // [call AJAX function here]
                }
            });
}

Refresh the page now and try to make the payment now. You can use the following information for testing the payment:

Debit Card Number4242 4242 4242 4242
CVV422
Expiry date (month)04
Expiry date (year)27
Stripe sandbox testing payment information

You will see a payment ID in the console if the payment is successful. Now we need to validate this payment from the server-side as well.

Server Side : Verify the Payment

The following code goes in the [call AJAX function here] section of the previous step. We will call an AJAX to the server with the payment ID to verify this payment.

confirmPayment(result.paymentIntent.id);

Then we need to create this function in Javascript:

function confirmPayment(paymentId) {
    var ajax = new XMLHttpRequest();
    ajax.open("POST", "stripe.php", true);
 
    ajax.onreadystatechange = function () {
        if (this.readyState == 4) {
            if (this.status == 200) {
                var response = JSON.parse(this.responseText);
                console.log(response);
            }
 
            if (this.status == 500) {
                console.log(this.responseText);
            }
        }
    };
 
    var formData = new FormData();
    formData.append("payment_id", paymentId);
    ajax.send(formData);
}

After that, we need to create a file named stripe.php that will handle this request. You can set the server file as your own. The following code goes in the stripe.php file:

<?php

	require_once "vendor/autoload.php";

	$stripe = new \Stripe\StripeClient('{your_secret_key}');

	try
	{
		$payment = $stripe->paymentIntents->retrieve(
			$_POST["payment_id"],
			[]
		);

		if ($payment->status == "succeeded")
		{
			echo json_encode([
				"status" => "success",
				"payment" => $payment,
			]);
			exit();
		}
	}
	catch (\Exception $exp)
	{
		echo json_encode([
			"status" => "error",
			"message" => $exp->getMessage()
		]);
		exit();
	}

Make sure to replace your own secret key in line #5. Refresh the page now and try to make another payment, now you will see 2 console messages.

  1. The first console message will tell the payment ID if the payment is made, or an error message otherwise.
  2. The second console message will be the response sent from the server, whether the payment is verified or not.

You can also check the payment from your Stripe dashboard directly from here.

For Laravel Developers

If you are developing your application in Laravel, you do not need to write the require_once line.

So now you have learned how to integrate stripe in your website using Javascript and PHP. You can also learn how to receive donations from Stripe on your WordPress website for non-profit organizations.

PayPal Javascript PHP SDK

In this tutorial, we are going to teach you how you can receive payments online via the PayPal payment gateway using Javascript and PHP. This tutorial uses simple Javascript and PHP, so you will be able to apply this tutorial to any framework like React, Vue, Laravel, etc.

It also goes with any backend framework like Laravel, WordPress, or even if your backend is in Node JS or Python, not just PHP.

Video Tutorial: (Client-Side)

Server side:

# Step 1

The first step is to include PayPal Javascript SDK in your website. Paste the following code into your HTML page where you want to receive the payments.

<!-- Load the required checkout.js script -->
<script src="https://www.paypalobjects.com/api/checkout.js" data-version-4></script>

<!-- Load the required Braintree components. -->
<script src="https://js.braintreegateway.com/web/3.39.0/js/client.min.js"></script>
<script src="https://js.braintreegateway.com/web/3.39.0/js/paypal-checkout.min.js"></script>

Refresh the page now and check your browser console, if all goes well, then you are ready to render the payment button.

# Step 2

Then you need to go to this link and create an app on your PayPal dashboard and copy the Client ID of both (Sandbox and Live) accounts.

# Step 3

Finally, you need to render the payment button using the following code:

<!-- paypal button will be rendered here using Javascript -->
<div id="btn-paypal-checkout"></div>

<script>
    window.addEventListener("load", function () {
        var cartItems = [{
            name: "Product 1",
            description: "Description of product 1",
            quantity: 1,
            price: 50,
            sku: "prod1",
            currency: "USD"
        }, {
            name: "Product 2",
            description: "Description of product 2",
            quantity: 3,
            price: 20,
            sku: "prod2",
            currency: "USD"
        }, {
            name: "Product 3",
            description: "Description of product 3",
            quantity: 4,
            price: 10,
            sku: "prod3",
            currency: "USD"
        }];

        var total = 0;
        for (var a = 0; a < cartItems.length; a++) {
            total += (cartItems[a].price * cartItems[a].quantity);
        }

        // Render the PayPal button
        paypal.Button.render({

            // Set your environment
            env: 'sandbox', // sandbox | production

            // Specify the style of the button
            style: {
                label: 'checkout',
                size: 'medium', // small | medium | large | responsive
                shape: 'pill', // pill | rect
                color: 'gold', // gold | blue | silver | black,
                layout: 'vertical'
            },

            // PayPal Client IDs - replace with your own
            // Create a PayPal app: https://developer.paypal.com/developer/applications/create

            client: {
                sandbox: '',
                production: ''
            },

            funding: {
                allowed: [
                    paypal.FUNDING.CARD,
                    paypal.FUNDING.ELV
                ]
            },

            payment: function(data, actions) {
                return actions.payment.create({
                    payment: {
                        transactions: [{
                            amount: {
                                total: total,
                                currency: 'USD'
                            },
                            item_list: {
                                // custom cartItems array created specifically for PayPal
                                items: cartItems
                            }
                        }]
                    }
                });
            },

            onAuthorize: function(data, actions) {
                return actions.payment.execute().then(function() {
                    // you can use all the values received from PayPal as you want
                    console.log({
                        "intent": data.intent,
                        "orderID": data.orderID,
                        "payerID": data.payerID,
                        "paymentID": data.paymentID,
                        "paymentToken": data.paymentToken
                    });

                    // [call AJAX here]
                });
            },
            
            onCancel: function (data, actions) {
                console.log(data);
            }

        }, '#btn-paypal-checkout');
    });
</script>

Refresh the page now and you will a Paypal payment button. On clicking, will open the pop-up from Paypal itself from where your users can make the payment and it will automatically be received in your PayPal business account.

# Step 4

Now we need to validate the payment on the server-side. After payment is made, you might want to activate your user’s account or perform any action.

So you will call an AJAX to the server to perform that action, but the AJAX can be manipulated by the client-side. So the payment must be validated first.

Write the following code in the [call AJAX here] section:

paymentMade(data.orderID, data.payerID, data.paymentID, data.paymentToken);

Then you need to create a Javascript function that will call the AJAX request:

function paymentMade(orderID, payerID, paymentID, paymentToken) {
    var ajax = new XMLHttpRequest();
    ajax.open("POST", "paypal.php", true);

    ajax.onreadystatechange = function () {
        if (this.readyState == 4) {
            if (this.status == 200) {
                var response = JSON.parse(this.responseText);
                console.log(response);
            }

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

    var formData = new FormData();
    formData.append("orderID", orderID);
    formData.append("payerID", payerID);
    formData.append("paymentID", paymentID);
    formData.append("paymentToken", paymentToken);
    ajax.send(formData);
}

Now we need to create a PHP file named paypal.php that will handle this request. It will have the following code:

<?php

// show all errors
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// initialize CURL
$ch = curl_init();

// set path to PayPal API to generate token
// remove "sandbox" from URL when in live
curl_setopt($ch, CURLOPT_URL, 'https://api-m.sandbox.paypal.com/v1/oauth2/token');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "grant_type=client_credentials");
// write your own client ID and client secret in following format:
// {client_id}:{client_secret}
curl_setopt($ch, CURLOPT_USERPWD, '{client_id}:{client_secret}');

// set headers
$headers = array();
$headers[] = 'Accept: application/json';
$headers[] = 'Accept-Language: en_US';
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

// call the CURL request
$result = curl_exec($ch);

// check if there is any error in generating token
if (curl_errno($ch))
{
    echo json_encode([
    	"status" => "error",
    	"message" => curl_error($ch)
    ]);
    exit();
}
curl_close($ch);

// the response will be a JSON string, so you need to decode it
$result = json_decode($result);

// get the access token
$access_token = $result->access_token;

// we only need the second part of orderID variable from client side
$payment_token_parts = explode("-", $_POST["orderID"]);
$payment_id = "";

if (count($payment_token_parts) > 1)
{
    $payment_id = $payment_token_parts[1];
}

// initialize another CURL for verifying the order
$curl = curl_init();

// call API and send the payment ID as parameter
curl_setopt($curl, CURLOPT_URL, 'https://api-m.sandbox.paypal.com/v2/checkout/orders/' . $payment_id);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET');

// set headers for this request, along with access token
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: Bearer ' . $access_token;
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

// executing the request
$result = curl_exec($curl);

// check if there is any error
if (curl_errno($curl))
{
    echo json_encode([
    	"status" => "error",
    	"message" => "Payment not verified. " . curl_error($curl)
    ]);
    exit();
}
curl_close($curl);

// get the response JSON decoded
$result = json_decode($result);

// you can use the following if statement to make sure the payment is verified
// if ($result->status == "COMPLETED")

// send the response back to client
echo json_encode([
	"status" => "success",
	"message" => "Payment verified.",
	"result" => $result
]);
exit();

Comments have been added with each line for an explanation. Now you will be able to accept payments online via PayPal Javascript and PHP SDK.

If you want to accept payments from the Stripe payment gateway too, you can check our tutorial on Stripe as well.

If you have any questions or facing any problems, feel free to contact us in the comments section below.

Note: I will add PayPal payment gateway in your website in just $5.

CRUD in Vue JS and PHP

In this tutorial, we are going to perform a complete CRUD (create, read, update, delete) operation using Vue JS and PHP. We will be using Vue JS for the frontend and PHP for backend processing. We will also be using PDO prepared statements for preventing SQL injection.

First, you need to download Vue JS from here and Bootstrap from here. You will also need to download jQuery from here as well. After that, you need to copy-paste the JS file from Vue JS in your project. You also need to copy-paste the CSS and JS files from Bootstrap too.

After downloading and placing in your project, you need to include these files as well.

<script src="vue.min.js"></script>

<link rel="stylesheet" type="text/css" href="css/bootstrap.css" />
<script src="js/jquery-3.3.1.min.js"></script>
<script src="js/bootstrap.js"></script>

Create

First thing is that you need to insert the data into the database. For the sake of this tutorial, we have created a simple table in our MySQL database. The table name is users and it has the following columns:

  1. id (auto increment)
  2. name
  3. email
  4. password

Then you need to create a form from which you can enter the details to save in the database.

<div id="myApp">
	<div class="container">
		<h1 class="text-center">Create</h1>

		<div class="row">
			<div class="offset-md-3 col-md-6">
				<form method="POST" action="create.php" v-on:submit.prevent="doCreate">
					<div class="form-group">
						<label>Name</label>
						<input type="text" name="name" class="form-control" />
					</div>

					<div class="form-group">
						<label>Email</label>
						<input type="email" name="email" class="form-control" />
					</div>

					<div class="form-group">
						<label>Password</label>
						<input type="password" name="password" class="form-control" />
					</div>

					<input type="submit" value="Create User" class="btn btn-primary" />
				</form>
			</div>
		</div>
	</div>
</div>

After that, we need to create a Vue JS app and a method that will call an AJAX request to the server.

<script>
	// initialize Vue JS
	const myApp = new Vue({
		el: "#myApp",
		methods: {

			doCreate: function () {
				const self = this;
				const form = event.target;

				const ajax = new XMLHttpRequest();
				ajax.open("POST", form.getAttribute("action"), true);

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

				const formData = new FormData(form);
				ajax.send(formData);
			}
		},
	});
</script>

Now create a file named create.php that will handle the request.

<?php

// connect database
$conn = new PDO("mysql:host=localhost:8889;dbname=test", "root", "root");

// prepare insert statement
$sql = "INSERT INTO users (name, email, password) VALUES (:name, :email, :password)";
$result = $conn->prepare($sql);

// execute the query
$result->execute([
	":name" => $_POST["name"],
	":email" => $_POST["email"],
	// encrypt password in hash
	":password" => password_hash($_POST["password"], PASSWORD_DEFAULT),
]);

echo "Done";

Refresh the page now and enter new user details and hit submit. Then go to your phpMyAdmin and refresh the users table and you will see a new row inserted in the database.

Read

Now the data is being inserted in the database but you should all the inserted data when the page loads. To create an HTML table:

<h1 class="text-center">Read</h1>

<table class="table">
	<tr>
		<th>ID</th>
		<th>Name</th>
		<th>Email</th>
	</tr>

	<tr v-for="(user, index) in users">
		<td v-text="user.id"></td>
		<td v-text="user.name"></td>
		<td v-text="user.email"></td>
	</tr>
</table>

In your Vue JS instance, create a data object, and inside that object create a users array.

data: {
	users: []
},

And when the Vue JS instance is mounted, we need to call a method to call an AJAX request to get the data.

// call an AJAX to fetch data when Vue JS is mounted
mounted: function () {
	this.getData();
}

After that, create a method in your methods object in the Vue JS instance:

// get all users from database
getData: function () {
	const self = this;

	const ajax = new XMLHttpRequest();
	ajax.open("POST", "read.php", true);

	ajax.onreadystatechange = function () {
		if (this.readyState == 4) {
			if (this.status == 200) {
				const users = JSON.parse(this.responseText);
				self.users = users;
			}
		}
	};

	const formData = new FormData();
	ajax.send(formData);
},

This will send an AJAX request but we need to create a server file that will handle this request. So create a file named read.php and the following will be the code of this file:

<?php

// connect database
$conn = new PDO("mysql:host=localhost:8889;dbname=test", "root", "root");

// get all users from database sorted by latest first
$sql = "SELECT * FROM users ORDER BY id DESC";
$result = $conn->prepare($sql);
$result->execute([]);
$data = $result->fetchAll();

// send all records fetched back to AJAX
echo json_encode($data);

Refresh the page now and you will be able to view all the records added to the database. But if you insert the new record again, you again have to refresh the page to see this new entry. However, newly inserted records should automatically be prepended at the top of the table.

So you need to modify your create.php and first return the newly inserted record from the database.

// get the latest record inserted
$sql = "SELECT * FROM users WHERE id = :id";
$result = $conn->prepare($sql);
$result->execute(array(
    ":id" => $conn->lastInsertId()
));
$data = $result->fetch();

// send the newly inserted record back to AJAX
echo json_encode($data);

Then in your Vue JS instance inside the doCreate method when the response is successfully received, prepend the new user in the users array.

const user = JSON.parse(this.responseText);

// prepend in local array
self.users.unshift(user);

Refresh the page now and try to insert a new user again. Now you will see that it will be prepended at the top automatically.

Update

To update the user we first must show a button to edit the user. To create a new column in your table:

<th>Actions</th>

And inside the v-for loop create a button for edit.

<td>
	<button type="button" v-bind:data-id="user.id" v-on:click="showEditUserModal" class="btn btn-primary">Edit</button>
</td>

Then you need to create a method in the methods object of your Vue JS instance that will be called when this button is clicked.

showEditUserModal: function () {
	const id = event.target.getAttribute("data-id");
	
	// get user from local array and save in current object
	for (var a = 0; a < this.users.length; a++) {
		if (this.users[a].id == id) {
			this.user = this.users[a];
			break;
		}
	}

	$("#editUserModal").modal("show");
},

Then you need to create another variable in your data object that will hold the information of the selected user.

user: null

The above-created function will display a Bootstrap modal to edit the user. Now we need to create that model in our HTML.

<!-- Modal -->
<div class="modal" id="editUserModal">
	<div class="modal-dialog" role="document">
		<div class="modal-content">
			<div class="modal-header">
				<h5 class="modal-title">Edit User</h5>
				<button type="button" class="close" data-dismiss="modal" aria-label="Close">
					<span aria-hidden="true">&times;</span>
				</button>
			</div>
			
			<div class="modal-body">
				<form method="POST" action="update.php" v-on:submit.prevent="doUpdate" id="form-edit-user" v-if="user != null">
					<input type="hidden" name="id" v-bind:value="user.id" />

					<div class="form-group">
						<label>Name</label>
						<input type="text" name="name" v-bind:value="user.name" class="form-control" />
					</div>

					<div class="form-group">
						<label>Email</label>
						<input type="email" name="email" v-bind:value="user.email" class="form-control" />
					</div>
				</form>
			</div>

			<div class="modal-footer">
				<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
				<button type="submit" name="submit" class="btn btn-primary" form="form-edit-user">Save changes</button>
			</div>
		</div>
	</div>
</div>

When the edit form is submitted, it called a Javascript function to call an AJAX request to the server. So we need to create that method in our Vue JS instance methods object.

// update the user
doUpdate: function () {
	const self = this;
	const form = event.target;

	const ajax = new XMLHttpRequest();
	ajax.open("POST", form.getAttribute("action"), true);

	ajax.onreadystatechange = function () {
		if (this.readyState == 4) {
			if (this.status == 200) {

				const user = JSON.parse(this.responseText);

				// update in local array
				// get index from local array
				var index = -1;
				for (var a = 0; a < self.users.length; a++) {
					if (self.users[a].id == user.id) {
						index = a;
						break;
					}
				}

				// create temporary array
				const tempUsers = self.users;

				// update in local temporary array
				tempUsers[index] = user;

				// update the local array by removing all old elements and inserting the updated users
				self.users = [];
				self.users = tempUsers;
			}
		}
	};

	const formData = new FormData(form);
	ajax.send(formData);

	// hide the modal
	$("#editUserModal").modal("hide");
},

Now we need to create a new file called update.php that will handle this AJAX request and will update the data in database.

<?php

// connect database
$conn = new PDO("mysql:host=localhost:8889;dbname=test", "root", "root");

// update user name and email using his unique ID
$sql = "UPDATE users SET name = :name, email = :email WHERE id = :id";
$result = $conn->prepare($sql);

$result->execute([
	":name" => $_POST["name"],
	":email" => $_POST["email"],
	":id" => $_POST["id"],
]);

// get the updated record
$sql = "SELECT * FROM users WHERE id = :id";
$result = $conn->prepare($sql);
$result->execute(array(
    ":id" => $_POST["id"]
));
$data = $result->fetch();

// send the updated record back to AJAX
echo json_encode($data);

Refresh the page now, and you will see an “Edit” button with each row. On click, you will see a modal to update the data. Once submitted, the data will be updated in the database, the bootstrap modal will be closed and you will also see the data updated in the HTML table too.

Delete

To complete the CRUD operation in Vue JS and PHP. The final step is to create a “Delete” button. In front of each edit button, we need to create another button that will delete the user from the database and from the local array as well.

<form method="POST" action="delete.php" v-on:submit.prevent="doDelete" style="display: contents;">
	<input type="hidden" name="id" v-bind:value="user.id" />
	<input type="submit" name="submit" class="btn btn-danger" value="Delete" />
</form>

Then we need to create a method in Vue JS that will call an AJAX request to delete the user.

// delete user
doDelete: function () {
	const self = this;
	const form = event.target;

	const ajax = new XMLHttpRequest();
	ajax.open("POST", form.getAttribute("action"), true);

	ajax.onreadystatechange = function () {
		if (this.readyState == 4) {
			if (this.status == 200) {
				
				// remove from local array
				for (var a = 0; a < self.users.length; a++) {
					if (self.users[a].id == form.id.value) {
						self.users.splice(a, 1);
						break;
					}
				}
			}
		}
	};

	const formData = new FormData(form);
	ajax.send(formData);
},

Lastly, we need to create a file named delete.php that will handle this request and will actually delete the user from the database.

<?php

// connect database
$conn = new PDO("mysql:host=localhost:8889;dbname=test", "root", "root");

// delete the user from database
$sql = "DELETE FROM users WHERE id = :id";
$result = $conn->prepare($sql);
$result->execute(array(
    ":id" => $_POST["id"]
));

// send the response back to AJAX
echo "Done";

Refresh the page now and you will see a “Delete” button too with each row. On clicking, will delete that record from the database, and also it will delete the HTML table row as well.

Congratulations! You just completed your CRUD operation in Vue JS and PHP.

Download CRUD in Vue JS and PHP source code:

[wpdm_package id=’1511′]

Create a single page application in MEVN stack

Free tutorial

Prevent form submit event from reloading the page

In this article, we are going to discuss 2 options that how you can prevent your HTML form submit event from reloading the page. Normally, when you submit the form, it redirects to the action attribute link. But you can stop that reload and call an AJAX or any other Javascript function.

1. preventDefault

You can call the preventDefault function on the event target and it will stop the form from redirecting to the page specified in the action attribute of the <form> tag.

<form method="POST" action="your-page.php" onsubmit="onFormSubmit();">
	<input type="submit" />
</form>

Then you can create the following Javascript function to prevent the page reload:

function onFormSubmit() {
	event.preventDefault();

	// your Javascript code here
}

In this method, the form is first prevented from submission and then your Javascript code will be run. So it prevents the form submit event first, then it will run our Javascript code which is a good approach.

You can learn more about preventDefault from here.

2. return false

The second approach is to use the return false statement in your Javascript code. For this, you also need to return the value from the onsubmit event function. Let’s check this out.

<form method="POST" action="your-page.php" onsubmit="return onFormSubmit();">
	<input type="submit" />
</form>

Then create your Javascript function as like that:

function onFormSubmit() {
	// your Javascript code here
	
	return false;
}

In this method, your Javascript code runs first before preventing the form submission.

Recommendation

We would recommend the 1st method i.e. preventDefault because it is the very first line of the Javascript function. So if there is an error in your Javascript code, your browser will not get reloaded and thus you will be able to view the error in the browser console.

Now that you have learned to prevent the form submit event. You can also display a pop-up for confirmation in case of the delete function. You can follow this tutorial to display a pop-up confirmation before submitting the form.

Display Message in Console – Javascript, Figlet

In this article, we are going to show you how you can display a beautiful message in a browser console using Javascript. You just need to download a library called Figlet.

After download, you need to extract the zip file and copy the file lib/figlet.js in your project. You also need to copy the fonts folder too.

Then you need to include that library in your project using the script tag:

<script src="figlet.js"></script>

Right after that, you can display the message you want in the browser console:

<script>
	// initialize the library

	const textDisplay = "adnan-tech.com";
	const font = "Speed";

	figlet(textDisplay, font, function (error, text) {
		// display the text in console
		console.log(text);
	});
</script>

For more Javascript tutorials, please visit here.

Change title text – PHP, MySQL, Node JS

In this article, we are going to show you, how you can change title text of an HTML page using simple Javascript. We will show a real-time notification to your users in their title bar using PHP, MySQL, and Node JS. You can show a notification in a title bar with just PHP and MySQL. But the “real-time” effect can only be achieved with Node JS.

We can change title text using Javascript’s document.title object, but we will show you with a real-world example.

What we will do:

  1. Save notification in the database
  2. Display counter in the title bar
  3. Show all unread notifications to the user
  4. Mark notification as read
  5. Make notifications real-time

1. Save notifications in the MySQL database

First, we need to save the notifications in the database. Notifications can be of any type, for example, “a new message is received” or “your account has been activated” etc. We will create a new file named “send-notification.php“.

<?php

	// connect with database
	$conn = new PDO("mysql:host=localhost;dbname=test", "root", "");

	// create table if not exists
	$sql = "CREATE TABLE IF NOT EXISTS notifications (
		id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
		user_id INTEGER,
		message TEXT,
		is_read BOOLEAN,
		created_at DATETIME
	)";

	// prepare the query
	$statement = $conn->prepare($sql);
	
	// execute the statement
	$statement->execute();

	// user who needs to receive the notification
	$user_id = 565; // replace this your user ID
	$message = "You have received a new message " . time() . ".";
	$is_read = 0;

	// insert in notifications table
	$sql = "INSERT INTO notifications (user_id, message, is_read, created_at) VALUES (?, ?, ?, NOW())";
	$statement = $conn->prepare($sql);
	$statement->execute([
		$user_id, $message, $is_read
	]);

Comments have been added with each line for an explanation. Run the above code and check your database, you will see a new table named “notifications” and also a new row is inserted in that table. Now we need to display this on the user side.

2. Display the counter in the title bar

We just need to fetch the total number of unread notifications from the database and display them in the user’s title bar. Create a new file named “index.php” and it will have the following code:

<?php

	// start session and login the user
	session_start();

	// you might be saving the session during login,
	// I am hard-coding the value for testing purpose
	$_SESSION["user_id"] = 565;

	// connect with database
	$conn = new PDO("mysql:host=localhost;dbname=test", "root", "");

	// get number of unread notifications
	$sql = "SELECT COUNT(*) AS total_unread_notifications FROM notifications WHERE user_id = ? AND is_read = 0";
	$statement = $conn->prepare($sql);
	$statement->execute([
		$_SESSION["user_id"]
	]);
	$row = $statement->fetch();
	$total_unread_notifications = $row["total_unread_notifications"];

Then we need to fetch this variable in Javascript and prepend it in the title bar. First, we need to create a title tag and a hidden input field where we will put the above variable value.

<!-- title where notification number will be displayed -->
<title>My Website</title>

<!-- save variables in hidden input field to access in Javascript -->
<input type="hidden" id="total-unread-notifications" value="<?php echo $total_unread_notifications; ?>" />

Then we need to get this input field value in Javascript and render it in the title tag. We will create a separate Javascript function to render the title bar because we will need it in multiple situations when:

  1. The page is loaded
  2. There is a new notification (increment)
  3. A notification is read by the user (decrement)
<script>

	// get variables in Javascript
	var totalUnreadNotifications = document.getElementById("total-unread-notifications").value;
	totalUnreadNotifications = parseInt(totalUnreadNotifications);

	// show count in title bar
	showTitleBarNotifications();

	function showTitleBarNotifications() {
		// pattern to check if there is any counter number at the start of title bar
    	var pattern = /^\(\d+\)/;

    	if (totalUnreadNotifications == 0) {
    		document.title = document.title.replace(pattern, "");
			return;
		}

		if (pattern.test(document.title)) {

			// update the counter
			document.title = document.title.replace(pattern, "(" + totalUnreadNotifications + ")");
		} else {

			// prepend the counter
			document.title = "(" + totalUnreadNotifications + ") " + document.title;
		}
	}
</script>

This will first check if the value of variable totalUnreadNotifications is greater than 0. If it is 0, then we will not show any number at all (not even 0). Then we will check if there is already any value in the title bar. If there is any value, then we will simply increment the counter value and re-render the title bar.

If there isn’t any value already in the title bar, then we will simply prepend the counter before the title tag content.

Here, the document.title is the only line that change title text.

This does change title text because initially, it was only “My Website”. After a notification is fetched from database, it prepends the value in the <title> tag.

At this point, you are seeing the number of unread notifications in your title bar. Now you need to find a way to mark notifications as “read” and decrement the counter.

3. Show all unread notifications to the user

To mark notifications as “read”, we first must show all the notifications to the user which when clicked will be marked as “read”. After that, the counter will be decremented and the title tag will be re-rendered. We will create a new file named “notifications.php” to display all notifications to the user.

<?php

	// start session
	session_start();

	// connect with database
	$conn = new PDO("mysql:host=localhost;dbname=test", "root", "");

	// get all notifications sorting by unread goes first
	$sql = "SELECT * FROM notifications WHERE user_id = ? ORDER BY is_read ASC";
	$statement = $conn->prepare($sql);
	$statement->execute([
		$_SESSION["user_id"]
	]);
	$notifications = $statement->fetchAll();

This will fetch all the notifications of the logged-in user. Now we need to display them in an HTML table. We will simply by displaying a notification message and a button to mark that notification as read.

<!-- show all notifications in a table -->
<table>
	<tr>
		<th>Message</th>
		<th>Action</th>
	</tr>

	<?php foreach ($notifications as $notification): ?>
		<tr>
			<td><?php echo $notification['message']; ?></td>
			<td>
				<!-- show 'read' button only if the notification is un-read -->
				<?php if (!$notification['is_read']): ?>
					<form onsubmit="return markAsRead();">
						<input type="hidden" name="id" value="<?php echo $notification['id']; ?>" />
						<input type="hidden" name="user_id" value="<?php echo $notification['user_id']; ?>" />
						<input type="submit" value="Read" />
					</form>
				<?php endif; ?>
			</td>
		</tr>
	<?php endforeach; ?>
</table>

If you refresh the page now, you will see a list of all notifications with the button “read”. On clicking that button, we need to call an AJAX request to the server to mark this notification as “read” in the MySQL database. We will be using Vanilla JS to do that, no jQuery or any other external library is being used.

Now we need to create this Javascript function that will actually send the AJAX request. We will be using AJAX because there will be a lot of notifications and it will not be a good idea to keep refreshing the page for each notification to be marked as read.

<script>
	// when the read button is clicked
	function markAsRead() {
		// prevent the form from submitting
		event.preventDefault();

		// get the form node
		var form = event.target;

		// create AJAX object
		var ajax = new XMLHttpRequest();

		// set method and URL of request
		ajax.open("POST", "read-notification.php", true);

		// when the status of request changes
		ajax.onreadystatechange = function () {

			// when the response is received from server
			if (this.readyState == 4) {

				// if the response is successful
				if (this.status == 200) {

					// convert the JSON string into Javascript object
					var data = JSON.parse(this.responseText);
					console.log(data);

					// if there is no error
					if (data.status == "success") {

						// remove the 'read' button
						form.remove();

						// [emit read notification event here]
					}
				}
			}
		};

		// create form data object with the form
		var formData = new FormData(form);

		// send the AJAX request with the form data
		ajax.send(formData);
	}
</script>

This will prevent the form from redirecting and calling our Javascript code. After the notification is successfully marked as read from the server, we will remove the “read” button. The last thing we need is a server-side PHP file that will handle this request.

4. Mark notification as read

Now we need to create a new file named “read-notification.php” that will mark this notification as “read”. In this file, we will also check the user_id along with the notification ID to make sure that the notification we are marking is “read” is actually sent to the logged-in user.

<?php

	// start the session
	session_start();

	// connect with database
	$conn = new PDO("mysql:host=localhost;dbname=test", "root", "");

	// get ID from AJAX
	$id = $_POST["id"];

	// mark notification as read
	$sql = "UPDATE notifications SET is_read = 1 WHERE id = ? AND user_id = ?";
	$statement = $conn->prepare($sql);
	$statement->execute([
		$id,
		$_SESSION["user_id"]
	]);

	// send the response back to client
	echo json_encode([
		"status" => "success"
	]);
	exit();

This file will first check that the notification ID sent from AJAX actually refers to the logged-in user. Because someone can try to tamper with the client-side code and mark any other user’s notification as “read”. So we must do server-side validation like above.

At this point, if you run the code now, you will be able to see all the notifications in an HTML table with a “Read” button. When clicked, will mark the notification as read and also will remove the “read” button.

If you refresh the “index.php” file, you will now see the counter in the title bar will be decremented. One more thing you can do is to make it real-time, so when there is any notification added, the counter will be incremented in the title bar. And also when the notification is read by the user, then the counter should be decremented automatically.

5. Make notifications real-time

Making these notifications in real-time is crucial. You might have used the WhatsApp Web where you will see that the counter in the title bar automatically gets incremented and decremented based on the number of new notifications you received and the notifications have you read.

Now we need to learn how you can implement this functionality in your project. We will be using the Socket IO JS library for this and we will also create a small Node JS server for this purpose. You can download Socket IO JS from their official site.

After downloading, you need to paste the JS file into your project. You also need to download and install Node JS in your system, you can download it from here.

Setting up Node JS server

After Node JS installation, open the command prompt or terminal in your project root directory and run the following command:

npm init

This will ask a couple of questions, you can press “enter” for all questions and it will automatically set the default answer. Then we need to install the required modules for this feature. Run the following command in your terminal:

npm install express http socket.io

This will install the Express, HTTP, and Socket IO module in your Node JS app. To start the server, we need to install another module globally named “nodemon“. So again, run the following command in your terminal:

npm install -g nodemon

Typically when you made changes in your code, you need to manually restart the Node JS server. But it slows down the process during development. So this module automatically restarts the server if there is any change in the server file.

Create a new file named “server.js“, this will be our Node JS server file. Paste the following code in that file, we will explain this in the next step:

// initialize express server
var express = require("express");
var app = express();

// create http server from express instance
var http = require("http").createServer(app);

// include socket IO
var socketIO = require("socket.io")(http, {
	cors: {
		origin: ["http://localhost"]
	}
});

// start the HTTP server at port 3000
http.listen(process.env.PORT || 3000, function () {
	console.log("Server started running...");

	// an array to save all connected users IDs
	var users = [];

	// called when the io() is called from client
	socketIO.on("connection", function (socket) {

		// called manually from client to connect the user with server
		socket.on("connected", function (id) {
			users[id] = socket.id;
		});
	});
});

In this file we are:

  1. Initializing the Express framework and also HTTP module.
  2. Including the Socket IO module. You can place your own server URL in the CORS origin array.
  3. Then we are starting the server at port 3000. We use process.env.PORT on deployment.
  4. When a new user is connected with a server, a unique socket ID is generated. We are saving each user’s socket ID in a local array along with his ID from the database.

Now is the time to start the server. Run the following command in your terminal to start the server.

nodemon server.js

If you check the terminal, you will see a message “Server started running…” this means that you are ready to send connect your client-side with this server.

Increment counter on new notification

Whenever a new notification is sent to the server, we need to automatically increment the counter in the title bar. We have already created a function in “index.php” that displays the counter in the title bar.

To add this feature we need to perform the following tasks:

  1. Connect socket IO JS on the “send-notification.php” file.
  2. Then emit (send) the notification event to the Node JS server along with the ID of the user.
  3. On the Node JS server-side, listen to that event and emit the event to the relative user.
  4. Connect socket IO JS on the “index.php” file.
  5. Listener for that new notification event.
  6. When that event is received, increment the counter and re-render the title.

The following code goes in the “send-notification.php” file after the notification is inserted in the database:

<!-- save user id -->
<input type="hidden" id="user-id" value="<?php echo $user_id; ?>" />

<!-- include socket IO JS -->
<script src="socket.io.js"></script>

<script>
	// connect with Node JS server
	var socketIO = io("http://localhost:3000");

	// get user ID
	var userId = document.getElementById("user-id").value;

	// send notification to the server
	socketIO.emit("newNotification", userId);
</script>

We are already creating the $user_id variable in the first step. Then we are simply including the socket IO JS library and connect with the Node JS server. Getting the user ID from the hidden input field. And finally emitting an event to the server with a user ID.

In your “server.js” listen to this event and emit the event to the user with the same ID.

// when a new notification is received
socket.on("newNotification", function (userId) {

	// send notification to the selected user
	socketIO.to(users[userId]).emit("newNotification", userId);
});

The event has been dispatched from the server to the client. Now the client must listen to this event and when received should increment the counter and re-render the title. The following code goes in your “index.php“:

<!-- include socket IO JS -->
<script src="socket.io.js"></script>

<script>
	// connect with Node JS server
	var socketIO = io("http://localhost:3000");

	// connect user with Node JS server
	var userId = document.getElementById("user-id").value;
	socketIO.emit("connected", userId);

	// when a new notification is received
	socketIO.on("newNotification", function (data) {
		totalUnreadNotifications++;
		showTitleBarNotifications();
	});
</script>

Open “index.php” and “send-notification.php” in separate tabs and refresh both of these pages. Every time you refresh the send notification page, you will see the title of the index file gets incremented. Now we need to do the same for reading notifications, except that the title bar will be decremented whenever a notification is marked as read.

Decrement counter on reading notification

In “notifications.php” first, we need to include the socket IO JS library and connect with the server.

<!-- include socket IO JS -->
<script src="socket.io.js"></script>

<script>
	// connect with Node JS server
	var socketIO = io("http://localhost:3000");
</script>

Following code goes in the [emit read notification event here] section:

// send notification to the server
socketIO.emit("notificationRead", form.user_id.value);

Now we need to create a listener for this in our “server.js” file.

socket.on("notificationRead", function (userId) {
	socketIO.to(users[userId]).emit("notificationRead", userId);
});

Similarly, you need to create a listener on the user side too in the index.php file.

socketIO.on("notificationRead", function (data) {
	totalUnreadNotifications--;
	showTitleBarNotifications();
});

This also change title text, but this time it decrements the counter value.

Run the code now and refresh both of your browsers. And try to read some notifications, as soon as you read them, you will see that the counter in the title bar will be decremented too.

So that’s how you can change title text of an HTML page using vanilla Javascript.

Conclusion

So that’s how you can implement a real-time notification system in your website with an unread notification counter in the title bar using simple PHP, Javascript, and Node JS. There is no PHP or Javascript framework used in this tutorial, so you can work with it with any framework in your existing project.

That’s how you can change the title text of the browser tab. If you face any problems in following this, kindly do let me know in the comments section below.

Download source code

[wpdm_package id=’1415′]

Dynamic testimonial – PHP & MySQL, Vue JS

In this tutorial, we are going to teach you how you can add a dynamic testimonial to your website using PHP and MySQL in the backend and Vue JS in the frontend. Testimonials are displayed on a website to show the new users how your product satisfies your previous customers. We will be creating 2 pages, one for adding testimonials from the admin panel. And second to display all testimonials in a beautiful design.

If you do not have a dynamic testimonial, then you have to manually add, modify or delete a testimonial from your website. By going dynamic, you can perform all these actions from your admin panel.

Add Testimonial

First, download Bootstrap from here and Vue JS from here. Paste the CSS and JS files in your project, we will be using them in a moment. After that, we need to create a form from which we can add testimonials. Each testimonial will have a picture of the person, name, designation in his company, and his comments.

The following code goes in your admin panel from where you want to add testimonials.

<!-- include bootstrap -->
<link rel="stylesheet" type="text/css" href="bootstrap.min.css" />
 
<!-- include vue js -->
<script src="vue.min.js"></script>

<!-- container for vue js app -->
<div class="container" style="margin-top: 50px; margin-bottom: 50px;" id="addTestimonialApp">
    <div class="row">
        <!-- center align form -->
        <div class="offset-md-3 col-md-6">
            <h2 style="margin-bottom: 30px;">Add Testimonial</h2>
 
 			<!-- form to add testimonial -->
            <form v-on:submit.prevent="store" enctype="multipart/form-data">

            	<!-- picture of user -->
                <div class="form-group">
                    <label>Picture</label>
                    <input type="file" name="picture" accept="image/*" class="form-control" />
                </div>

                <!-- name of user -->
                <div class="form-group">
                    <label>Name</label>
                    <input type="text" name="name" class="form-control" />
                </div>

                <!-- designation of user -->
                <div class="form-group">
                    <label>Designation</label>
                    <input type="text" name="designation" class="form-control" />
                </div>

                <!-- comment -->
                <div class="form-group">
                    <label>Comment</label>
                    <textarea name="comment" class="form-control"></textarea>
                </div>

                <!-- submit button -->
                <input type="submit" name="submit" class="btn btn-info" value="Add Testimonial" />
            </form>
        </div>
    </div>

    [show all testimonials for deleting]
</div>

This will show a form with input fields. But when you click on the “Add Testimonial” button, nothing happens. This is because we need to render it using Vue JS.

<script>
    // initialize vue js app
    var addTestimonialApp = new Vue({
        el: "#addTestimonialApp", // id of container div
        data: {
            // all values used in this app
            testimonials: []
        },
        // all methods
        methods: {
            // [other methods goes here]

             // called when form is submitted
            store: function () {
                // get this app instance
                var self = this;
                var form = event.target;
             
                // call an AJAX to create a new entry in testimonials
                var ajax = new XMLHttpRequest();
                ajax.open("POST", "store.php", true);
             
                ajax.onreadystatechange = function () {
                    if (this.readyState == 4) { // response received
                        if (this.status == 200) { // response is successfull
                            // console.log(this.responseText);
             
                            // parse the response from JSON string to JS arrays and objects
                            var response = JSON.parse(this.responseText);
                            // console.log(response);

                            alert(response.message);
             
                            // if there is no error
                            if (response.status == "success") {
                                self.testimonials.unshift(response.testimonial);
                                form.reset();
                            } else {
                                // when there is any error
                            }
                        }
             
                        if (this.status == 500) {
                            console.log(this.responseText);
                        }
                    }
                };
             
                // create form data object and form to it
                var formData = new FormData(form);
             
                // actually sending the request
                ajax.send(formData);
            },
        },

        // [mount code goes here]
    });
</script>

Refresh the page now and you will be able to submit the form, this is because of Vue JS. An AJAX request will be sent to the server to store the picture attached and save the other fields in the MySQL database using PHP.

Create a new file named “store.php” and paste the following code in it:

<?php
 
// connect with database
$conn = new PDO("mysql:host=localhost;dbname=test", "root", "");

// create tables if not exists
$sql = "CREATE TABLE IF NOT EXISTS testimonials (
    id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
    picture TEXT NULL,
    name VARCHAR(255) NULL,
    designation VARCHAR(255) NULL,
    comment TEXT NOT NULL,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)";
$result = $conn->prepare($sql);
$result->execute();

$file_path = "";
if ($_FILES["picture"]["error"] == 0)
{
    $folder_name = "testimonials";
    mkdir($folder_name);
    $file_path = $folder_name . "/" . $_FILES["picture"]["name"];
    move_uploaded_file($_FILES["picture"]["tmp_name"], $file_path);
}

// insert in testimonials table
$sql = "INSERT INTO testimonials (picture, name, designation, comment, created_at) VALUES (?, ?, ?, ?, NOW())";
$result = $conn->prepare($sql);
$result->execute([
    $file_path,
    $_POST["name"],
    $_POST["designation"],
    $_POST["comment"],
]);
$testimonial_id = $conn->lastInsertId();

// get the testimonial just inserted in database
$sql = "SELECT * FROM testimonials WHERE id = ?";
$result = $conn->prepare($sql);
$result->execute([
    $testimonial_id
]);
$testimonial = $result->fetch();

echo json_encode([
    "status" => "success",
    "message" => "Testimonial has been added.",
    "testimonial" => $testimonial
]);
exit();

If you refresh the page now, upload the picture, enter the fields and hit submit, it will create a new table in the database if not already created. Then it will create a folder named “testimonials” and save the image file in it. Then it will insert a new row in it. And finally, it will return the new row back to the client (AJAX).

From there we will prepend it in our local testimonials array. Now we need to display all the added testimonials in an HTML table with a button to delete them.

Display all Testimonials to Admin

The following code goes in the [show all testimonials for deleting] section:

<!-- show all testimonials -->
<div class="row" style="margin-top: 50px;">
    <div class="col-md-12">
        <table class="table table-bordered">
            <!-- table heading -->
            <tr>
                <th>ID</th>
                <th>Picture</th>
                <th>Name</th>
                <th>Designation</th>
                <th>Comment</th>
                <th>Actions</th>
            </tr>
 
            <!-- loop through an array of testimonials -->
            <tr v-for="(testimonial, index) in testimonials">
                <td v-text="testimonial.id"></td>
                <td>
                    <img v-bind:src="testimonial.picture" style="width: 300px;" />
                </td>
                <td v-text="testimonial.name"></td>
                <td v-text="testimonial.designation"></td>
                <td v-text="testimonial.comment"></td>
                <td>
                    <!-- form to delete testimonial -->
                    <form v-on:submit.prevent="deleteTestimonial">
                        <input type="hidden" name="id" v-model="testimonial.id" required />
                        <input type="submit" class="btn btn-danger btn-sm" value="Delete" />
                    </form>
                </td>
            </tr>
        </table>
    </div>
</div>

This will create an empty HTML table because we need to load the in it first. We will call an AJAX to fetch all the stored testimonials using PHP and MySQL and display them using Vue JS. The following code goes in the [mount code goes here] section:

mounted: function () {
    this.getData();
}

Now we need to create a function named “getData” in our Vue JS instance. Replace the code in section [other methods goes here] with the following:

// [delete method]

getData: function () {
    // get this app instance
    var self = this;
 
    // call an AJAX to get all testimonials
    var ajax = new XMLHttpRequest();
    ajax.open("POST", "fetch.php", true);
 
    ajax.onreadystatechange = function () {
        if (this.readyState == 4) { // response received
            if (this.status == 200) { // response is successfull
                // console.log(this.responseText);
 
                // parse the response from JSON string to JS arrays and objects
                var response = JSON.parse(this.responseText);
                // console.log(response);
 
                // if there is no error
                if (response.status == "success") {
                    self.testimonials = response.data;
                } else {
                    // when there is any error
                }
            }
 
            if (this.status == 500) {
                console.log(this.responseText);
            }
        }
    };
 
    // create form data object
    var formData = new FormData();
 
    // actually sending the request
    ajax.send(formData);
},

Finally, we need to create a new file named “fetch.php” that will fetch all the testimonials from the MySQL database using PHP.

<?php

// connect with database
$conn = new PDO("mysql:host=localhost;dbname=test", "root", "");

// fetch all testimonials
$sql = "SELECT * FROM testimonials ORDER BY id DESC";
$statement = $conn->prepare($sql);
$statement->execute();
$data = $statement->fetchAll();

// create new field for full comment text
// because we will be displaying less text and display 'show more' button
for ($a = 0; $a < count($data); $a++)
{
	$data[$a]["comment_full"] = $data[$a]["comment"];
	$data[$a]["comment"] = substr($data[$a]["comment"], 0, 50);
}

// send the response back to client
echo json_encode([
    "status" => "success",
    "message" => "Testimonial has been fetched.",
    "data" => $data
]);
exit();

?>

Refresh the page now and you will be able to see all the testimonials added. Also, if you add a new testimonial, it will automatically be prepended in the HTML table. Now we need to make it able to delete the testimonial.

Delete Testimonial

We need to follow the following steps to delete the testimonial:

  1. Call an AJAX with an ID of testimonial.
  2. On server side, fetch the testimonial using ID.
  3. Delete the picture from the “testimonials” folder using PHP unlink() function.
  4. Delete the testimonial from MySQL database.
  5. Send the response back to client.
  6. The client will remove the testimonial from local array.
  7. It will automatically be removed from the HTML table.

Replace the section [delete method] with the following code:

// method to delete testimonial
deleteTestimonial: function () {
    // get this app instance
    var self = this;
 
    // get form
    var form = event.target;
 
    // call an AJAX to delete the testimonial
    var ajax = new XMLHttpRequest();
    ajax.open("POST", "delete.php", true);
 
    ajax.onreadystatechange = function () {
        if (this.readyState == 4) { // response received
            if (this.status == 200) { // response is successfull
                // console.log(this.responseText);
 
                // parse the response from JSON string to JS arrays and objects
                var response = JSON.parse(this.responseText);
                console.log(response);
 
                // remove from local array if deleted from server
                if (response.status == "success") {
                    for (var a = 0; a < self.testimonials.length; a++) {
                        var testimonial = self.testimonials[a];
                        if (testimonial.id == form.id.value) {
                            self.testimonials.splice(a, 1);
                            break;
                        }
                    }
                } else {
                    // display an error message
                    alert(response.message);
                }
            }
 
            if (this.status == 500) {
                console.log(this.responseText);
            }
        }
    };
 
    // append form in form data object
    var formData = new FormData(form);
 
    // call AJAX with form data
    ajax.send(formData);
},

Then we need to create a new file named “delete.php” that will handle this request. It will have the following code:

<?php
 
// connect with database
$conn = new PDO("mysql:host=localhost;dbname=test", "root", "");

// get the testimonial just inserted in database
$sql = "SELECT * FROM testimonials WHERE id = ?";
$result = $conn->prepare($sql);
$result->execute([
    $_POST["id"]
]);
$testimonial = $result->fetch();

if (!$testimonial)
{
    // send the response back to client
    echo json_encode([
        "status" => "error",
        "message" => "Testimonial not found."
    ]);
    exit();
}

// remove the picture from folder
unlink($testimonial["picture"]);

// create a query to delete the pricing table from database
$sql = "DELETE FROM testimonials WHERE id = ?";
 
// prepare the query
$result = $conn->prepare($sql);
 
// execute the query
$result->execute([
    $_POST["id"]
]);
 
// send the response back to client
echo json_encode([
    "status" => "success",
    "message" => "Testimonial has been deleted."
]);
exit();

Refresh the page now and you will be able to delete the testimonials as well. The only thing left is to show the testimonials on the user side.

Display Testimonials on User Side

To display testimonials on the user side, you need to download font-awesome and slick, you already have the Bootstrap and Vue JS files in your project folder. You can download font-awesome from here and slick from here. After downloading, paste both folders into your project, we will include them on your user side.

The following code will display the layout for each testimonial using HTML. Which we will render using Vue JS in the next step.

<!-- include bootstrap CSS -->
<link rel="stylesheet" type="text/css" href="bootstrap.min.css" />

<!-- include font awesome -->
<link rel="stylesheet" type="text/css" href="font-awesome/css/font-awesome.min.css" />

<!-- include slick -->
<link rel="stylesheet" type="text/css" href="slick.css" />
<link rel="stylesheet" type="text/css" href="slick-theme.css" />

<!-- include vue js -->
<script src="vue.min.js"></script>

<div class="container" id="testimonialApp" style="margin-top: 30px;">
	<div class="row">
		<div class="col-md-12">
			<h2 class="text-center">Testimonials</h2>
		</div>
	</div>

	<div class="row">
		<div class="col-md-12">
			<div class="items">

				<div class="card" v-for="(testimonial, index) in testimonials">
			        <div class="card-body">
			            <h4 class="card-title">
			            	<img src="https://img.icons8.com/ultraviolet/40/000000/quote-left.png" />
			            </h4>
			            
			            <div class="template-demo">
			                <p>
			                	<span v-text="testimonial.comment"></span>

			                	<span class="show-more-text" v-on:click="loadMoreContent" v-bind:data-index="index">show more</span>
			                </p>
			            </div>

			            <h4 class="card-title">
			            	<img src="https://img.icons8.com/ultraviolet/40/000000/quote-right.png" style="margin-left: auto;" />
			            </h4>
			            
			            <hr />
			            
			            <div class="row">
			                <div class="col-sm-3">
			                	<img class="profile-pic" v-bind:src="testimonial.picture" />
			                </div>
			                
			                <div class="col-sm-9">
			                    <div class="profile">
			                        <h4 class="cust-name" v-text="testimonial.name"></h4>
			                        <p class="cust-profession" v-text="testimonial.designation"></p>
			                    </div>
			                </div>
			            </div>
			        </div>
			    </div>
			    
			</div>
		</div>
	</div>
</div>

<!-- include jquery -->
<script src="jquery-3.3.1.min.js"></script>

<script src="slick.min.js"></script>

<!-- include bootstrap JS -->
<script src="bootstrap.min.js"></script>

<!-- your JS code -->
<script src="script.js?v=<?php echo time(); ?>"></script>

Create a new file named “script.js” and paste the following code in it:

var mainURL = window.location.origin + "/" + window.location.pathname + "/";

var testimonialApp = new Vue({
    el: "#testimonialApp",
    data: {
        testimonials: []
    },
    methods: {
        loadMoreContent: function () {
            var node = event.target;
            var index = node.getAttribute("data-index");

            if (this.testimonials[index].comment.length > 50) {
                // it needs to display less
                node.innerHTML = "show more";
                this.testimonials[index].comment = this.testimonials[index].comment_full.substr(0, 50);
            } else {
                // it needs to display more
                node.innerHTML = "show less";
                this.testimonials[index].comment = this.testimonials[index].comment_full;
            }
        },

        getData: function () {
            // get this app instance
            var self = this;
         
            // call an AJAX to get all testimonials
            var ajax = new XMLHttpRequest();
            ajax.open("POST", "fetch.php", true);
         
            ajax.onreadystatechange = function () {
                if (this.readyState == 4) { // response received
                    if (this.status == 200) { // response is successfull
                        // console.log(this.responseText);
         
                        // parse the response from JSON string to JS arrays and objects
                        var response = JSON.parse(this.responseText);
                        // console.log(response);
         
                        // if there is no error
                        if (response.status == "success") {
                            self.testimonials = response.data;

                            setTimeout(function () {
                                $('.items').slick({
                                    dots: true,
                                    infinite: true,
                                    speed: 800,
                                    autoplay: false,
                                    slidesToShow: 2,
                                    slidesToScroll: 2,
                                    responsive: [{
                                            breakpoint: 1024,
                                            settings: {
                                                slidesToShow: 3,
                                                slidesToScroll: 3,
                                                infinite: true,
                                                dots: true
                                            }
                                        }, {
                                            breakpoint: 600,
                                            settings: {
                                                slidesToShow: 2,
                                                slidesToScroll: 2
                                            }
                                        }, {
                                            breakpoint: 480,
                                            settings: {
                                                slidesToShow: 1,
                                                slidesToScroll: 1
                                            }
                                        }
                                    ]
                                });
                            }, 100);
                        } else {
                            // when there is any error
                        }
                    }
         
                    if (this.status == 500) {
                        console.log(this.responseText);
                    }
                }
            };
         
            // create form data object
            var formData = new FormData();
         
            // actually sending the request
            ajax.send(formData);
        }
    },
    mounted: function () {
        this.getData();
    }
});

At this point, you will be able to view the testimonials added from the admin panel on your website. It will also have a carousel slider. Finally, you can apply some CSS styles to make it look better for the users.

<style>
	.show-more-text {
		background-color: #72a4d5;
	    color: white;
	    padding: 3px 5px;
	    border-radius: 5px;
	    margin-left: 3px;
	    cursor: pointer;
	}
	.more {
		display: none;
	}

	@media (max-width:991.98px) {
		.padding {
			padding: 1.5rem
		}
	}

	@media (max-width:767.98px) {
		.padding {
			padding: 1rem
		}
	}

	.padding {
		padding: 5rem
	}

	.card {
		position: relative;
		display: flex;
		width: 350px;
		flex-direction: column;
		min-width: 0;
		word-wrap: break-word;
		background-color: #fff;
		background-clip: border-box;
		border: 1px solid #d2d2dc;
		border-radius: 11px;
		-webkit-box-shadow: 0px 0px 5px 0px rgb(249, 249, 250);
		-moz-box-shadow: 0px 0px 5px 0px rgba(212, 182, 212, 1);
		box-shadow: 0px 0px 5px 0px rgb(161, 163, 164)
	}

	.card .card-body {
		padding: 1rem 1rem
	}

	.card-body {
		flex: 1 1 auto;
		padding: 1.25rem
	}

	p {
		font-size: 0.875rem;
		margin-bottom: .5rem;
		line-height: 1.5rem
	}

	h4 {
		line-height: .2 !important
	}

	.profile {
		margin-top: 16px;
		margin-left: 11px
	}

	.profile-pic {
		width: 100px;
	}

	.cust-name {
		font-size: 18px
	}

	.cust-profession {
		font-size: 10px
	}

	.items {
		width: 90%;
		margin: 0px auto;
		margin-top: 30px
	}

	.slick-slide {
		margin: 10px;
		height: auto !important;
	}
</style>

So that’s it, you have a dynamic testimonial section fully manageable from the admin panel. If you face any problems in following this, kindly do let us know in the comments section below.

Also learn how to add dynamic pricing table in your website.

Download

[wpdm_package id=’1399′]

10 Javascript Libraries for Every Web Project

In this article, we are going to discuss 10 useful Javascript libraries that you need to use in almost every web project. We will discuss the following libraries along with their use:

  1. Sweetalert
  2. Datetime Picker by XD Soft
  3. Socket IO
  4. DataTable
  5. RichText
  6. PDFObject
  7. Vue JS
  8. Notify JS
  9. Chart JS
  10. TimeCircles

1. Sweetalert

Sweetalert is a JS library used to display alert messages. You can also use it for displaying confirm messages i.e. ask for the user’s confirmation before performing any action. To display a simple alert message:

swal("Message goes here");

To display an alert with a title:

swal("My Title", "Text goes here");

Success alert:

swal("Done", "Your message goes here", "success");

Error alert:

swal("Error", "Error message goes here", "error");

For confirmation dialog:

swal({
	title: "Confirm",
	text: "Are you sure, this data will be removed ?",
	icon: "warning",
	buttons: true,
	dangerMode: true,
})
.then((isOkay) => {
	if (isOkay) {
		//
	}
});

Learn more about how to use the confirmation dialog properly from here. You can also use it as a prompt:

swal("Enter your name:", {
    content: "input",
})
.then((value) => {
    if (value == "") {
        return false;
    }
    console.log(value);
});

You can read more about it from their official page.

2. Datetime Picker by XD Soft

It is a JS library that is used to display a calendar with a date and time picker. You can use it to get the user’s date of birth during registration. The basic usage is, you need to give your input field a unique ID:

<input type="text" id="datetimepicker" />

Then you can display the datetimepicker by calling the function:

jQuery("#datetimepicker").datetimepicker();

Make sure you have jQuery included in your project, this library requires jQuery. You can see this library in action from here. The complete documentation of this library is found on their official page.

3. Socket IO

Socket IO is used for real-time communication. If you are working on a feature that requires data from the server after regular intervals, there are 2 options to achieve this:

  1. Polling
  2. Sockets

Polling

This technique requires calling an AJAX request to the server every few seconds. This will overload the server with a lot of requests. There will be a lot of unnecessary requests to the server and if you have a lot of users, then your website might get crashed.

Sockets

The solution to the above problem is the sockets. Sockets attach a listener to the client-side and emit events from the server. The client is continuously listening to that event, whenever that event is received, the client will perform the action accordingly.

The difference between Polling and Sockets can be explained by this example:

For example, you are going on a trip with your family. Your Dad is driving the car and you are in the back seat. And you are continuously asking your Dad “did we reached the destination ?” every few minutes. This is Polling.

And in the other case, you ask your Dad “please inform me when we reach our destination”. Now you are silently listening to your Dad, who will send an event to you only when you reached your destination. This is Socket.

Learn how to use sockets with Node JS. Complete documentation can be found on their official page.

4. DataTable

This library is used to display data in tabular form. It has a built-in search feature, that allows you to search the entire table. You can search value from any row from any column. The search is case insensitive so you do not have to worry about capital or small letters.

It also has a sorting feature that allows you to sort the data based on any column. It also allows you to decide how many records you want to show on one page (e.g. 25, 50, 75, or 100). It has built-in pagination based on the number of records you are displaying on one page.

Its usage is rather simple. You just need to give your table tag a unique ID:

<table id="table"></table>

Then in your Javascript, simply initialize the library:

$("#table").DataTable();

It also requires jQuery to be included in your project. You can see this library in action from here. You can learn more about it from their official page.

5. RichText

This library applies to your textarea tag. It makes your text area as WYSIWYG (What You See Is What You Get). It enhances the Textarea field and gives it more options like:

  1. Text formatiing (font size, bold, italic, underline, color).
  2. Text alignment (left, center, right, justify).
  3. Headings & paragraphs.
  4. Upload images.
  5. Attach URLs.
  6. Adding tables.
  7. Or you can even add HTML tags too.

Its usage is almost the same as the DataTable library. You need to give your textarea a unique ID:

<textarea id="content" name="content"></textarea>

And in your Javascript, you need to initialize it like this:

$("#content").richText();

This library also requires jQuery to be included. Full documentation of this library can be found here.

6. PDFObject

When working with PDF files, if you want to show PDF files from your website, you have 3 options:

  1. Make the PDF file downloadable, so user can view it offline too.
  2. Display the PDF in a new window or tab.
  3. Embed the PDF in your website specific section.

This library fulfills the 3rd approach. It embeds the PDF file in your website using a div tag. Place a div tag anywhere in your code where you want to show the PDF file:

<div id="pdf"></div>

Then in your Javascript, initialize the library with a URL of the PDf file:

PDFObject.embed("my-file.pdf", "#pdf");

More information can be found on pdfobject.com.

7. Vue JS

Vue JS is more a framework than a library. But since it can be integrated with any project whether it is in core PHP, Laravel, WordPress, or Node JS, it can be called a library. You can learn all functions of it from their official guide. You can check our following projects developed in Vue JS:

  1. Picture Competition Web App – Vue JS, Node JS, Mongo DB
  2. Firebase Storage – Vue JS
  3. Financial Ledger Web App – Vue JS, Node JS, Mongo DB

You will learn a lot about Vue JS from the above projects.

8. Notify JS

This lightweight library is used to display notification pop-ups on the corners of the browser window. This library also requires jQuery to be included before using it. Its usage is extremely easy, you simply need to call the following function when you want to show the notification:

$.notify("New message");

By default, it displays a pop-up on the top right, but you can decide the position of it. You can learn more about this library from here.

9. Chart JS

As the name suggests, this library is used to draw charts and graphs on your website. You can show statistics to the users using this library. It uses canvas to render charts. The following code will create a simple bar chart:

<canvas id="myChart" width="400" height="400"></canvas>
<script>
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3],
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)',
                'rgba(153, 102, 255, 0.2)',
                'rgba(255, 159, 64, 0.2)'
            ],
            borderColor: [
                'rgba(255, 99, 132, 1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)'
            ],
            borderWidth: 1
        }]
    },
    options: {
        scales: {
            y: {
                beginAtZero: true
            }
        }
    }
});
</script>

There are many graphs & charts provided by this library. You can learn the implementation of all chars from their official page.

10. TimeCircles

This is used to create a countdown timer. You can set the date and the timer will start counting down till that time. This also requires jQuery on your website. Its usage is simple, you just need to give a data-date attribute to the div tag where you want to show the countdown timer. data-date attribute’s value will be the date and time when the timer hits zero. Give it a unique ID so it can be accessible in Javascript.

<div data-date="2021-10-12 23:02:55" id="count-down"></div>

Then in your Javascript, initialize the countdown timer with the following function:

$("#count-down").TimeCircles();

Learn How to Create a Dynamic Countdown Timer. Download the library from here.

What’s Next

You should learn all the libraries above and create small programs in them. But then you need to create a web application where you should apply all the above libraries together. We are going to give you a simple task that helps you learn how to combine all libraries together to create great web applications.

Assignment

Create a simple website that inputs date using DateTimePicker, description using RichText, an input field to upload PDF files and a submit button. When the submit button is pressed, it should show a message using Sweetalert that the message has been sent. It should send an event to the server using Socket IO and the other user should receive that event and display the description in a table using DataTable.

Another user should also see a notification using NotifyJS that a new event has been received. You need to show a countdown timer using TimeCircles till the date field value ends. You should also display the uploaded PDF file in a div tag using the PDFObject library.

Complete assignment’s frontend should be done in Vue JS. If you face any problem in doing this assignment, kindly do let us know in the comments section below.