Posted on Leave a comment

Bootstrap Sticky Navbar Menu on Scroll using CSS and JavaScript

by Vincy. Last modified on January 13th, 2022.

The Bootstrap navbar is a menu responsive header with navigation. Bootstrap supports enabling many UI effects with this navbar component. For example,

  1. Sticky navbar on scrolling the content.
  2. Slide-in effect by using Bootstrap expand-collapse
  3. Mobile-friendly responsive menu navigation.

This article is for creating a Bootstrap sticky navbar on the page top header. It shows both static and dynamic content on the navigation header. Let us see how to display a sticky navbar on a page using Bootstrap.

This quick example shows code to display the stick navbar. It includes Boostrap into the code by using CDN URL. You can also install Bootstrap via composer into your application vendor directory.

It uses Bootstrap sticky-top to the .navbar element.

Quick Example

Include this into the HTML <head>


<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script> 

Put this Bootstrap sticky navbar into the <body>


<nav class="navbar navbar-expand-lg navbar navbar-expand-sm sticky-top navbar-dark bg-dark"> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"><a class="nav-link" href="#">Home</a></li> <li class="nav-item active"><a class="nav-link" href="#">Contact</a> </li> <li class="nav-item active"><a class="nav-link" href="#">About</a> </ul> </div>
</nav> 

Bootstrap navbar default behaviour

The below list shows the default behaviour of the Bootstrap navbar. This article features this UI component more by making it sticky on scrolling.

  • Navbar is responsive by default in any viewport.
  • It is hidden for printing but can be overridden by adding .d-print to the .navbar.
  • It lets assistive mechanism to identify navbar by using <nav>. Bootstrap recommends to add role=”navigation” attribute for the <div> like containers.

Uses  of  Bootstrap sticky navbar

The Bootstrap sticky navbar provides a fixed header element mostly at the top. Sometimes, it will be used in the page and form footer.

The following list of items shows some of the uses of a sticky navbar in a website.

  1. To create a fixed header menu. Eg: The header menu links like ‘Contact’, ‘Request a quote’ will be useful if they are sticky on scroll.
  2. To create fixed footer links. Eg: The social media share option in the footer can be sticky to let the user to share the content at any time of reading.
  3. To keep a HTML form footer sticky on scroll. The payment form with the ‘Pay now’ or ‘Buy now’ control should be fixed regardless of the page scroll. It reduces friction and allows users to buy the product easily.

Bootstrap sicky navbar with static menu HTML

This code will help users having static websites who want to add a sticky navbar in the header.

This example includes an expandable static header menu. It shows the sub-menu dropdown on clicking the main menu link.

bootstrap-sticky-navbar-static.php


<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</head>
<style>
.container { height: 1000px;
}
</style>
<body> <nav class="navbar navbar-expand-lg navbar navbar-expand-sm sticky-top navbar-dark bg-dark"> <a class="navbar-brand" href="#">Site logo</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"><a class="nav-link" href="#">Home</a></li> <li class="nav-item active"><a class="nav-link" href="#">Contact</a> </li> <li class="nav-item active"><a class="nav-link" href="#">About</a> </li> <li class="nav-item dropdown active"><a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Services </a> <div class="dropdown-menu" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="#">Map integration</a> <a class="dropdown-item" href="#">Chart generation</a> <a class="dropdown-item" href="#">Report generation </a> </div></li> <li class="nav-item dropdown active"><a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Projects </a> <div class="dropdown-menu" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="#"> Chat plugin</a> <a class="dropdown-item" href="#">Form builder</a> </div></li> <li class="nav-item active"><a class="nav-link disabled" href="#">What's new</a></li> </ul> <form class="form-inline my-2 my-lg-0"> <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> </div> </nav> <div class="container"> <div class="row"> <div class="col-12 py-4"> <h1>Page scroll content</h1> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent tincidunt dolor eget lorem blandit, auctor porttitor enim faucibus. Mauris sed elit sollicitudin, aliquam lorem nec, suscipit ex. Sed mollis rhoncus scelerisque. Morbi varius a est sed luctus. Morbi sapien velit, venenatis a sapien vitae, commodo rutrum erat. Nam volutpat diam ac convallis egestas. Nunc convallis tempor hendrerit. Aenean turpis quam, viverra eu eros quis, ornare tristique velit. </div> </div> </div>
</body>
</html> 

Bootstrap navbar with data-target link

In the bootstrap sticky navbar, it allows specifying the data target to expand.

In this example, the header navbar shows a cart icon on page load. The header HTML also contains the cart info hidden by default.

The navbar cart element targets this hidden cart info to expand it on the click event.

navbar-with-data-target.php


<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</head>
<style>
.container { height: 1000px;
}
</style>
<body> <div class="pos-f-t sticky-top"> <div class="collapse " id="navbarToggleExternalContent"> <div class="bg-dark p-4 text-right"> <div class="text-light ">Item count = 5</div> <div class="text-light ">Total price = $375</div> </div> </div> <nav class="navbar navbar-dark bg-dark"> <div class="col-lg-12"> <button class="navbar-toggler float-right" type="button" data-toggle="collapse" data-target="#navbarToggleExternalContent" aria-controls="navbarToggleExternalContent" aria-expanded="false" aria-label="Toggle navigation"> <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-shopping-cart"> <circle cx="9" cy="21" r="1"></circle> <circle cx="20" cy="21" r="1"></circle> <path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"></path></svg> </button> </div> </nav> </div> <div class="container"> <div class="row"> <div class="col-12 py-4"> <h1>Page scroll content</h1> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent tincidunt dolor eget lorem blandit, auctor porttitor enim faucibus. Mauris sed elit sollicitudin, aliquam lorem nec, suscipit ex. Sed mollis rhoncus scelerisque. Morbi varius a est sed luctus. Morbi sapien velit, venenatis a sapien vitae, commodo rutrum erat. Nam volutpat diam ac convallis egestas. Nunc convallis tempor hendrerit. Aenean turpis quam, viverra eu eros quis, ornare tristique velit. </div> </div> </div>
</body>
</html> 

The below screenshot cart icon and the expanded cart info. It displays the number of items in the cart and the total amount.

bootstrap sticky navbar cart info

bootstrap data target

Dynamic menu in the sticky navbar

This example includes HTML as like as the static menu example. The difference is the menu items are from the database.

This code uses a PHP class DataSource.php to process the database operations. It uses MySqli with prepared-statement to access the database.

bootstrap-sticky-navbar-dynamic.php


