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.
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 Number
4242 4242 4242 4242
CVV
422
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:
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.
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:
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.
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.
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:
id (auto increment)
name
email
password
Then you need to create a form from which you can enter the details to save in the database.
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:
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.
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.
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.
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.
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.
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.
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.
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>
In this tutorial, we are going to create a simple WordPress plugin that allows you to signin with google to your website. Here is the demo of what we are going to create.
Demo
Table of content
Creating and Activating the Plugin.
Displaying Google One-tap Sign In Popup.
Calling an AJAX in WordPress.
Show Popup to Non-authenticated Users Only.
Replace User Gravatar with Your Image.
Let’s get started
So let’s start allowing your users to signin with google on your WordPress website.
First, go to your wp-content content at the root of your WordPress website. And inside this, go to the plugins folder. Then create a new folder named signin-with-google. This will be our plugin folder, you are free to name it as you like.
Inside this newly created folder, create a new file named signin-with-google.php. This will be our main file. By setting the same name as the folder name, WordPress will automatically pick it up as the main file. Write the following code in this file to view it on the “Plugins” page in the admin panel.
<?php
/**
* Plugin Name: Sign in With Google
* Description: This plugin is for one-tap google sign in.
* Version: 1.0
* Author: adnan-tech.com
**/
Go to your “Plugins” page in your WordPress admin dashboard and you will see your plugin as “Sign in With Google”. You can find the direct link to the plugins folder from the following URL:
https://{your_domain}/wp-admin/plugins.php
You need to “Activate” your plugin in order to make it work.
Displaying google one-tap sign-in popup
To display the Google one-tap Sign-in popup on each page, you first need to generate a Google OAuth client ID. You can generate it from here. Or you can follow our tutorial that will help you set this up.
After the client ID is generated, write the following code in your plugin’s main file:
function SIWG_init()
{
// [user authentication is checked here]
// [JS scripts will be included here]
echo '<script src="https://accounts.google.com/gsi/client" async defer></script>
<div id="g_id_onload"
data-client_id="{your_google_client_id}"
data-context="signin"
data-callback="SIWG_googleLoginEndpoint"
data-close_on_tap_outside="false">
</div>';
}
add_action('wp_footer', 'SIWG_init');
Make sure to write your own Google Client ID in place of {your_google_client_id} code. Refresh your frontend side and open your browser console window. You will see an error that you need to create a Javascript function. So we will create a Javascript function that will be called when the user clicks the “Sign in” button on the popup.
So write the following code in the [JS scripts will be included here] section:
Then create the file named SIWG-script.js at the root of your plugin folder. We are appending “?v=1” at the end of the path of the file, it is to prevent the browser from caching this file. If you are making changes in your Javascript code and your changes are not being reflected when you refresh the page, simply increment the “?v=1” counter and it will work fine.
Following will be the code of SIWG-script.js file:
function SIWG_googleLoginEndpoint(googleUser) {
console.log(googleUser);
// [ajax code goes here]
}
Now refresh the page and this time there will be no error. Click the “Sign in” button in the popup and you will see the credential object in the browser console. On the client-side, Google only returns this credential also known as ID Token. We will send this ID Token to the server to verify the user.
Calling an AJAX in WordPress
To send an AJAX in WordPress, we need to include a built-in WordPress library called wp-util. So write the following code in the [include WP util] section:
// Manually enqueue the wp-util library.
wp_enqueue_script( 'wp-util' );
After that, we need to call an AJAX from Javascript. So replace the [ajax code goes here] section with the following code:
Now we need to create an API in our plugin’s main PHP file that will handle this request.
// a function that will handle the AJAX request
function SIWG_google_login()
{
// secure credential value from AJAX
$credential = sanitize_text_field($_POST["credential"]);
// verify the ID token
$curl = curl_init( 'https://oauth2.googleapis.com/tokeninfo?id_token=' . $credential );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
$response = curl_exec( $curl );
curl_close( $curl );
// convert the response from JSON string to object
$response = json_decode($response);
// if there is any error, send the error back to client
if (isset($response->error))
{
wp_send_json_error($response->error_description);
}
else
{
// check if user already exists in WordPress users
$user_id = username_exists( $response->email );
if ( ! $user_id && !email_exists( $response->email ) )
{
// user does not exists
// generate a random hashed password
$random_password = wp_generate_password( $length = 12, $include_standard_special_chars = false );
// insert the user as WordPress user
$user_id = wp_insert_user([
"user_email" => $response->email,
"user_pass" => $random_password,
"user_login" => $response->email,
"display_name" => $response->name,
"nickname" => $response->name,
"first_name" => $response->given_name,
"last_name" => $response->family_name
]);
}
// do login
$user = get_user_by('login', $response->email );
if ( !is_wp_error( $user ) )
{
wp_clear_auth_cookie();
wp_set_current_user ( $user->ID );
wp_set_auth_cookie ( $user->ID );
// set user profile picture
update_user_meta($user->ID, "SIWG_profile_picture", $response->picture);
}
// send the success response back
wp_send_json_success( $response );
}
}
add_action( 'wp_ajax_nopriv_SIWG-google-login', 'SIWG_google_login' );
Comments have been added with each line for an explanation. Refresh the page now and when the popup is displayed, click on the “Sign in” button. Your browser page will refresh automatically after a few seconds. And you will see that the user is now logged-in.
You can also see the user in the admin panel dashboard.
Show popup to non-authenticated users only
Users who are already logged in to your site should not be seeing the popup as they are already logged in. So we need to show this popup only for users who are not logged in. So write the following code in the [user authentication is checked here] section:
if (is_user_logged_in())
{
return false;
}
It will simply stop the function from executing if the user is already logged in.
Replace user gravatar with your image
We are saving the user profile picture URL from google in our user metadata using the key “SIWG_profile_picture“. Now we need to display it. To do that, we need to add a filter that will update the WordPress Gravatar image with the URL saved in the database. Add the following code in your plugin’s main PHP file.
function SIWG_override_avatar( $avatar, $id_or_email, $size, $default, $alt )
{
//If is email, try and find user ID
if( ! is_numeric( $id_or_email ) && is_email( $id_or_email ) )
{
$user = get_user_by( 'email', $id_or_email );
if( $user )
{
$id_or_email = $user->ID;
}
}
//if not user ID, return
if( ! is_numeric( $id_or_email ) )
{
return $avatar;
}
//Find URL of saved avatar in user meta
$saved = get_user_meta( $id_or_email, 'SIWG_profile_picture', true );
//check if it is a URL
if( filter_var( $saved, FILTER_VALIDATE_URL ) )
{
//return saved image
return '<img src="' . esc_url( $saved ) . '" alt="' . esc_attr( $alt ) . '" />';
}
//return normal
return $avatar;
}
add_filter( 'get_avatar', 'SIWG_override_avatar', 10, 5 );
By adding the above code, if the user is logged-in and is registered by Google, then his profile picture will be displayed as in his google account. Otherwise, it will be displayed by WordPress gravatar.
So that’s how you can enable your site’s visitors to signin with google on your wordpress website. This will definitely increase the number of daily registrations. Because it is a quicker way for the users to join.
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:
Save notification in the database
Display counter in the title bar
Show all unread notifications to the user
Mark notification as read
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:
The page is loaded
There is a new notification (increment)
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:
Initializing the Express framework and also HTTP module.
Including the Socket IO module. You can place your own server URL in the CORS origin array.
Then we are starting the server at port 3000. We use process.env.PORT on deployment.
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:
Connect socket IO JS on the “send-notification.php” file.
Then emit (send) the notification event to the Node JS server along with the ID of the user.
On the Node JS server-side, listen to that event and emit the event to the relative user.
Connect socket IO JS on the “index.php” file.
Listener for that new notification event.
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.
In this article, we are going to show you how you can implement a Google sign in on your website using Javascript and PHP. We will use Javascript to render the button. And we will use PHP to verify the token generated by the Google client because anyone can try to tamper with the client-side code.
Follow this tutorial to create an OAuth Client ID on the Google developer console.
2. Install Google OAuth Library
You can install the Google OAuth library by running the following command at the root of your project:
composer require google/apiclient
3. Render Google sign in button
Then we need to create a container where we will display the sign-in button at the appropriate place on your website.
<!-- include bootstrap -->
<link rel="stylesheet" type="text/css" href="css/bootstrap.css" />
<!-- google signin button -->
<div class="container" style="margin-top: 50px;">
<div class="row">
<div class="col-md-12">
<div id="myGoogleButton" onclick="googleSigninClick();"></div>
</div>
</div>
</div>
<!-- initialize google API -->
<script src="https://apis.google.com/js/platform.js?onload=googleInit" async defer></script>
Then we need to render the <div> tag with the sign in button. Make sure to replace the {your_google_client_id} code with your Google client ID generated from 1st step.
<script>
// variable to check that the button must be clicked manually
var googleSigninClicked = false;
// when the button is clicked by user
function googleSigninClick() {
googleSigninClicked = true;
}
// called when the google API is initialized
function googleInit() {
// load the auth API
gapi.load('auth2', () => {
// initialize the auth library
gapi.auth2.init({ client_id: "{your_google_client_id}" }).then(() => {
// render the google sign in button
gapi.signin2.render('myGoogleButton', {
'scope': 'profile email',
'width': 240,
'height': 40,
'longtitle': true,
'theme': 'dark',
onsuccess: (googleUser) => {
// this function is called when the page is loaded too,
// so we must login the user when the button is manually clicked
if (!googleSigninClicked) {
return false;
}
googleSigninClicked = false;
// get user profile
console.log(googleUser);
var profile = googleUser.getBasicProfile();
console.log({
"id": profile.getId(),
"name": profile.getName(),
"picture": profile.getImageUrl(),
"email": profile.getEmail()
});
// get token to be verified from server
var id_token = googleUser.getAuthResponse().id_token;
// send an AJAX request to the server to verify the token
var ajax = new XMLHttpRequest();
ajax.open("POST", "google-sign-in.php", true);
// when the status of request is changed
ajax.onreadystatechange = function () {
// when the response is received from server
if (this.readyState == 4) {
// if the server is successfull
if (this.status == 200) {
// the response will be a JSON string, convert that into javascript object
var data = JSON.parse(this.responseText);
console.log(data);
}
// if there is any internal server error
if (this.status == 500) {
console.log(this.responseText);
}
}
};
// create form data object
var formData = new FormData();
// append the token in the request
formData.append("id_token", id_token);
// send the request
ajax.send(formData);
},
onfailure: (error) => {
console.log(error);
}
});
});
});
}
</script>
Refresh the page now and you will be able to see a Google sign-in button. By default, you will see the message “Sign-in with Google”. Once you click the button and sign in with your Google account, you will see your profile information in the browser console.
4. Verify token
The token generated from the sign-in button must be verified from the server-side because anyone can tamper with the client-side code. To verify this token we are already sending an AJAX request. Now we need to create a new file named “google-sign-in.php” and paste the following code into it.
Make sure to replace the value of $google_oauth_client_id variable with your own client ID.
<?php
// include google API client
require_once "vendor/autoload.php";
// set google client ID
$google_oauth_client_id = "";
// create google client object with client ID
$client = new Google_Client([
'client_id' => $google_oauth_client_id
]);
// verify the token sent from AJAX
$id_token = $_POST["id_token"];
$payload = $client->verifyIdToken($id_token);
if ($payload && $payload['aud'] == $google_oauth_client_id)
{
// get user information from Google
$user_google_id = $payload['sub'];
$name = $payload["name"];
$email = $payload["email"];
$picture = $payload["picture"];
// send the response back to client side
echo json_encode([
"status" => "success"
]);
}
else
{
// token is not verified or expired
echo json_encode([
"status" => "error"
]);
}
Refresh the page now and try to log in again. Now we will also see a success response in your browser console, that is because of an AJAX request. On the server side, you can register the user if he is not already registered or you can start his session if he is already registered.
So that’s how you can implement a Google sign-in button in your website using plain Javascript and PHP. Try to implement this in your live site and let us know in the comments section if there is any problem.
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:
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:
Call an AJAX with an ID of testimonial.
On server side, fetch the testimonial using ID.
Delete the picture from the “testimonials” folder using PHP unlink() function.
Delete the testimonial from MySQL database.
Send the response back to client.
The client will remove the testimonial from local array.
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.
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.
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.
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:
Sweetalert
Datetime Picker by XD Soft
Socket IO
DataTable
RichText
PDFObject
Vue JS
Notify JS
Chart JS
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({
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:
Polling
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.
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:
Text formatiing (font size, bold, italic, underline, color).
Text alignment (left, center, right, justify).
Headings & paragraphs.
Upload images.
Attach URLs.
Adding tables.
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:
Make the PDF file downloadable, so user can view it offline too.
Display the PDF in a new window or tab.
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:
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:
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:
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.
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.