Encrypt and Decrypt Strings using Node JS and Mongo DB

In this tutorial, we are going to teach you, how you can encrypt and decrypt the strings using Node JS and Mongo DB. The encrypted strings will be saved in the database and upon retrieval will be decrypted.

Setup the Project

First, create an empty folder and open a command prompt in it. Then run the following commands in it one by one:

npm init
npm install express http mongodb crypto ejs
npm install -g nodemon
nodemon server.js

crypto module will be used to encrypt and decrypt the strings. ejs module will be used to render HTML files. Then create a file named server.js at the root of folder. Open server.js file and write the following code in it:

// initialize express JS
const express = require("express");
const app = express();

// create HTTP server
const http = require("http").createServer(app);

// [include Mongo DB module here]

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

    // [connect with Mongo DB here]
});

Open your terminal and you will see the message that the server has been started. You can access your project at http://localhost:3000/

Setup Mongo DB

Write the following lines in place of [include Mongo DB module here] section in your server.js file:

// include mongo DB
var mongodb = require("mongodb");
var MongoClient = mongodb.MongoClient;

Then connect the database in the [connect with Mongo DB here] section:

// connect with mongo DB server
MongoClient.connect("mongodb://localhost:27017", function (error, client) {
    if (error) {
        console.error(error);
        return;
    }

    // set database
    db = client.db("encrypt_decrypt_string");
    console.log("Database connected");

    // [routes goes here]

});

Save the file and open your terminal, now you will see another message that the database has been connected as well.

Encrypt the String

First, include the crypto module at the top of your server.js file:

// include crypto module
const crypto = require("crypto")

// set encryption algorithm
const algorithm = 'aes-256-cbc'

// private key
const key = "adnan-tech-programming-computers" // must be of 32 characters

// random 16 digit initialization vector
const iv = crypto.randomBytes(16)

The key and initialization vector can be any string of 32 and 16 characters respectively. But it is recommended to keep the key hard-coded and initialization vector to be random. Because IV will be saved in database.

We cannot save the key in the database, because if the database gets hacked then all your encrypted strings will be compromised as well.

After that, create a GET route that will encrypt the string and save in Mongo DB. Write the following code in the [routes goes here] section:

// route to encrypt the message
app.get("/encrypt/:message", async function (request, result) {
    // get message from URL
    const message = request.params.message;

	// random 16 digit initialization vector
	const iv = crypto.randomBytes(16);

    // encrypt the string using encryption algorithm, private key and initialization vector
    const cipher = crypto.createCipheriv(algorithm, key, iv);
    let encryptedData = cipher.update(message, "utf-8", "hex");
    encryptedData += cipher.final("hex");

    // convert the initialization vector to base64 string
    const base64data = Buffer.from(iv, 'binary').toString('base64');
    
    // save encrypted string along wtih initialization vector in database
    await db.collection("strings").insertOne({
        iv: base64data,
        encryptedData: encryptedData
    });

    // show the encrypted message
    result.send(encryptedData);
});

Save the file and try to access the URL: http://localhost:3000/encrypt/This is a test string

You can write any string in the URL and you will see the encrypted text in the browser and also in your Mongo DB.

Show all Encrypted Strings

To show all encrypted strings, we are going to use a module named ejs. Write the following line at the top of your server.js file:

// set templating engine as EJS
app.set("view engine", "ejs");

The create the following GET route to show all encrypted strings:

// route to show all encrypted messages
app.get("/", async function (request, result) {
    // get all data from database
    const data = await db.collection("strings")
        .find({})
        .sort({
            _id: -1
        }).toArray();

    // render index.ejs
    result.render("index", {
        data: data
    });
});

Create a new folder named views and inside it create a file named index.ejs. It will have the following code:

<table>
    <% for (let d in data) { %>
        <tr>
            <td>
                <a href="/decrypt/<%= data[d].encryptedData %>" target="_blank">
                    <%= data[d].encryptedData %>
                </a>
            </td>
        </tr>
    <% } %>
</table>

