Check internet connection javascript

In this article, we are going to teach you how you can check your internet connection using Javascript. We will be displaying a toast or alert message to the user if their internet gets disconnected. And hide the toast when the internet gets reconnected.

Video tutorial:

First, you need to download a library called Toastify. You can download it from GitHub.

After that, you need to include it in your project like this:

<link rel="stylesheet" type="text/css" href="js/toastify.css" />
<script src="js/toastify.js"></script>

Then you need to download another library called Checknet. You can also download it from GitHub too.

You need to include that library as well:

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

Javascript code to check internet connection

After that, the following code will show a toast message when the internet is down. And it will keep displaying until the network is restored or the toast is manually closed:

<script>

    // create global toastify instance
    var toastify = null;

    // check when the internet is disconnected
    Checknet.addEventListener('dropped', function() {

        // show a toast message
        toastify = Toastify({
            text: "Internet connection lost.",
            duration: -1,
            newWindow: false,
            close: true,
            gravity: "bottom", // `top` or `bottom`
            position: "center", // `left`, `center` or `right`
            stopOnFocus: true, // Prevents dismissing of toast on hover
            style: {
                background: "red",
            },
            onClick: function() {} // Callback after click
        }).showToast();
    });

    // callback when the connection is restored
    Checknet.addEventListener('restored', function() {

        // hide the toast if it is being displayed
        if (toastify != null) {
            toastify.hideToast();
        }
    });

    // start listening for network connectivity
    Checknet.start();

</script>

Refresh the page now and try to disconnect your laptop from the internet. You will immediately see a toast message saying that the internet connection is lost.

Then re-connect the internet, the toast message will be removed automatically. You do not have to refresh the page.

Hope you find this tutorial helpful. If you did, you also browse our Javascript tutorials.

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.

Email marketing tool in Laravel and Vue JS

An email marketing tool is created in Laravel and Vue JS. It is a single-page application. It allows you to send bulk emails to a large group of people. The database used for this project is MySQL.

Demo:

https://emailmarketingtool.adnan-tech.com

How to use:

  1. Add your SMTP account
  2. Create a list
  3. Add subscribers to a list
  4. Create campaign
  5. Run campaign

1. Add your SMTP account

The first step is to add an SMTP account. You can add your hosting SMTP account or even your personal Gmail account as well. To add an SMTP account, you need to enter your hostname, usually, it is like this mail.yourdomain.com. But you need to visit your hosting cPanel and go to the “Email Accounts” to confirm.

Then you need to enter the “Display name“. This is the name that will be displayed to the recipients when you start sending emails through campaigns. And finally, the email and password of your email account. Your credentials are stored securely in our server and you can delete the SMTP account at any time and it will be deleted permanently (no trash can or backup).

Contact us to get help in this step.

Note: If you delete the SMTP account, all campaigns where that account is used, will be deleted as well.

2. Create a list

Then you need to create a list. In this list, you can add as many people as you want. You only need to enter the name of the list, for example, “USA Subscribers” etc. You can add multiple lists as well. Then while running the campaign, you can simply select the list and it will automatically send emails to all the users in that list.

3. Add subscribers in a list

Now that you have created a list, you can start adding subscribers to it. Adding a subscriber is super easy, simply enter the name and email of the person. Then select the list where he wanted to be added. You can add the same subscriber in multiple lists as well. There is no such restriction.

4. Create a campaign for email marketing

Creating a campaign is also super simple. You just need to enter the name of the campaign like “Black Friday Sales” etc. Then you need to write the content of the email that needs to be sent. The content of the email can be HTML too so you can use HTML tags and CSS properties as well.

Then you need to select the list for that campaign. The campaign will send emails to all the subscribers that are added to that list. And finally, you need to select the SMTP account from whom the email should be sent. Since you might have multiple SMTP accounts like:

  • sales@yourwebsite.com
  • support@yourwebsite.com
  • info@yourwebsite.com
  • no-reply@yourwebsite.com

You can select the SMTP account of your choice to use as a “Sender” of that particular campaign.

5. Run an email marketing campaign

The final step is to run the campaign and sit and relax. You will see all your added campaigns with a status. We have 3 statuses for each campaign:

  • draft: The campaign is created and ready to start sending emails.
  • active: The campaign has been started and is sending emails to the selected list of subscribers. You can check every 30 minutes to check the progress.
  • done: The campaign has sent emails to all the subscribers added to that list.

Dynamic variables in email

Since in email marketing you will be sending emails in bulk, you might want to address each user differently. For example, it is better to have an email that starts with “Hello Mr. John” rather than just “Hello”. Personalizing your email has a higher chance of getting more sales.

Track each email

The email will be sent to a large number of people and the content of each email can be different like the recipient name etc. So you can see the content of each email sent to subscribers so you can know if your users have received the email correctly.

Send single email

Campaigns are used to send bulk emails, but sometimes you just want to send an email to a single person only. We have added a feature that allows you to do that. You can simply enter the name and email address of the recipient, and enter the subject and body of the email. Again the body of the email can be HTML too.

Email with attachments

When sending single emails, you can also attach multiple documents to them. The documents will be attached to the email and the recipient will be able to download it directly from their mail client, for example, Gmail, Outlook, Webmail, Thunderbird, etc.

Business model

If you buy this project, you can also make money from it. Just give a trial period of 3 days with all features to your users, after that you can charge per day. You can see the pricing from here, you can set the pricing as you desire. Check the below video to find out how the trial period works:

Google one-tap sign in and sign up

You can sign in or sign-up with your Google account with just one click. If the user’s account is not created, then it will be created automatically and the user will be logged-in. Otherwise, it will simply log in to the user.

Technical details

  1. Laravel 8
  2. MySQL
  3. Vue JS
  4. Materialize CSS
  5. PHPMailer
  6. Eloquent ORM