<?php
namespace Phppot; use Phppot\DataSource;
require_once __DIR__ . '/DataSource.php';
$conn = new DataSource();
$query = "SELECT * FROM tbl_menu where parent = 0";
$mainresult = $conn->select($query);
?>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</head>
<style>
.container { height: 1000px;
}
</style>
<body> <nav class="navbar navbar-expand-lg navbar navbar-expand-sm sticky-top navbar-dark bg-dark"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <?php foreach ($mainresult as $key => $val){?> <li class="nav-item dropdown active"><a class="nav-link " href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"><?php echo $mainresult[$key]["menu_name"];?></a> <?php $query = "SELECT * FROM tbl_menu where parent= ?"; $paramType = "i"; $paramValue = array( $mainresult[$key]["id"] ); $subresult = $conn->select($query, $paramType, $paramValue); ?> <?php if (! empty($subresult)) {?> <div class="dropdown-menu" aria-labelledby="navbarDropdown"> <?php foreach ($subresult as $k => $v) {?> <a class="dropdown-item" href="#"><?php echo $subresult[$k]["menu_name"];?></a> <?php }?> </div> <?php } } ?> </li> </ul> <form class="form-inline my-2 my-lg-0"> <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> </div> </nav> <div class="container"> <div class="row"> <div class="col-12 py-4"> <h1>Page scroll content</h1> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent tincidunt dolor eget lorem blandit, auctor porttitor enim faucibus. Mauris sed elit sollicitudin, aliquam lorem nec, suscipit ex. Sed mollis rhoncus scelerisque. Morbi varius a est sed luctus. Morbi sapien velit, venenatis a sapien vitae, commodo rutrum erat. Nam volutpat diam ac convallis egestas. Nunc convallis tempor hendrerit. Aenean turpis quam, viverra eu eros quis, ornare tristique velit. </div> </div> </div>
</body>
</html> 

Responsive Bootstrap sticky navbar

Bootstrap navbar is responsive by default. In a mobile viewport, it displays a slide-down responsive menu. On clicking the menu-expand icon it drops down the menu items.

responsive-navbar.php


<?php
namespace Phppot; use Phppot\DataSource;
require_once __DIR__ . '/DataSource.php';
$conn = new DataSource();
$query = "SELECT * FROM tbl_menu";
$result = $conn->select($query);
?>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</head>
<style>
.container { height: 1000px;
}
</style>
<body> <nav class="navbar navbar-expand-lg sticky-top navbar-dark bg-dark"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarTogglerDemo03" aria-controls="navbarTogglerDemo03" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarTogglerDemo03"> <ul class="navbar-nav mr-auto mt-2 mt-lg-0"> <?php foreach ($result as $key => $val){?> <li class="nav-item active"><a class="nav-link" href="#"><?php echo $result[$key]["responsive_name"];?> </li> </a><?php }?> </ul> <form class="form-inline my-2 my-lg-0"> <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> </div> </nav> <div class="container"> <div class="row"> <div class="col-12 py-4"> <h1>Page scroll content</h1> Dolor sit amet, consectetur adipiscing elit. </div> </div> </div>
</body>
</html> 

Database script

Import this database script to display a dynamic Bootstrap sticky navbar. It contains menu items and the parent-child relationship data.

database.sql


CREATE TABLE `tbl_menu` ( `id` int(11) NOT NULL, `menu_name` text NOT NULL, `parent` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; --
-- Dumping data for table `tbl_menu`
-- INSERT INTO `tbl_menu` (`id`, `menu_name`, `parent`) VALUES
(1, 'Site logo', '0'),
(2, 'Home', '0'),
(3, 'Contact', '0'),
(4, 'About', '0'),
(5, 'Services', '0'),
(8, 'Map integration', '5'),
(9, 'Chart generation', '5'),
(10, 'Report generation', '5'),
(11, 'Projects', '0'),
(12, 'Chat plugin', '11'),
(13, 'Form builder', '11'),
(14, 'What\'s new', '0'); --
-- Indexes for table `tbl_menu`
--
ALTER TABLE `tbl_menu` ADD PRIMARY KEY (`id`); ALTER TABLE `tbl_menu` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=15; 

Bootstrap sticky navbar output

bootstrap sticky navbar

responsive sticky navbar
Download

↑ Back to Top

Posted on Leave a comment

HTML Contact Form Template to Email with Custom Fields

by Vincy. Last modified on January 5th, 2022.

Why do we need a contact form on a website? It is to enable (prospective) customers to connect with you.

Elon Musk says, “…maximize the area under the curve of customer happiness…”.

So, increasing the possibilities of reading the customer’s mind will drive us forward to attain the goal. The contact form interface is one of the tools to know our customers.

Let’s design a simple and useful contact form component for your website. The below sections explain how to create a contact form from the scratch.

Uses of a contact form in a website

There are a few more advantages of having a contact form interface.

  1. It helps have conversions by knowing the requirement of the customers.
  2. It helps to know the scope of improvements.
  3. It helps to collect the end users’ ideas and opinions relevant to the business model.

About this example

This example code is for designing an HTML contact form with the following features.

  1. Contact form with custom fields.
  2. Add/Delete custom fields dynamically via jQuery.
  3. Send an email with the posted form data.
  4. Storing the form data into the database.

Application configuration

This HTML contact form backend code allows both send an email and the store-to-database action. But, The store-to-database feature is optional and disabled initially.

This configuration file has the flag to enable or disable the store-to-database feature.

By default, the ENABLE_DATABASE flag is set to false. Make it true to show the “store-to-database” control in the UI.

config.php


<?php const ENABLE_DATABASE = false;
?> 

HTML contact form landing page code

This HTML code is to display a contact form on a landing page. The index.php file includes the following to make an HTML contact form dynamic.

  • It contains the form HTML.
  • It includes the application configuration file.
  • It requires the form action PHP file to process data submitted by the user.
  • It includes the form validation javascript and required jQuery dependency.

By connecting all the contact form example components, this file lets the HTML contact form be interactive.

It shows two controls to save to the database or to send an email. By default the save to the database control will be hidden. It is configurable to display this option.

index.php


<?php require_once __DIR__ . '/contact-form-action.php';?>
<?php require_once __DIR__ . '/config.php';?>
<!DOCTYPE html>
<html>
<head>
<link href="style.css" rel="stylesheet" type="text/css" />
<title>HTML Contact Form with Add More Custom Fields</title>
<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
<script type="text/javascript" src="js/contact.js">
</script>
</head>
<body> <h1>HTML Contact Form with with Add More Custom Fields</h1> <div class="form-container"> <form name="mailForm" id="mailForm" method="post" action="" enctype="multipart/form-data" onsubmit="return validate()"> <div class="input-row"> <label style="padding-top: 20px;">Name</label> <span id="userName-info" class="info"></span><br /> <input type="text" class="input-field" name="userName" id="userName" /> </div> <div class="input-row"> <label>Subject</label> <span id="subject-info" class="info"></span><br /> <input type="text" class="input-field" name="subject" id="subject" /> </div> <div class="input-row"> <label>Message</label> <span id="userMessage-info" class="info"></span><br /> <textarea name="userMessage" id="userMessage" class="input-field" id="userMessage" cols="60" rows="6"></textarea> </div> <div class="input-row"> <div class="custom-field-name"> <input type="text" class="custom-field" name="Fieldname[]" id="Fieldname" placeholder="Fieldname" /> </div> <div class="custom-field-value"> <input type="text" class="custom-field" name="Fieldvalue[]" id="Fieldvalue" placeholder="Fieldvalue" /> </div> <div class="col"> <div class="custom-field-col"> <div onClick="addMore();" class="plus-button" title="Add More"> <img src="./images/icon-add.svg" alt="Add More"> </div> <div onClick="remove();" class="minus-button" title="Remove"> <img src="./images/icon-remove.svg" alt="Remove"> </div> </div> </div> </div> <div class="col"> <input type="submit" name="send" id="send" class="btn-submit" value="Send email" /> <div class="col"> <?php if(ENABLE_DATABASE == true){?> <input type="submit" name="savetodatabase" class=btn-submit id="savetodatabase" value="Save database" /> <?php }?> </div> <div id="pageloader"> <img id="loading-image" src="./images/loader.gif" /> </div> </div> <div id="statusMessage"> <?php if (! empty($message)) { ?> <p class='<?php echo $type; ?>Message'><?php echo $message; ?></p> <?php } ?> </div> </form> </div>
</body>
</html> 

Contact form validation script using jQuery

Form validation can be done either on the server-side or client-side. But, validation on the client-side with Javascript is very usual. And it is quite easy and seamless also.

So, I created a jQuery-based validation script to validate the HTML contact form. It requires all fields to be mandatory except the custom fields.

The contact form custom fields are optional. But, in PHP, it checks the custom field name and value not to be empty. This server-side validation will be done before preparing the contact-form action parameter.

Other JavaScript handlers

This contact.js file does not only include the validation handler. But also, defines handlers to add, delete custom field rows in the UI.

It allows anyone row of custom field inputs to be in the HTML contact form. It is coded in the showHideControls() function of the below file.

contact.js


function validate() { var valid = true; $(".info").html(""); var userName = document.forms["mailForm"]["userName"].value; var subject = document.forms["mailForm"]["subject"].value; var userMessage = document.forms["mailForm"]["userMessage"].value; if (userName == "") { $("#userName-info").html("(required)"); $("#userName").css('background-color', '#FFFFDF'); valid = false; } if (subject == "") { $("#subject-info").html("(required)"); $("#subject").css('background-color', '#FFFFDF'); valid = false; } if (userMessage == "") { $("#userMessage-info").html("(required)"); $("#userMessage").css('background-color', '#FFFFDF'); valid = false; } handleLoader(valid); return valid;
}
function handleLoader(valid) { if (valid == true) { if ($("#savetodatabase")) { $("#savetodatabase").hide();// hide submit } $("#send").hide(); $("#loading-image").show();// show loader }
}
function addMore() { $(".input-row:last").clone().insertAfter(".input-row:last"); $(".input-row:last").find("input").val(""); showHideControls();
}
function remove() { $(".input-row:last").remove(".input-row:last"); $(".plus-button:last").show(); $(".minus-button:last").hide(); $(".input-row:last").find("input").val("");
}
function showHideControls() { $(".plus-button").hide(); $(".minus-button").show(); $(".minus-button:last").hide(); $(".plus-button:last").show();
} 

PHP contact form action to send email or store to Database

Generally, the contact form action will send an email with the body of posted form data. This example gives additional support to store the posted message and the details in the database.

This will be suitable when the HTML contact form is used to collect the following.

  • Users’ feedback
  • Support request
  • Project inquiry
  • Comments

This PHP code handles the form submission by checking the posted action index. It uses the PHP mail() function to send the HTML contact form email. If you want to send an email via SMTP using the PHPMailer library, the link has the code for it.

Refer PHP.net manual to know more about this mail() function.

If the user clicks the ‘Save to database’ button, it connects the Database via the DataSource class. It triggers insert action by sending the form data in the query parameters.

contact-form-action.php


<?php
namespace Phppot; use Phppot\DataSource;
require_once __DIR__ . '/DataSource.php';
require_once __DIR__ . '/index.php';
if (! empty($_POST["savetodatabase"])) { $conn = new DataSource(); $query = "INSERT INTO tbl_contact_mail(userName,subject,userMessage)VALUES(?,?,?)"; $paramType = 'sss'; $paramValue = array( $_POST["userName"], $_POST["subject"], $_POST["userMessage"] ); $id = $conn->insert($query, $paramType, $paramValue); if (! empty($_POST["Fieldname"])) { $customFieldLength = count($_POST["Fieldname"]); for ($i = 0; $i < $customFieldLength; $i ++) { if (! empty($_POST["Fieldname"][$i]) && $_POST["Fieldvalue"][$i]) { $query = "INSERT INTO tbl_custom_field(fieldName,fieldValue,contact_id)VALUES(?,?,?)"; $paramType = 'ssi'; $paramValue = array( $_POST["Fieldname"][$i], $_POST["Fieldvalue"][$i], $id ); $conn->insert($query, $paramType, $paramValue); } } } if ($query==true) { $message = "Data Saved"; $type = "success"; } else { $message = "Problem in data"; $type = "error"; }
} elseif (! empty($_POST["send"])) { if (isset($_POST["userName"])) { $userName = $_POST["userName"]; } if (isset($_POST["subject"])) { $subject = $_POST["subject"]; } if (isset($_POST["userMessage"])) { $message = $_POST["userMessage"]; } $htmlBody = '<div>' . $message . '</div>'; $htmlBody .= '<br>'; $htmlBody .= '<div style=font-weight:bold;>More details:' . '</div>'; for ($i = 0; $i < count($_POST["Fieldname"]); $i ++) { if (isset($_POST["Fieldname"][$i]) && (isset($_POST["Fieldvalue"][$i]))) { $fieldname = $_POST["Fieldname"][$i]; $fieldvalue = $_POST["Fieldvalue"][$i]; $htmlBody .= '<div>' . $fieldname . '<div style=display:inline-block;margin-left:10px;>' . $fieldvalue . '</div>'; } } $htmlBody .= '<br><br><br>'; $htmlBody .= '<div>Thank You...!' . '</div>'; // Run loop
$recipient="recipient@domain.com"; if (mail($recipient, $subject, $htmlBody)) { $message = "Mail sent successfully"; $type = "success"; } else { $message = "Problem in sending email"; $type = "error"; }
} ?>

Database script

This .sql file contains the create a statement and required indices of the tbl_contact table.

Import this SQL after setting up this example code in your PHP environment.

Note: This is only required if you need the “Store to database” option.

database.sql


-- -------------------------------------------------------- --
-- Table structure for table `tbl_contact`
-- CREATE TABLE `tbl_contact` ( `id` int(11) NOT NULL, `userName` varchar(255) NOT NULL, `subject` varchar(255) NOT NULL, `userMessage` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -------------------------------------------------------- --
-- Table structure for table `tbl_custom_field`
-- CREATE TABLE `tbl_custom_field` ( `id` int(11) NOT NULL, `contact_id` int(11) NOT NULL, `fieldName` varchar(11) NOT NULL, `fieldValue` varchar(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; --
-- Indexes for dumped tables
-- --
-- Indexes for table `tbl_contact`
--
ALTER TABLE `tbl_contact` ADD PRIMARY KEY (`id`); --
-- Indexes for table `tbl_custom_field`
--
ALTER TABLE `tbl_custom_field` ADD PRIMARY KEY (`id`); --
-- AUTO_INCREMENT for dumped tables
-- --
-- AUTO_INCREMENT for table `tbl_contact`
--
ALTER TABLE `tbl_contact` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; --
-- AUTO_INCREMENT for table `tbl_custom_field`
--
ALTER TABLE `tbl_custom_field` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; 

html contact form custom field

Conclusion

I hope this article gives you a useful contact form component for your website. It will be helpful to have a good idea to create a form like this on your own.

Custom field integration with contact forms a rare and tricky requirement. Share your thoughts in the comments section to continue posting useful codes.

Download

↑ Back to Top

Posted on Leave a comment

Stripe Apple Pay Web Integration with Example

by Vincy. Last modified on December 7th, 2021.

Integrating Stripe Apple pay into a web application is easy. It requires a few steps to achieve this integration. This article shows how to enable Apple or Google pay option using Stripe.

We can divide this article into 2 sections. It narrates the action items, prerequisites, and codes for the payment integration.

  1. Preparing your web environment to display the payment request option.
  2. Building PHP example for  Stripe Apple Pay integration.

If you are new to the Stripe payment integration, check with the linked article. It explains how to get the Stripe API app credentials and other basic knowledge.

About Stripe Payment Request Button Element

This payment method collects details from customers using Stripe Apple Pay dialog. We have already seen how to collect recurring payments using Stripe subscriptions.

Stripe’s Payment Request Button method mounts a UI control to allow payment. This is a single point of integration for Apple Pay, Google Pay, and Microsoft Pay.

By ticking up the list of prerequisites in the documentation, we can see any one of the below buttons in the UI.

stripe apple pay

1. Preparing your web environment to display the payment request option

This section will tell the steps to display the Stripe apple pay. In Chrome or Microsoft edge, this will show other payment request buttons in a web interface.

  1. Ensure that the domain is HTTPS enabled.
  2. Let the domain pass through the Apple pay’s verification process.
  3. Save cards or other payment methods to the browser. The specifications vary based on the payment methods and browsers.

How to verify a domain with Apple Pay?

Follow the below steps to display the Stripe Apple pay button in your interface.

  1. Download and put the domain association file in the following path of your web root. /.well-known/apple-developer-merchantid-domain-association.
  2. Request to create a Stripe Apple Pay domain. This can be done in any one of the below methods.
    • By navigating to the Stripe Apple Pay tab in the Account Settings of your Dashboard.
    • By using the API with your live secret key.
  3. Use API keys to make payments via the website registered with Apple Pay Stripe.

Note: Need not create Apple merchant id or generate certificate signing request (CSR). Stripe will take care of these in the back end.

API request to create Stripe Apple Pay domain

The following PHP script shows how to create a Stripe API.


\Stripe\Stripe::setApiKey("STRIPE SECRET KEY HERE"); \Stripe\ApplePayDomain::create([ 'domain_name' => 'example.com',
]);

2. Building PHP example for  Stripe Apple pay integration

These are the steps to integrate Stripe Apple pay in a PHP web application. Some of the below are similar as we have seen in the Stripe payment gateway integration example.

  1. Download the Stripe API client.
  2. Configure Stripe API keys and tokens.
  3. Verify the payment request and mount the Stripe Apple pay button.
  4. Request and Confirm payment.
  5. Handle shipping/delivery address change events.
  6. Creating PHP endpoints to prepare and initiate Stripe API requests.

Download the Stripe client

Download PHP stripe API client and add up in the application dependency. This will be helpful to create AppleDomain and PaymentIntent objects via API.

It is available on Github. You can install this via composer also. The command to install the Stripe-PHP library is,


composer require stripe/stripe-php

Configure Stripe API keys and tokens

This is the web application config file. It includes the keys used to access the payment request API for Stripe Apple pay integration.

It also contains the web application root and the payment or order endpoint URLs. It defines Product details and shipping amount to build the payment request.

Common/config.php


<?php
namespace Phppot; class Config
{ const ROOT_PATH = "http://localhost/stripe-apple-pay"; /* Stripe API test keys */ const STRIPE_PUBLISHIABLE_KEY = ""; const STRIPE_SECRET_KEY = ""; const STRIPE_WEBHOOK_SECRET = ""; const RETURN_URL = Config::ROOT_PATH . "/success.php"; /* PRODUCT CONFIGURATIONS BEGINS */ const PRODUCT_NAME = 'A6900 MirrorLess Camera'; const PRODUCT_IMAGE = Config::ROOT_PATH . '/images/camera.jpg'; const PRODUCT_PRICE = '289.61'; const CURRENCY = 'usd'; const US_SHIPPING = 7; const UK_SHIPPING = 12;
} 

Verify the payment request and mount Stripe Apple pay button

The index.php is a landing page that contains the product tile. It has the container to mount the Stripe Apple pay button.

The HTML elements have the data attributes to have the payment configurations.

In imports the Stripe.js library and the payment.js file created for this example.

index.php


<?php
namespace Phppot; require_once __DIR__ . '/Common/Config.php';
?>
<html>
<title>Stripe Apple Pay integration</title>
<head>
<link href="assets/css/style.css" type="text/css" rel="stylesheet" />
</head>
<body> <div class="phppot-container"> <h1>Stripe Apple Pay integration</h1> <div id="payment-box" data-pk="<?php echo Config::STRIPE_PUBLISHIABLE_KEY; ?>" data-return-url="<?php echo Config::RETURN_URL; ?>"> <input type="hidden" id="unit-price" value="<?php echo Config::PRODUCT_PRICE; ?>" /> <input type="hidden" id="product-label" value="<?php echo Config::PRODUCT_NAME; ?>" /> <input type="hidden" id="currency" value="<?php echo Config::CURRENCY; ?>" /> <input type="hidden" id="shipping-amount" value="<?php echo Config::US_SHIPPING; ?>" /> <img src="<?php echo Config::PRODUCT_IMAGE; ?>" /> <h4 class="txt-title"><?php echo Config::PRODUCT_NAME; ?></h4> <div class="txt-price">$<?php echo Config::PRODUCT_PRICE; ?></div> </div> <!-- Element target to render Stripe apple pay button --> <div id="payment-request-button"> <!-- A Stripe Element will be inserted here. --> </div> </div> <script src="https://js.stripe.com/v3/"></script> <script src="assets/js/payment.js"></script>
</body>
</html>

This is a partial code of the payment.js file. It shows the script required for rendering the Stripe Apple pay button into the UI. It builds the Stripe payment request object by using the following details.

  • Customer details: name, email, address.
  • Amount
  • Currency
  • Shipping details: amount, description.

The data for these details are from the config file. The payment form HTML contains hidden fields and data attributes to hold the config. This script uses the data attributes and hidden data to prepare the request.

After preparing the request body, it calls canMakePayment() to verify the paymentRequest object. Once verified, then it will render the Apple pay button in the UI.

assets/js/payment.js


var publishableKey = document.querySelector('#payment-box').dataset.pk;
var returnURL = document.querySelector('#payment-box').dataset.returnUrl;
var unitPrice = document.querySelector('#unit-price').value;
unitPrice = Math.round((unitPrice * 100));
var productLabel = document.querySelector('#product-label').value;
var currency = document.querySelector('#currency').value;
var shippingAmount = document.querySelector('#shipping-amount').value;
shippingAmount = Math.round((shippingAmount * 100)); var stripe = Stripe(publishableKey, { apiVersion: "2020-08-27",
});
var paymentRequest = stripe.paymentRequest({ country: 'US', currency: currency, total: { label: productLabel, amount: unitPrice, }, requestPayerName: true, requestPayerEmail: true, requestShipping: true, shippingOptions: [ { id: 'Default Shipping', label: 'Default Shipping', detail: '', amount: shippingAmount, }, ],
}); var elements = stripe.elements();
var prButton = elements.create('paymentRequestButton', { paymentRequest: paymentRequest,
}); // Verify payment parameters with the the Payment Request API.
paymentRequest.canMakePayment().then(function(result) { if (result) { prButton.mount('#payment-request-button'); } else { document.getElementById('payment-request-button').style.display = 'none'; }
});

Request and Confirm payment

This section contains the rest of the payment.js code. It creates paymentIntent object by clicking the ‘pay’ button on the payment overlay.

Once paymentIntent is created, the endpoint returns the client-secret-key. Then, the script calls stripe.confirmCardPayment with the reference of the client-secret-key.

assets/js/payment.js


paymentRequest.on('paymentmethod', function(ev) { //Create Stripe payment intent var requestParam = { email: ev.payerEmail, unitPrice: unitPrice, currency: currency, name: ev.payerName, address: ev.shippingAddress.addressLine[0], country: ev.shippingAddress.country, postalCode: ev.shippingAddress.postalCode, shippingPrice: ev.shippingOption.amount, }; var createOrderUrl = "ajax-endpoint/create-stripe-order.php"; fetch(createOrderUrl, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(requestParam) }).then(function(result) { return result.json(); }).then(function(data) { // Script to confirm payment stripe.confirmCardPayment( data.clientSecret, { payment_method: ev.paymentMethod.id }, { handleActions: false } ).then(function(confirmResult) { if (confirmResult.error) { // Report to the browser that the payment failed, prompting it to // re-show the payment interface, or show an error message and close // the payment interface. ev.complete('fail'); } else { // Report to the browser that the confirmation was successful, prompting // it to close the browser payment method collection interface. ev.complete('success'); // Check if the PaymentIntent requires any actions and if so let Stripe.js // handle the flow. If using an API version older than "2019-02-11" instead // instead check for: `paymentIntent.status === "requires_source_action"`. if (confirmResult.paymentIntent.status === "requires_action") { // Let Stripe.js handle the rest of the payment flow. stripe.confirmCardPayment(clientSecret).then(function(result) { if (result.error) { // The payment failed -- ask your customer for a new payment method. } else { // The payment has succeeded. window.location.replace(returnURL + "?orderno=" + data.orderHash); } }); } else { // The payment has succeeded. window.location.replace(returnURL + "?orderno=" + data.orderHash); } } }); });
});

Handle shipping/delivery address change events

This section deals with the shipping options on-change events. This code is applicable only if the payment object is enabled with shipping options.

It hits the PHP endpoint via AJAX and gets the JSON to change the shipping options. It passes the selected shipping address to the PHP.

assets/js/payment.js


paymentRequest.on('shippingaddresschange', function(ev) { // Perform server-side request to fetch shipping options fetch('ajax-endpoint/calculate-product-shipping.php', { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ adress: ev.shippingAddress }) }).then(function(response) { return response.json(); }).then(function(result) { ev.updateWith({ status: 'success', shippingOptions: result.shippingOptions, }); });
});

This is the PHP endpoint file that reads the shipping data sent via AJAX. It parses the shipping data and gets the country from it.

It uses an appropriate shipping amount from the config based on the country. You can include your additional shipping calculation here if needed.

It returns a JSON response with the shipping address and corresponding amount.

ajax-endpoint/calculate-product-shipping.php


<?php
require_once __DIR__ . '/../Common/Config.php'; $content = trim(file_get_contents("php://input")); $jsondecoded = json_decode($content, true);
$country = filter_var($jsondecoded["adress"]["country"], FILTER_SANITIZE_STRING);
if ($country == 'UK') { $shippingAmount = Config::UK_SHIPPING;
} else { $shippingAmount = Config::US_SHIPPING;
} $shippingOptions = array( "shippingOptions" => array( array( "id" => 'Edited shipping', 'label' => "Shipping Costs based on Country", 'detail' => $detail, 'amount' => $shippingAmount ) )
); echo json_encode($shippingOptions);
exit(); ?>

Creating PHP endpoints to prepare and initiate Stripe API requests

The below PHP files contains the server-side code that hits API. It reads the request body and creates a payment object on sending the Stripe apple pay request.

The StripeService.php file sets the API secret key to the Stripe object. It contains a function captureResponse() function that updates orders and payment entity.

Stripe calls the webhook endpoint as configured in the config.php. This endpoint reads Stripe response. Then, it invokes the captureResponse() function to update the database.

PHP AJAX endpoint to create order

ajax-endpoint/create-stripe-order.php


<?php
namespace Phppot; use Phppot\StripeService;
use Phppot\StripePayment;
require_once __DIR__ . '/../Common/Config.php'; $content = trim(file_get_contents("php://input")); $jsondecoded = json_decode($content, true); if (! empty($jsondecoded)) { require_once __DIR__ . "/../lib/StripeService.php"; $stripeService = new StripeService(); $email = filter_var($jsondecoded["email"], FILTER_SANITIZE_EMAIL); $name = filter_var($jsondecoded["name"], FILTER_SANITIZE_STRING); $address = filter_var($jsondecoded["address"], FILTER_SANITIZE_STRING); $country = filter_var($jsondecoded["country"], FILTER_SANITIZE_STRING); $postalCode = filter_var($jsondecoded["postalCode"], FILTER_SANITIZE_STRING); $notes = 'Stripe Apple Pay Payment'; $currency = filter_var($jsondecoded["currency"], FILTER_SANITIZE_STRING); $orderReferenceId = $stripeService->getToken(); $unitPrice = ($jsondecoded["unitPrice"] + $jsondecoded["shippingPrice"]); $orderStatus = "Pending"; $paymentType = "stripe"; $customerDetailsArray = array( "email" => $email, "name" => $name, "address" => $address, "country" => $country, "postalCode" => $postalCode ); $metaData = array( "email" => $email, "order_id" => $orderReferenceId ); require_once __DIR__ . '/../lib/StripePayment.php'; $stripePayment = new StripePayment(); $orderId = $stripePayment->insertOrder($orderReferenceId, $unitPrice, $currency, $orderStatus, $name, $email); $result = $stripeService->createPaymentIntent($orderReferenceId, $unitPrice, $currency, $email, $customerDetailsArray, $notes, $metaData); if (! empty($result) && $result["status"] == "error") { http_response_code(500); } $response = json_encode($result["response"]); echo $response; exit();
}

Stripe apple pay webhook endpoint

webhook-ep/capture-response.php


<?php
namespace Phppot; use Phppot\StriService; require_once __DIR__ . "/../lib/StripeService.php"; $stripeService = new StripeService(); $stripeService->captureResponse(); ?>

Stripe Service with request-response handlers

lib/StripeService.php


<?php
namespace Phppot; use Phppot\StripePayment;
use Stripe\Stripe;
use Stripe\WebhookEndpoint;
require_once __DIR__ . '/../vendor/autoload.php'; class StripeService
{ private $apiKey; private $webhookSecret; private $stripeService; function __construct() { require_once __DIR__ . '/../Common/Config.php'; $this->apiKey = Config::STRIPE_SECRET_KEY; $this->webhookSecret = Config::STRIPE_WEBHOOK_SECRET; $this->stripeService = new Stripe(); $this->stripeService->setVerifySslCerts(false); } public function createPaymentIntent($orderReferenceId, $amount, $currency, $email, $customerDetailsArray, $notes, $metaData) { try { $this->stripeService->setApiKey($this->apiKey); $paymentIntent = \Stripe\PaymentIntent::create([ 'description' => $notes, 'shipping' => [ 'name' => $customerDetailsArray["name"], 'address' => [ 'line1' => $customerDetailsArray["address"], 'postal_code' => $customerDetailsArray["postalCode"], 'country' => $customerDetailsArray["country"] ] ], 'amount' => $amount, 'currency' => $currency, 'payment_method_types' => [ 'card' ], 'metadata' => $metaData ]); $output = array( "status" => "success", "response" => array( 'orderHash' => $orderReferenceId, 'clientSecret' => $paymentIntent->client_secret ) ); } catch (\Error $e) { $output = array( "status" => "error", "response" => $e->getMessage() ); } return $output; } public function captureResponse() { $payload = @file_get_contents('php://input'); $sig_header = $_SERVER['HTTP_STRIPE_SIGNATURE']; $event = null; try { $event = \Stripe\Webhook::constructEvent($payload, $sig_header, $this->webhookSecret); } catch (\UnexpectedValueException $e) { // Invalid payload http_response_code(400); exit(); } catch (\Stripe\Exception\SignatureVerificationException $e) { // Invalid signature http_response_code(400); exit(); } if (! empty($event)) { $eventType = $event->type; $orderReferenceId = $event->data->object->metadata->order_id; $paymentIntentId = $event->data->object->id; $amount = $event->data->object->amount; require_once __DIR__ . '/../lib/StripePayment.php'; $stripePayment = new StripePayment(); if ($eventType == "payment_intent.payment_failed") { $orderStatus = 'Payement Failure'; $paymentStatus = 'Unpaid'; $amount = $amount / 100; $stripePayment->updateOrder($paymentIntentId, $orderReferenceId, $orderStatus, $paymentStatus); $stripePayment->insertPaymentLog($orderReferenceId, $payload); } if ($eventType == "payment_intent.succeeded") { /* * Json values assign to php variables * */ $orderStatus = 'Completed'; $paymentStatus = 'Paid'; $amount = $amount / 100; $stripePayment->updateOrder($paymentIntentId, $orderReferenceId, $orderStatus, $paymentStatus); $stripePayment->insertPaymentLog($orderReferenceId, $payload); http_response_code(200); } } }
}

Updating orders and payments in database

lib/StripePayment.php


<?php
namespace Phppot; use Phppot\DataSource; class StripePayment
{ private $ds; function __construct() { require_once __DIR__ . "/../lib/DataSource.php"; $this->ds = new DataSource(); } public function insertOrder($orderReferenceId, $unitAmount, $currency, $orderStatus, $name, $email) { $orderAt = date("Y-m-d H:i:s"); $insertQuery = "INSERT INTO tbl_order(order_reference_id, amount, currency, order_at, order_status, billing_name, billing_email) VALUES (?, ?, ?, ?, ?, ?, ?, ?) "; $paramValue = array( $orderReferenceId, $unitAmount, $currency, $orderAt, $orderStatus, $name, $email ); $paramType = "sdssssss"; $insertId = $this->ds->insert($insertQuery, $paramType, $paramValue); return $insertId; } public function updateOrder($paymentIntentId, $orderReferenceId, $orderStatus, $paymentStatus) { $query = "UPDATE tbl_order SET stripe_payment_intent_id = ?, order_status = ?, payment_status = ? WHERE order_reference_id = ?"; $paramValue = array( $paymentIntentId, $orderStatus, $paymentStatus, $orderReferenceId ); $paramType = "ssss"; $this->ds->execute($query, $paramType, $paramValue); } public function insertPaymentLog($orderReferenceId, $response) { $insertQuery = "INSERT INTO tbl_stripe_payment_log(order_id, stripe_payment_response) VALUES (?, ?) "; $paramValue = array( $orderReferenceId, $response ); $paramType = "ss"; $this->ds->insert($insertQuery, $paramType, $paramValue); }
}
?>

Stripe Apple Pay Output

The below screenshot shows the product tile with the Stripe Apple pay button. The details are dynamic from the web application config.

stripe apple pay integration

By clicking the Stripe Apple pay button in the above tile, the following payment dialog will pop up. It will have the option to proceed with payment by using the Apple touch id.

stripe apple pay form

Conclusion

Thus, we have integrated Stripe Apple pay in a web application using PHP. We used the Stripe Payment Request Button to display the Apple pay option in the UI.

We have seen the pre-requisites and configuration steps needed for this integration. I hope, the example code helps to understand the steps easily.
Download

↑ Back to Top

Posted on Leave a comment

How to use includes in JavaScript Array, String

by Vincy. Last modified on November 21st, 2021.

Coding in JavaScript is one of the critical skills required in building websites. Though mastering JavaScript is a journey to the center of the earth, continuous learning will help you make it.

We have seen some of the JavaScript functions like find(), forEach() earlier. Now, let’s learn about the function includes() in JavaScript.

Quick example


<script>
inputArray = ['Create', 'Read', 'Update', 'Delete', 'Filter'];
inputArray.includes('Read'); //returns true
inputArray.includes('Read','3'); //returns false
inputArray.includes('Error'); //returns false
inputArray.includes('Delete','-1'); //returns false inputString = 'How to learn JavaScript?';
inputString.includes('learn'); //returns true
inputString.includes('learn','8'); //returns false
</script> 

About JavaScript includes

It checks if an array or string includes a given value.

In an array context, it checks the given value is one among the array elements. In the string prototype, the includes() in JavaScript checks if the given value is the substring.

Syntax, parameters and return value


includes(searchElement, [fromIndex]); 

It has two parameters, searchElement and fromIndex. The fromIndex is optional and its default value is 0 to start with.

The fromIndex accepts signed numbers. With a negative value, it applies this formula to compute the position to start.

fromIndex = arrayLength + signedFromIndex

It returns boolean true if any match is found or false otherwise.

Note:

  • JavaScript includes() searches array or string with case sensitivity.
  • It can also be called as a generic method.
  • It works in most modern browsers.
  • The negative value is not applicable for the includes() in the String prototype.
  • The Array.prototype.includes() will not search for a sub-array.

include in javascript

Where to use JavaScript includes

The includes in JavaScript can be used for many scenarios. Some of them are listed below.

  1. To form a conditional code block based on the presence of the search element in an array or string.
  2. To highlight the keyword in the search result, if the includes in JavaScript returns true.
  3. To make the select, checkbox, radio options selected if the options found in the haystack.

Visit the linked article to know the other array prototype methods in JavaScript.

Examples for using includes in JavaScript

This article includes 4 examples to see how to use JavaScript includes(). Those are,

  1. To search array if a specified element exists or not.
  2. To use includes with a positive or negative fromIndex parameter.
  3. To use String.prototype.includes.
  4. To invoke includes() as a generic method.

Search array element using Includes in JavaScript

This example contains an array of 4 strings. It defines a custom function checkOption() to form a condition using includes().

This function receives a string and applies array.includes() on it. It returns Boolean true if the passed element is found on the array.

It prepares the output string based on the boolean value returned. It writes the log on the console to see the result of the program.

how-to-use-includes-in-javascript-array.php


<script> var optionArray = [ 'Create', 'Read', 'Update', 'Delete' ]; checkOption('Read'); checkOption('Filter'); function checkOption(keyword) { var isIncludes = optionArray.includes(keyword); if(!isIncludes) { console.log(keyword + ": not exists"); } else { console.log(keyword + ": exists"); } }
</script> 

Includes function with optional from-index parameter

It uses the optional fromIndex parameter while calling the includes() in JavaScript.

It supplies either positive or negative values in the second parameter. On getting a negative index, it computes the position from where it should start the search.

As passed -1 the computed position is 5, since arrayLength+negativeIndex = 6+(-1) = 5.

From the 5th position, it searches for ‘Pagination’ and returns true. When it searches for ‘Filter’ then it will return false.

javascript-includes-with-from-index.php


<script>
var optionArray = [ 'Create', 'Read', 'Update', 'Delete', 'Filter', 'Pagination' ]; console.log(optionArray.includes('Update', 2));
console.log(optionArray.includes('Update', 3));
console.log(optionArray.includes('Pagination', -1));
console.log(optionArray.includes('Filter',-1));
</script> 

JavaScript string includes

It’s for using String.prototype.includes() in Javascript. It assigns a long string to a variable and searches the passed keyword on it.

It also receives fromIndex position. A negative index will create no change. This program uses the fromIndex default value 0 and searches the string end to end.

check-string-includes-substring.php


<script>
var inputString = "How much wood would a woodchuck chuck if a woodchuck could chuck wood?";
var result = inputString.includes("woodchuck");
console.log(result);
</script> 

Invoke includes in JavaScript on array-like objects

JavaScript allows calling the includes() function as a generic method. In the above examples, the includes() is called with respect to this value representing an array or string context.

This example calls the includes in JavaScript on a functions’ argument list instead of an array.

how-to-call-includes-as-generic.php


<script>
(function() { console.log(Array.prototype.includes.call(arguments, 'Read', 1)); console.log(Array.prototype.includes.call(arguments, 'Read', -1));
})('Create', 'Read', 'Update', 'Delete') </script> 

Similar JavaScript methods like includes

There are more functions in JavaScript as like as the includes(). The below list shows some of those functions.

  • find() – applies condition on an array and returns the first element satisfying the condition.
  • findIndex() – as like as find() but returns index instead of the value.
  • indexOf() – returns index by element value.
  • lastIndexOf() – returns last index of an input element. It makes difference if the there are multiple occurances of the passed element.

Conclusion

We have seen about the includes in JavaScript end to end. The above article contains the basic idea about this function. It covers a beginner’s level introductory section and the usage mechanisms.

The examples will make it clear how to use includes in JavaScript. I hope the scenarios to use and the list of related functions gives relevancy to get the idea.

Download

↑ Back to Top

Posted on Leave a comment

PHP session time set unset and check existence

by Vincy. Last modified on November 21st, 2021.

PHP session is one of the methods for keeping data persistency on the server side.

PHP sessions have a deadline time limit for keeping data persistent. PHP configuration file includes directives to have this specification.

We can also create custom code to change the default PHP session deadline.

This article contains sections that describe the PHP sessions, their time-limit configurations. It provides examples for setting session limits and tracking existence.

The below example gives a quick solution to set PHP session time. It contains only two steps to set and track the session expiration status.

Quick example

1. Create a file set-session.php and set value and lifetime.


<?php
session_start();
//Set PHP session with value, time
$currentTime = time();
$_SESSION['color'] = array( "value" => "blue", "time" => $currentTime, "life_time" => 5
);
?>

2. Create a file check-session.php to compute if the session existence.


<?php
session_start();
if (isset($_SESSION['color'])) { $sessionSetTime = $_SESSION['color']['time']; $sessionLifeTime = $_SESSION['color']['life_time']; if ((time() - $sessionSetTime) > $sessionLifeTime) { unset($_SESSION['color']); print 'Session expired'; }
}
?>

About PHP session

We have already seen PHP sessions and cookies in a previous article. PHP sessions are for managing application data, state persistent during the working flow.

There are a lot of uses of sessions in an application. The below list shows some of the states or data managed by the use of sessions.

We have seen how to create a login script using the PHP session. In that, the session lifetime tracking can be used to log out after few minutes of inactivity.

php session

PHP session lifetime settings

This section describes the configuration directives used to set PHP session time. The below table shows two PHP.ini settings related to the session.

PHP directive Description
session.gc_maxlifetime It sets the max lifetime after which the session will be elapsed and collected as garbage.
session.cookie_lifetime It sets the time limit for the session cookie in seconds. Default is 0 which means to be persistent until the client quits. Note: PHP session_set_cookie_params() sets all the session cookie parameters in runtime.

The below PHP info highlights the session configuration settings. Refer to more runtime session configuration directives in the linked official site.

php session settings

Example: Working with PHP session time – Set expiration and limit lifetime

This PHP session time handling example is the enhanced version of the above quick example.

It creates three session variables to set color, shape and size. It sets the lifetime for each PHP session variable while setting values.

The PHP code checks if the session exists. Once the time is reached, it unset that particular session variable and destroys it.

php session time files

Landing page to set session

The landing page of this example shows a control to set the PHP session time. Once started, the session expiration status is checked at a periodic interval. This page includes the AJAX script to raise the call to PHP to check the session.

If the PHP session time is over, then this page will display a notice to the user. After all the sessions are expired, then the page will clear the notification and ask to reset the session.

index.php


<html>
<head>
<link href="./assets/css/style.css" rel="stylesheet" type="text/css" />
</head>
<body> <div class="session" data-status='<?php if(!empty($_GET["status"])) { echo $_GET["status"]; } ?>'> <div id="box"> <h1 align="center">Set PHP session time</h1> <div class="text"> <a href="set-session.php" class="btn">Reset Session</a> </div> <div id="status"></div> </div> <div id="message"></div> </div> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="./assets/js/session.js"></script>
</body>
</html> 

Check PHP session time via JavaScript AJAX

This script sets an interval to call the AJAX script to check the PHP session time. After getting the response, this AJAX success block shows the expired PHP sessions.

It checks the PHP session time every 5 seconds via AJAX. This script uses JavaScript setInterval() to invoke the checkSession() method.

session.js


if($('.session').data('status') != "") { var interval; interval=setInterval(checkSession, 5000); $("#status").text("Checking session expiration status...");
}
function checkSession(){ $.ajax({ url:"check-session.php", method:"POST", success:function(response){ if(response!=""){ if(response == -1){ $("#status").hide(); clearInterval(interval); window.location.href='index.php'; } else{ $("#message").append(response); } } } });
};

Set unset PHP session time

In this section, it shows two PHP files to set and unset the PHP session time.

The set-session.php is called on clicking the UI control on the landing page. It sets the color, shape and size in the PHP session.

Each session array is a multi-dimensional associative array. It has the details of PHP session set time, lifetime and value.

The session set-time and lifetime are used to calculate the session expiry.

set-session.php


<?php
if (! isset($_SESSION)) { session_start();
}
$currentTime = time();
$_SESSION['color'] = array( "value" => "blue", "time" => $currentTime, "lifetime" => 3
);
$_SESSION['shape'] = array( "value" => "circle", "time" => $currentTime, "lifetime" => 5
);
$_SESSION['size'] = array( "value" => "big", "time" => $currentTime, "lifetime" => 10
);
header("Location: index.php?status=starts");
exit();
?> 

This code returns the response text once the session is expired.

It validates the session expiry by comparing the remaining time and the PHP session lifetime.

Once all three sessions are expired, then this code returns -1. On receiving -1, the AJAX callback stops tracking by clearing the interval.

check-session.php


<?php
if (! isset($_SESSION)) { session_start();
} if (! isset($_SESSION['color']) && (! isset($_SESSION['shape'])) && (! isset($_SESSION['size']))) { print - 1;
}
if (isset($_SESSION['color'])) { $sessionTimeColor = $_SESSION['color']['time']; $sessionLifeTimeColor = $_SESSION['color']['lifetime']; if ((time() - $sessionTimeColor) > $sessionLifeTimeColor) { unset($_SESSION['color']); print '<div class="response-text"><span>Color Session Expired</span></div>'; } } if (isset($_SESSION['shape'])) { $sessionTimeShape = $_SESSION['shape']['time']; $sessionLifeTimeShape = $_SESSION['shape']['lifetime']; if ((time() - $sessionTimeShape) > $sessionLifeTimeShape) { unset($_SESSION['shape']); print '<div class="response-text"><span>Shape Session Expired</span></div>'; } } if (isset($_SESSION['size'])) { $sessionTimeSize = $_SESSION['size']['time']; $sessionLifeTimeSize = $_SESSION['size']['lifetime']; if ((time() - $sessionTimeSize) > $sessionLifeTimeSize) { unset($_SESSION['size']); print '<div class="response-text"><span>Size Session Expired</span></div>'; }
}
exit();
?> 

Conclusion

Thus we have learned how to set PHP session time via programming. This article described the PHP configurations to set max session lifetime.

I hope this example helped to create your own code to manage PHP sessions and time.
Download

↑ Back to Top

Posted on Leave a comment

Sendmail in PHP using mail(), SMTP with Phpmailer

by Vincy. Last modified on October 10th, 2021.

Sendmail in PHP is possible with just single line of code. PHP contains built-in mail functions to send mail.

There are reasons why I am feeling embraced with this PHP feature. Because I write lot of code for sending mails regularly. PHP really saves our time with its built-ins.

Quick Example


<?php
mail('recipient@domain.com', 'Mail Subject', 'Mail test content'); ?> 

In this tutorial, we will see how to add code to sendmail in PHP. We will see several examples in this to enrich the features with more support.

The below list examples we are going to see below. It will cover basic to full-fledged support to sendmail in PHP.

  1. Simple text mail with PHP mail().
  2. Send rich-text content via mail.
  3. Sendmail in PHP with attachments.
  4. Sendmail using PHPMailer with SMTP.

PHP mail()

The PHP mail() is to sendmail from an application. Let’s see the PHP configurations required to make the mail() function work. Also, we will see the common syntax and parameters of this PHP function below.

Syntax


mail( string $recipient_email, string $subject, string $message, array|string $headers = [], string $additional_params = ""
)

Parameters

$recipient_email
One or more comma-separated value that is the target mail addresses. The sample format of the values are,

  • name@domain.com
  • Name <name@domain.com>
  • name@domain.com, name2.domain.com
  • Name <name@domain.com>, Name2 <name2@domain.com>

$subject
Mail subject. It should satisfy RFC 2047.

$message
Mail content body. It uses \r\n for passing a multi-line text. It has a character limit of 70 for a line. It accepts various content types depends on the specification in the extra header.

$headers
This is an extra string or array append to the mail header. Use to pass the array of specifications like content-type, charset and more. It’s an optional parameter. It uses \r\n to append multiple headers. The header array contains key-value pair to specify header name and specification respectively.

$additional_params
This is also optional. It is to pass extra flags like envelope sender address with a command-line option.

Return Values

This function returns boolean true or false based on the sent status of the mail. By receiving boolean true that doesn’t mean the mail was sent successfully. Rather, it only represents that the mail sending request is submitted to the server.

PHP sendmail – configurations

We have to configure some directives to make the mail script work in your environment.

Locate your php.ini file and set the mail function attributes. The below image shows the PHP configuration of the mail function.

sendmail in php config

Set the mail server configuration and the sendmail path with this php.ini section. Then restart the webserver and ensure that the settings are enabled via phpinfo().

Examples to Sendmail in PHP

Sendmail in PHP to send plaintext content

This is a short example of sending plain text content via PHP Script. It sets the mail subject, message and recipient email parameter to sendemail in PHP.

This program print response text based on the boolean returned by the mail() function.

sendmail-with-plain-text.php


<?php
$to = 'recipient@email.com';
$subject = 'Mail sent from sendmail PHP script';
$message = 'Text content from sendmail code.';
// Sendmail in PHP using mail()
if (mail($to, $subject, $message,)) { echo 'Mail sent successfully.';
} else { echo 'Unable to send mail. Please try again.';
}
?>

PHP Sendmail code to send HTML content

Like the above example, this program also uses the PHP mail() function to send emails. It passes HTML content to the mail function.

For sending HTML content, it sets the content type and other header values with the mail header.

php-mail-with-html-content.php


<?php
$to = 'recipient@email.com'; $subject = 'Mail sent from sendmail PHP script'; $from = 'test@testmail.com';
$headers = "From: $from";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=UTF-8\r\n"; $message = '<p><strong>Sendmail in PHP with HTML content. </strong></p>'; if (mail($to, $subject, $message, $headers)) { echo 'Mail sent successfully.';
} else { echo 'Unable to send mail. Please try again.';
}
?>

Sendmail in PHP to attach files

This program attaches a text file with the email content. It reads a source file using PHP file_get_contents(). It encodes the file content and prepares a mail header to attach a file.

It sets content-type, encoding with the message body to make it work. This script uses the optional $header variable on executing sendmail in PHP.

sendmail-with-attachment.php


<?php
$file = "example.txt"; $to = 'recipient@email.com';
$subject = 'Mail sent from sendmail PHP script'; $content = file_get_contents($file);
$encodedContent = chunk_split(base64_encode($content)); $divider = md5(time()); $headers = "From: TestSupport <example@email.com>\r\n";
$headers .= "Content-Type: multipart/mixed; boundary=\"" . $divider . "\"\r\n";
$headers .= "Content-Transfer-Encoding: 7bit\r\n"; // prepare mail body with attachment
$message = "--" . $divider. "\r\n";
$message .= "Content-Type: application/octet-stream; name=\"" . $file . "\"\r\n";
$message .= "Content-Transfer-Encoding: base64\r\n";
$message .= "Content-Disposition: attachment\r\n";
$message .= $encodedContent. "\r\n";
$message .= "--" . $divider . "--"; //sendmail with attachment
if (mail($to, $subject, $message, $headers)) { echo 'Mail sent successfully.';
} else { echo 'Unable to send mail. Please try again.';
}
?>

sendmail in php to attach file

Sendmail on form submit

Instead of static values, we can also pass user-entered values to the PHP sendmail. An HTML form can get the values from the user to send mail. We have already seen how to send a contact email via the form.

This example shows a form that collects name, from-email and message from the user. It posts the form data to the PHP on the submit action.

The PHP reads the form data and uses them to prepare mail sending request parameters. It prepares the header with the ‘from’ email. It sets the mail body with the message entered by the user.

All the form fields are mandatory and the validation is done by the browser’s default feature.

sendmail-on-form-submit.php


<?php
if (isset($_POST["submit_btn"])) { $to = "recipient@email.com"; $subject = 'Mail sent from sendmail PHP script'; $from = $_POST["email"]; $message = $_POST["msg"]; $headers = "From: $from"; // Sendmail in PHP using mail() if (mail($to, $subject, $message, $headers)) { $responseText = 'Mail sent successfully.'; } else { $responseText = 'Unable to send mail. Please try again.'; }
}
?>
<html>
<head>
<style>
body { font-family: Arial; width: 550px;
} .response-ribbon { padding: 10px; background: #ccc; border: #bcbcbc 1px solid; margin-bottom: 15px; border-radius: 3px;
} input, textarea { padding: 8px; border: 1px solid #ccc; border-radius: 5px;
} #Submit-btn { background: #1363cc; color: #FFF; width: 150px;
} #email-form { border: 1px solid #ccc; padding: 20px;
} .response-ribbon { }
</style>
</head>
<body> <?php if(!empty($responseText)) { ?> <div class="response-ribbon"><?php echo $responseText; ?></div> <?php } ?> <form id="email-form" name="email-form" method="post" action=""> <table width="100%" border="0" align="center" cellpadding="4" cellspacing="1"> <tr> <td> <div class="label">Name:</div> <div class="field"> <input name="name" type="text" id="name" required> </div> </td> </tr> <tr> <td><div class="label">E-mail:</div> <div class="field"> <input name="email" type="text" id="email" required> </div></td> </tr> <tr> <td><div class="label">Message:</div> <div class="field"> <textarea name="msg" cols="45" rows="5" id="msg" required></textarea> </div></td> </tr> <tr> <td> <div class="field"> <input name="submit_btn" type="submit" id="submit-btn" value="Send Mail"> </div> </td> </tr> </table> </form>
</body>
</html> 

mail sending html form

PHP sendmail via SMTP

PHP mail() function has some limitation. To have a full-fledge functionality to sendmail in PHP, I prefer to use the PHPmailer library.

This library is one of the best that provides advanced mailing utilities. We have seen examples already to sendmail in PHP using PHPMailer via SMTP. If you are searching for the code to sendmail using OAuth token, the linked article has an example.

This example uses a minimal script to sendmail in PHP with PHPMailer via SMTP. It loads the PHPMailer library to create and set the mail object.

The mail object is used to configure the mail parameters. Then it invokes the send() method of the PHPMailer class to send mail.

Download PHPMailer from Github and put it into the vendor of this example directory. Replace the SMTP configurations in the below script to make this mail script working.

sendmail-in-php-via-smtp.php


<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception; require_once __DIR__ . '/vendor/phpmailer/phpmailer/src/Exception.php';
require_once __DIR__ . '/vendor/phpmailer/phpmailer/src/PHPMailer.php';
require_once __DIR__ . '/vendor/phpmailer/phpmailer/src/SMTP.php'; $mail = new PHPMailer(true);
$mail->SMTPDebug = 0;
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = "";
$mail->Password = "";
$mail->SMTPSecure = "ssl";
$mail->Port = 465; $mail->From = "test@testmail.com";
$mail->FromName = "Full Name"; $mail->addAddress("recipient@email.com", "recipient name"); $mail->isHTML(true); $mail->Subject = "Mail sent from php send mail script.";
$mail->Body = "<i>Text content from send mail.</i>";
$mail->AltBody = "This is the plain text version of the email content"; try { $mail->send(); echo "Message has been sent successfully";
} catch (Exception $e) { echo "Mailer Error: " . $mail->ErrorInfo;
}
?>

Related function to sendmail in PHP

The PHP provides alternate mail functions to sendmail. Those are listed below.

  • mb_send_mail() – It sends encoded mail based on the language configured with mb_language() setting.
  • imap_mail() – It allows to sendmail in PHP with correct handling of CC, BCC recipients.

Conclusion

The mail sending examples above provides code to sendemail in PHP. It supports sending various types of content, file attachments in the mail.

The elaboration on PHP in-built mail() function highlights the power of this function.

Hope this article will be helpful to learn more about how to sendmail in PHP.
Download

↑ Back to Top

Posted on Leave a comment

PHP Object to Array Convert using JSON Decode

by Vincy. Last modified on September 15th, 2021.

The PHP object to array conversion makes it easy to access data from the object bundle. Most of the API outputs object as a response.

Some APIs may return a complex object structure. For example, a mixture of objects and arrays bundled with a response. At that time, the object to array conversion process will simplify the data parsing.

This quick example performs a PHP object to array conversion in a single step. It creates an object bundle and sets the properties.

It uses JSON encode() decode() function for the conversion. The json_decode() supplies boolean true to get the array output.

Quick example

PHP object to array conversion in a line using json_decode


<?php
$object = new StdClass();
$object->id = 5678;
$object->name = "William";
$object->department = "CSE";
$object->designation = "Engineer"; $result = json_encode($object);
// converts object $result to array
$output = json_decode($result, true); print "<pre>";
print_r($result);
?>

Output

After decoding, the output array is printed to the browser. The below screenshot shows the output of this program.

php object to array

Different ways of converting a PHP object to array

When converting an object to array, the object property ‘name:value’ pairs will form an associative array.

If an object contains unassigned properties then it will return an array with numerical keys.

There are two ways to achieve a PHP object to array conversion.

  1. Typecasting object into an array.
  2. Encoding and decoding object properties into an array of elements.

Typecasting is a straightforward method to convert the type of input data. The second method applies json_decode() on the given object. It supplied boolean true as a second parameter to get the output in an array format.

This article includes examples of using both of the above methods to perform the object to array conversion.

PHP object to array using typecasting

This is an alternate method to convert an object type into an array. The below program uses the same input object.

It replaces the JSON encode decode via conversion with the typecasting statement. The output will be the same as we have seen above.

The PHP typecasting syntax is shown below. It prepends the target data type enclosed with parenthesis.


$output = (target-data-type) $input

type-casting-to-convert-object-to-array.php


<?php
$object = new StdClass();
$object->id = 5678;
$object->name = "William";
$object->department = "CSE";
$object->destination = "Engineer"; print"<pre>";
print_r( (array) $object );
?>

Recursive object to array conversion

This example uses an input object with depth = 3. It adds more properties at a nested level at different depths. The hierarchical object bundle is set as the input for the conversion process.

This program defines a custom function to convert a PHP object to array. It performs the conversion recursively on each level of the input object.

converting-recursive-object-to-array.php


<?php
$object = new StdClass();
$object->id = 5678;
$object->name = "William"; $object->address = new stdClass();
$object->address->email = "William@gmail.com"; $object->address->billing = new stdClass();
$object->address->billing->zipcode = 9950; $object->address->shipping = new stdClass();
$object->address->shipping->zipcode = 1234; $object->address->state = "South Carolina";
$object->address->city = "Columbia";
$object->address->country = "US"; function objectToArray($object)
{ foreach ($object as $k => $obj) { if (is_object($obj)) { $object->$k = objectToArray($obj); } else { $object->$k = $obj; } } return (array) $object;
} $result = objectToArray($object); print "<pre>";
print_r($result);
?>

This is the output of the recursive PHP object to the array conversion program above.

recursive object to array conversion

Convert PHP class object into array

This example constructs a PHP class object bundle. The class constructor sets the properties of the object during the instantiation.

Then, the Student class instance is encoded to prepare object type data. The json_encode() function prepares the JSON object to supply it for decoding. The json_decode() converts the PHP object to array.

convert-class-object-into-array.php


<?php
class student
{ public function __construct($id, $name, $state, $city, $country) { $this->id = $id; $this->name = $name; $this->state = $state; $this->city = $city; $this->country = $country; }
} $student = new student("5678", "William", "South Carolina", "Columbia", "US");
$result = json_encode($student);
$output = json_decode($result, true);
print "<pre>";
print_r($output);
?>

Check is_object() before conversion

It is good programming practice to check the data availability before processing. This example applies the is_object verification before converting a PHP object to an array.

This method verifies if the input is an object. PHP includes exclusive functions to verify data availability and its type. Example isset(), empty(), is_array() etc.

checking-object-before-conversion.php


<?php class student
{ public function __construct($id, $name, $state, $city, $country) { $this->id = $id; $this->name = $name; $this->state = $state; $this->city = $city; $this->country = $country; }
}
$student= new student("5678", "William", "South Carolina", "Columbia", "US"); print "<pre>";
if (is_object($student)) { echo "Input Object:" . '<br>'; $result = json_encode($student); print_r($result); $studentArray = json_decode($result, true);
} if(!empty($studentArray) && is_array($studentArray)) { echo "<br><br>Output Array:" . '<br>'; print_r($studentArray);
}
?>

Convert Private, Protected object of a class

The below program defines a class with private and protected properties. The PHP code instantiates the class and creates an object bundle.

It uses both the typecasting and decoding methods to convert the object into an array.

When using typecasting, the output array index of the private property contains the class name prefix. After conversion, the array index has a * prefix for the protected properties.

converting-private-protected-object.php


<?php
class Student
{ public $name; private $id; protected $email; public function __construct() { $this->name ="William"; $this->id = 5678; $this->email = "william@gmail.com"; }
} print "<pre>";
$student = new Student;
$result = json_encode($student);
$output1 = json_decode($result, true);
print "<br/>Using JSON decode:<br/>";
print_r($output1); $output2 = new Student;
print "<br/><br/>Using Type casting:<br/>";
print_r( (array) $output2 );
?>

This output screenshot shows the difference in the array index. Those are created from the private and protected properties of the class instance.

private protected properties

Accessing object properties with numeric keys

This code includes an associative array of student details. It also contains values with numeric keys.

When converting this array into an object, the associative array keys are used to access the object property values. There are exceptions to access properties if it doesn’t have a name.

The below code shows how to access objects with numeric keys. The key is enclosed by curly brackets to get the value.

problem-with-numerical-keys.php


<?php
$inputArray = array( 'name' => 'William', 'email' => 'William@gmail.com', 'phone' => '12345678', 'REG5678'
); $student = (object) array( 'name' => 'William', 'email' => 'William@gmail.com', 'phone' => '12345678', 'REG5678'
);
echo '<pre>' . print_r($student, true) . '</pre>';
echo '<br />' . $student->name;
echo '<br />' . $student->email;
echo '<br />' . $student->phone;
echo '<br />' . $student->{0};
?>

Conclusion

We have seen the different ways of converting a PHP object to an array. The basic PHP typecasting has achieved an object conversion except for few special cases.

The PHP JSON encode decode process made the conversion with one line code. It accepts class objects and converts their properties into an array list.

The custom function processes recursive object to array conversion. It is to handle complex objects with mixed objects or arrays as its child elements.
download

↑ Back to Top

Posted on Leave a comment

Python enumerate() — A Simple Illustrated Guide with Video

If you’re like me, you want to come to the heart of an issue fast. Here’s the 1-paragraph summary of the enumerate() function—that’s all you need to know to get started using it:

Python’s built-in enumerate(iterable) function allows you to loop over all elements in an iterable and their associated counters. Formally, it takes an iterable as an input argument and returns an iterable of tuples (i, x)—one per iterable element x. The first integer tuple value is the counter of the element x in the iterable, starting to count from 0. The second tuple value is a reference to the element x itself. For example, enumerate(['a', 'b', 'c']) returns an iterable (0, 'a'), (1, 'b'), (2, 'c'). You can modify the default start index of the counter by setting the optional second integer argument enumerate(iterable, start).

I’ve created a short visual guide into enumerate in the following graphic:

Python enumerate()

Usage Example

Learn by example! Here are some examples of how to use the enumerate() built-in function:

fruits = ['apple', 'banana', 'cherry']
for counter, value in enumerate(fruits): print(counter, value) # OUTPUT:
# 0 apple
# 1 banana
# 2 cherry

The enumerate(iterable, start) function takes an optional second argument that is the start value of the counter.

fruits = ['apple', 'banana', 'cherry']
for counter, value in enumerate(fruits, 42): print(counter, value) # OUTPUT:
# 42 apple
# 43 banana
# 44 cherry

You can use the enumerate function to create a list of tuples from an iterable where the first tuple value is the index of the element:

fruits = ['apple', 'banana', 'cherry']
fruits_with_indices = list(enumerate(fruits))
print(fruits_with_indices)
# [(0, 'apple'), (1, 'banana'), (2, 'cherry')]

Video enumerate()

Syntax enumerate()

Syntax: 
enumerate(iterable) -> loop over all elements in an iterable and their counters, starting from 0. 
enumerate(iterable, start) -> loop over all elements in an iterable and their counters, starting from start. 
Arguments iterable The iterable you want to enumerate.
start The start counter of the first element iterable[0].
Return Value enumerate object An iterable that allows you to iterate over each element associated to its counter, starting to count from start.

Interactive Shell Exercise: Understanding enumerate()

Consider the following interactive code:

Exercise: Change the start value of the enumerate function to your personal age and run the code. What’s the associated counter to the last fruit in the list?

Next, you’re going to dive deeper into the enumerate() function.


But before we move on, I’m excited to present you my brand-new Python book Python One-Liners (Amazon Link).

If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a single line of Python code. But it’s also an introduction to computer science, data science, machine learning, and algorithms. The universe in a single line of Python!

The book was released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco).

Link: https://nostarch.com/pythononeliners


What is the Return Value of Python’s enumerate() function?

The return value of enumerate(iterable) is an object of type enumerate. The enumerate class definition implements the iterable interface—the __next__() function—which means that you can iterate over it.

fruits = ['apple', 'banana', 'cherry']
print(type(enumerate(fruits)))
# <class 'enumerate'>

How is Python’s enumerate() Function Implemented?

The default implementation of enumerate() is done in C++, assuming you use cPython as your Python engine. However, the documentation shows an equivalent implementation of enumerate() in Python code that helps you understand how it works under the hood:

def enumerate(sequence, start=0): counter = start for element in sequence: yield counter, element counter += 1

You can see that the return value of enumerate() is not a list but a generator that issues the (counter, element) tuples as they appear in the sequence. Thus, the implementation is memory efficient—it doesn’t generate all (counter, element) pairs in advance and holds them in memory, but generates them as they’re needed.

How to Use enumerate() on Strings?

The enumerate(iterable) function takes an iterable as an input argument. A string is an iterable, so you can pass the string as an input. The return value of the function enumerate(string) will be an enumerate object that associates a counter to each character in the string for a series of tuples (counter, character). Here’s an example:

>>> list(enumerate('finxter'))
[(0, 'f'), (1, 'i'), (2, 'n'), (3, 'x'), (4, 't'), (5, 'e'), (6, 'r')]

You can also set the optional second argument start:

>>> list(enumerate('finxter', 42))
[(42, 'f'), (43, 'i'), (44, 'n'), (45, 'x'), (46, 't'), (47, 'e'), (48, 'r')]

How to Make Your Loop More Pythonic With enumerate()?

Beginner Python coders and coders coming from other programming languages such as Java or C++, often think in indices when creating loops such as this one:

# NON_PYTHONIC
fruits = ['apple', 'banana', 'cherry']
for i in range(len(fruits)): print(i, fruits[i])

The output of this correct, but unpythonic code is:

0 apple
1 banana
2 cherry

While the code does what it needs to do, it shouts into the world that its creator is not an experienced Python coder, but a newbie in Python. Why? Because an experienced Python coder will always prefer the enumerate() function due its more idiomatic and crisp functionality:

# PYTHONIC
fruits = ['apple', 'banana', 'cherry']
for i, fruit in enumerate(fruits): print(i, fruit)

You don’t have to use a single indexing mechanism—which reduces the likelihood of a bug and improves readability of your code.

Python enumerate() step

How to set a step in the indices used by the enumerate() function? For example, you may want to use only every third counter:

0 element_0
3 element_1
6 element_2

The answer is to multiply the returned counter value from a default call of the enumerate() function with the step size like this:

lst = ['element_0', 'element_1', 'element_2']
step = 3
for i, x in enumerate(lst): print(i*step, x)
OUTPUT:
0 element_0
3 element_1
6 element_2

Summary

Python’s built-in enumerate(iterable) function allows you to loop over all elements in an iterable and their associated counters.

Formally, it takes an iterable as an input argument and returns an iterable of tuples(i, x)—one per iterable element x.

  • The first integer tuple value is the counter of the element x in the iterable, starting to count from 0.
  • The second tuple value is a reference to the element x itself.

For example, enumerate(['a', 'b', 'c']) returns an iterable (0, 'a'), (1, 'b'), (2, 'c').

print(*enumerate(['a', 'b', 'c']))
# (0, 'a'), (1, 'b'), (2, 'c')

You can modify the default start index of the counter by setting the optional second integer argument enumerate(iterable, start).

print(*enumerate(['a', 'b', 'c'], 10))
# (10, 'a') (11, 'b') (12, 'c')

I hope you enjoyed the article! To improve your Python education, you may want to join the popular free Finxter Email Academy:

Do you want to boost your Python skills in a fun and easy-to-consume way? Consider the following resources and become a master coder!

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!

References:

The post Python enumerate() — A Simple Illustrated Guide with Video first appeared on Finxter.

Posted on Leave a comment

Python divmod() — A Simple Guide with Video

Python’s built-in divmod(a, b) function takes two integer or float numbers a and b as input arguments and returns a tuple (a // b, a % b). The first tuple value is the result of the integer division a//b. The second tuple is the result of the remainder, also called modulo operation a % b. In case of float inputs, divmod() still returns the division without remainder by rounding down to the next round number.

Python divmod() visual explanation

Usage

Learn by example! Here are some examples of how to use the divmod() built-in function with integer arguments:

# divmod() with integers
>>> divmod(10, 2)
(5, 0)
>>> divmod(10, 3)
(3, 1)
>>> divmod(10, 4)
(2, 2)
>>> divmod(10, 5)
(2, 0)
>>> divmod(10, 10)
(1, 0)

You can also use float arguments as follows:

# divmod() with floats
>>> divmod(10.0, 2.0)
(5.0, 0.0)
>>> divmod(10.0, 3.0)
(3.0, 1.0)
>>> divmod(10.0, 4.0)
(2.0, 2.0)
>>> divmod(10.0, 5.0)
(2.0, 0.0)
>>> divmod(10.0, 10.0)
(1.0, 0.0)

Video divmod()

Syntax divmod()

Syntax: 
divmod(a, b) -> returns a tuple of two numbers. The first is the result of the division without remainder a/b. The second is the remainder (modulo) a%b. 
Arguments integer The dividend of the division operation.
integer The divisor of the division operation.
Return Value tuple Returns a tuple of two numbers. The first is the result of the division without remainder. The second is the remainder (modulo).

Interactive Shell Exercise: Understanding divmod()

Consider the following interactive code:

Exercise: Guess the output before running the code.


But before we move on, I’m excited to present you my brand-new Python book Python One-Liners (Amazon Link).

If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a single line of Python code. But it’s also an introduction to computer science, data science, machine learning, and algorithms. The universe in a single line of Python!

The book is released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco).

Link: https://nostarch.com/pythononeliners


Exact Mathematical Definition divmod()

You can generally use the divmod(a, b) function with two integers, one integer and one float, or two floats.

Two integers. Say you call divmod(a, b) with two integers a and b. In this case, the exact mathematical definition of the return value is (a // b, a % b).

a = 5
b = 2
print((a // b, a % b))
print(divmod(a, b))
# OUTPUT:
# (2, 1)
# (2, 1)

One integer and one float. Say you call divmod(a, b) with an integer a and a float b. In this case, the exact mathematical definition of the return value is the return value of converting the integer to a float and calling divmod(a, float(b)).

a = 5.0
b = 2
print((a // b, a % b))
print(divmod(a, b))
# OUTPUT:
# (2.0, 1.0)
# (2.0, 1.0)

Two floats. Say you call divmod(a, b) with two floats a and b. In this case, the exact mathematical definition of the return value is (float(math.floor(a / b)), a % b).

import math a = 5.0
b = 2.0
print((float(math.floor(a / b)), a % b))
print(divmod(a, b))
# OUTPUT:
# (2.0, 1.0)
# (2.0, 1.0)

Note that because of the imprecision of floating point arithmetic, the result may have a small floating point error in one of the lower decimal positions. You can read more about the floating point trap on the Finxter blog.

Related Tutorial: Floating Point Error Explained

Python divmod() Negative Numbers

Can you use the divmod() method on negative numbers for the dividend or the divisor?

You can use divmod(a, b) for negative input arguments a, b, or both. In any case, if both arguments are integers, Python performs integer division a // b to obtain the first element and modulo division a % b to obtain the second element of the returned tuple. Both operations allow negative inputs a or b. The returned tuple (x, y) is calculated so that x * b + y = a.

Here’s an example of all three cases:

>>> divmod(-10, -3)
(3, -1)
>>> divmod(-10, 3)
(-4, 2)
>>> divmod(10, -3)
(-4, -2)

Python divmod() Performance — Is It Faster Than Integer Division // and Modulo % Operators?

There are two semantically identical ways to create a tuple where the first element is the result of the integer division and the second is the result of the modulo operation:

  • Use the divmod(a, b) function.
  • Use the (a // b, a % b) explicit operation with Python built-in operators.

Next, we measure the performance of calculating the elapsed runtime in milliseconds when performing 10 million computations for relatively small integers. Let’s start with divmod():

import time
import random # Small Operands
operands = zip([random.randint(1, 100) for i in range(10**7)], [random.randint(1, 100) for i in range(10**7)]) start = time.time() for i, j in operands: divmod(i, j) stop = time.time()
print('divmod() elapsed time: ', (stop-start), 'milliseconds')
# divmod() elapsed time: 1.7654337882995605 milliseconds

Compare this to integer division and modulo:

import time
import random # Small Operands
operands = zip([random.randint(1, 100) for i in range(10**7)], [random.randint(1, 100) for i in range(10**7)]) start = time.time() for i, j in operands: (i // j, i % j) stop = time.time()
print('(i // j, i % j) elapsed time: ', (stop-start), 'milliseconds')
# (i // j, i % j) elapsed time: 1.9048900604248047 milliseconds

The result of this performance benchmark is that divmod() requires 1.76 milliseconds and the explicit way of using integer division and modulo requires 1.90 milliseconds for 10,000,000 operations. Thus, divmod() is 8% faster. The reason is that the explicit way performs many duplicate operations to calculate the result of the integer division and the modulo operation which internally uses integer division again. This effect becomes even more pronounced if you use larger integers.

Performance difference divmod() vs Integer Division and Modulo

Python divmod() Implementation

For integer input arguments, here’s a semantically equivalent divmod() implementation:

>>> def divmod_own(x, y): return (x // y, x % y) >>> divmod_own(10, 3)
(3, 1)
>>> divmod(10, 3)
(3, 1)

But note that this implementation still performs redundant computations (e.g., integer division) and, therefore, is less efficient than divmod().

Summary

Python’s built-in divmod(a, b) function takes two integer or float numbers a and b as input arguments and returns a tuple (a // b, a % b).

In case of float inputs, divmod() still returns the division without remainder by rounding down to the next round number.


I hope you enjoyed the article! To improve your Python education, you may want to join the popular free Finxter Email Academy:

Do you want to boost your Python skills in a fun and easy-to-consume way? Consider the following resources and become a master coder!

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!

The post Python divmod() — A Simple Guide with Video first appeared on Finxter.

Posted on Leave a comment

How to Get Started With Python Dash on PyCharm [Absolute Beginners]

This is a chapter draft for our upcoming book “Python Dash” with NoStarch—to appear in 2021. Stay tuned!

Why an IDE

Using an integrated development environment (IDE) has the potential to significantly accelerate your programming productivity. Many programmers do not unlock their full potential until they finally decide to switch from a simple code editor to an IDE—and mastering the advanced functionality provided by the IDE. Some advantages of IDEs over simple text editors are code highlighting, tooltips, syntax checker, code linters that check for style issues, version control to safeguard the history of programming edits, debugging with the help of breakpoints, visual aids such as flowcharts and block diagrams, performance optimization tools and profilers—just to name a few.

PyCharm for Dash Apps

In this book about dashboard applications, we recommend that you also take your time to switch to an IDE, if you haven’t already. In particular, we recommend that you use the PyCharm IDE to follow along with the provided code examples. Apart from the benefits of using IDEs, you’ll also develop web applications that can quickly grow by adding more and more features. As your Python dashboard applications grow, so will your need to aggregate all source code at a single spot and in a single development environment. Increasing complexity quickly demands the use of an IDE.

In the following, we’ll describe how to download and install PyCharm, and create your first simple dashboard application that you can view in your browser. After you’ve completed those steps, you’re well-prepared to duplicate the increasingly advanced applications in the upcoming chapters.

Download PyCharm

First, let’s start with downloading the latest PyCharm version. We assume you have a Windows PC, but the steps are very similar on a macOS and Linux computer. As soon as you’ve launched the PyCharm application, the similarity of usage increases even more across the different operating systems.

You can download the PyCharm app from the official website.

Click the download button of the free community version and wait for the download to complete.

Install PyCharm on Your Computer

Now, run the executable installer and follow the steps of the installation application. A sensible approach is to accept the default settings suggested by the PyCharm installer.

Congratulations, you’ve installed PyCharm on your system!

Open PyCharm

Now type “PyCharm” into the search bar of your operating system and run the IDE!

Create a New Dash Project in PyCharm

After choosing “New Project”, you should see a window similar to this one:

This user interface asks you to provide a project name, a virtual environment, and a Python interpreter. We call our project firstDashProject, use a virtual environment with the standard Python installation, and don’t create a main.py welcome script:

Create the project and you should see your first PyCharm dashboard project!

Create Your Dash File app.py in Your PyCharm Project

Let’s create a new file app.py in your project and copy&paste the code from the official documentation into your app.py file:

# -*- coding: utf-8 -*- # Run this app with `python app.py` and
# visit http://127.0.0.1:8050/ in your web browser. import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.express as px
import pandas as pd external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] app = dash.Dash(__name__, external_stylesheets=external_stylesheets) # assume you have a "long-form" data frame
# see https://plotly.com/python/px-arguments/ for more options
df = pd.DataFrame({ "Fruit": ["Apples", "Oranges", "Bananas", "Apples", "Oranges", "Bananas"], "Amount": [4, 1, 2, 2, 4, 5], "City": ["SF", "SF", "SF", "Montreal", "Montreal", "Montreal"]
}) fig = px.bar(df, x="Fruit", y="Amount", color="City", barmode="group") app.layout = html.Div(children=[ html.H1(children='Hello Dash'), html.Div(children=''' Dash: A web application framework for Python. '''), dcc.Graph( id='example-graph', figure=fig )
]) if __name__ == '__main__': app.run_server(debug=True)

You can get the code from the official Dash tutorial: https://dash.plotly.com/layout

Your PyCharm dashboard project should now look like this:

Debug Your Dash App Using PyCharm’s Tooltips

Now, let’s try to run our project by using the top menu and select Run > app.py. Unfortunately, it doesn’t already work—PyCharm doesn’t recognize dash!

You can easily fix this by hovering over the red underlined “dash” library import in your app and choosing the “install package dash” option.

This is one great advantage of an IDE is that installing dependencies in your Python projects is as simple as accepting the tooltips provided by your intelligent development environment.

Install Dash in Your Virtual Environment

Installing the dash library will take a few moments. Note that the library will be installed only in a virtual environment which means that it’ll install it not on your global operating system but only on a project level. For a different project, you may have to install dash again. While this may sound tedious, it’s actually the most Pythonic way because it keeps dependency management simple and decentralized. There won’t be any version issues because your first project needs version 1 and your second project needs version 2 of a given library. Instead, each project installs exactly the version it needs.

Install Pandas in Your Virtual Environment

PyCharm will tell you when it is done with installing the dash library in the virtual environment. Now repeat the same procedure for all red-underlined libraries in the project. If you used the code given above, you’ll have to install the pandas library (see Chapter 3) as well in your local environment. A few moments later, the pandas installation will also successfully complete. The red underlined error messages in your code will disappear and you’re ready to restart the project again by clicking “Run”.

Exploring Your First Dash App in Your Browser

On my machine, the output after running the app.py file in PyCharm is:

C:\Users\xcent\Desktop\Python\firstDashProject\venv\Scripts\python.exe C:/Users/xcent/Desktop/Python/firstDashProject/app.py
Dash is running on http://127.0.0.1:8050/ * Serving Flask app "app" (lazy loading) * Environment: production WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Debug mode: on

Note the highlighted line (in bold). You can now copy the URL http://127.0.0.1:8050/ and paste it into your browser—the dashboard app runs on a local server that is hosted on your machine with IP address 127.0.0.1 and port 8050.  

When you visit this URL in your browser, you should see your first Dash application!

Congratulations, you’re now well-prepared to run all dashboard apps in this book—and beyond it as well—using similar steps. For further reading on PyCharm, feel free to check out our multi-site blog tutorial on https://academy.finxter.com/course/introduction-to-pycharm/

The post How to Get Started With Python Dash on PyCharm [Absolute Beginners] first appeared on Finxter.