Access the URL: http://localhost:3000/ and you will see all your encrypted strings in descending order.

Decrypt the String

To decrypt the string, create a GET route and fetch the encrypted string and initialization vector from Mongo DB. Then we can apply the decryption using key.

// route to decrypt the message
app.get("/decrypt/:encrypted", async function (request, result) {
    // get encrypted text from URL
    const encrypted = request.params.encrypted;

    // check if text exists in database
    const obj = await db.collection("strings").findOne({
        encryptedData: encrypted
    });

    if (obj == null) {
        result.status(404).send("Not found");
        return;
    }

    // convert initialize vector from base64 to buffer
    const origionalData = Buffer.from(obj.iv, 'base64') 

    // decrypt the string using encryption algorithm and private key
    const decipher = crypto.createDecipheriv(algorithm, key, origionalData);
    let decryptedData = decipher.update(obj.encryptedData, "hex", "utf-8");
    decryptedData += decipher.final("utf8");

    // display the decrypted string
    result.send(decryptedData);
});

If you click on any string now, you will see the actual string.

[wpdm_package id=’1554′]

Premium projects bundle

Buy the 14 premium projects bundle for $1000. The bundle contains projects in the following technologies:

  • Node JS and Mongo DB
  • PHP & MySQL, Laravel
  • Vue JS
  • Android apps

Project’s list

  1. Single page chat application – Vue JS, Node JS, Mongo DB
  2. E-commerce single page application – Vue JS, Node JS, Mongo DB
  3. Chat app – Android, Web admin panel
  4. Email marketing tool – Laravel, Vue JS
  5. Financial ledger – Vue JS, Node JS, Mongo DB
  6. Image sharing web app – Node JS, Mongo DB / MySQL
  7. Movie ticket booking site – PHP & MySQL, MVC
  8. Realtime blog in Node JS and Mongo DB
  9. File transfer web app – Node JS + Mongo DB
  10. Realtime customer support chat widget
  11. Video streaming website – Node JS, Mongo DB
  12. Picture competition web app – Node JS, Mongo DB
  13. Questionnaire – Node JS, Mongo DB
  14. Blog website – Laravel, Google Adsense approved

You can buy each project separately too as well. Besides getting all the pro features of all 14 projects, we also provide additional services to them.

Secure payment

We allow users to make payments easily and securely using their bank accounts. You can contact us here and we will send you an invoice to make the payment.

Source code

Complete source code is included in all the projects. You will enjoy the pro version of each project.

Support

If you encounter any problem in installing the project or deployment, our technical support team is here. You can schedule a meeting with them and they will be able to assist you over AnyDesk or TeamViewer.

Use as a college project

If you are a student and are looking to get ready-to-go projects to learn about code and how real projects work, this will be beneficial for you. Also, Node JS projects are good learning points for students in advanced programming.

Customize as you want

Once you download the projects, you can customize them as per your needs. You can change the color theme, add new features to it, etc.

Get help in deployment

Once projects are set up in your local host, we will be here if you needed any help in deployment to the live server. For Node JS projects, we will assist you in deployment to Heroku. And for Mongo DB projects, we will help you with a deployment to mongodb.com.

Price: $1000

Out TrustPilot reviews

TrustPilot-reviews
TrustPilot-reviews

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.

How to Create a ZIP file in Node JS

In this article, we are going to teach you how you can create a ZIP file of any file or folder with all its sub-folders in Node JS.

Video tutorial:

First, you need to install a module named “zip-local” in your project. So run the following command in your command prompt or terminal:

npm install zip-local

Then you need to include the module in your server file where you want to use it.

const zipLocal = require("zip-local")

After that, whenever you want to want to execute the code to create a folder ZIP, paste the following lines:

zipLocal.sync.zip("files").compress().save("my-files.zip")

zip(): Accepts the path and name of the file or folder that needs to be zipped.

save(): Accepts the path and name of a new ZIP file.

So that’s how you can create a zip file in your Node JS project.
Learn how to password protect a zip file from this tutorial.