Author

Ankit Kumar

Browsing

Hi, If you are looking for the PHP script to learn how to send email with attachment in PHP without going to spam then you are in the right place. I know you searched a lot on Google to find source code but every code sends that to spam, not in the inbox. Check our demo to confirm.

Here I am going to give a PHP script by which your email with an attachment will always go to inbox. Sending an email with attachment is the most common task in web development.

When you are applying for a job or submitting any application, you often might be noticed that they accept a file to upload. It may be anything like your CV or resume, profile picture or any other document.

Sending details to email is sometimes good in terms of saving space on our server. Since we are not storing the details on our database or attachment to our server folders.

How to do that?

Here we will use a simple HTML form accepting basic details like name, email, subject, message, and an attachment. The attachment has a validation that only PDF, DOC, JPG, JPEG, & PNG files are allowed to upload. In the previous tutorial, we learned about how to send email in PHP step by step but here we will do the same with attachment.

So what are we waiting for? Let’s start. Check the files and folder we are going to create.

how-to-send-email-with-attachment-in-php-coding-birds-online-file-and-folders
  • index.php is the main file which is a simple HTML form as I told above.
  • email-script.php is the script file that sends an email with an attachment.
  • validation-script.js is a javaScript validation file.
  • uploads folder saves the attachment to send emails and deletes later.

Now we should create these files. I am giving you just code block here. Make sure you put these CDN in to head off your index.php to work your code.

   <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

And include this javaScript validation file also before closing to the body tag.

<script src="validation-script.js"></script>

index.php

    <div class="container">
        <div class="row">
            <div class="col-lg-8 posts-list">
                <div class="card card-signin my-5">
                    <div class="card-body">
                        <center><img src="../website/img/coding-birds-online/coding-birds-online-favicon.png" width="70"></center>
                        <h5 class="card-title text-center">Send email with attachment in PHP</h5>
                        <form method="post" action="email-script.php" enctype="multipart/form-data" id="emailForm">
                            <div class="form-group">
                                <input type="text" name="name" id="name" class="form-control" placeholder="Name" >
                                <div id="nameError" style="color: red;font-size: 14px;display: none">nameError</div>
                            </div>
                            <div class="form-group">
                                <input type="email" name="email" id="email" class="form-control" placeholder="Email address" >
                                <div id="emailError" style="color: red;font-size: 14px;display: none">emailError</div>
                            </div>
                            <div class="form-group">
                                <input type="text" name="subject" id="subject" class="form-control"  placeholder="Subject" >
                                <div id="subjectError" style="color: red;font-size: 14px;display: none">subjectError</div>
                            </div>
                            <div class="form-group">
                                <textarea name="message" id="message" class="form-control" placeholder="Write your message here"></textarea>
                                <div id="messageError" style="color: red;font-size: 14px;display: none">messageError</div>
                            </div>
                            <div class="form-group">
                                <input type="file" name="attachment" id="attachment" class="form-control">
                                <div id="attachmentError" style="color: red;font-size: 14px;display: none">attachmentError</div>
                            </div>
                            <div class="submit">
                                <input type="submit" name="submit" onclick="return validateEmailSendForm();" class="btn btn-success" value="SUBMIT">
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

If you notice this form uses an action to email-script.php this file. Create this file also.

email-script.php

<?php

if(isset($_POST['submit'])){
    // Get the submitted form data
    $email = $_POST['email'];
    $name = $_POST['name'];
    $subject = $_POST['subject'];
    $message = $_POST['message'];
    $uploadStatus = 1;

    // Upload attachment file
    if(!empty($_FILES["attachment"]["name"])){

        // File path config
        $targetDir = "uploads/";
        $fileName = basename($_FILES["attachment"]["name"]);
        $targetFilePath = $targetDir . $fileName;
        $fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);

        // Allow certain file formats
        $allowTypes = array('pdf', 'doc', 'docx', 'jpg', 'png', 'jpeg');
        if(in_array($fileType, $allowTypes)){
            // Upload file to the server
            if(move_uploaded_file($_FILES["attachment"]["tmp_name"], $targetFilePath)){
                $uploadedFile = $targetFilePath;
            }else{
                $uploadStatus = 0;
                $statusMsg = "Sorry, there was an error uploading your file.";
            }
        }else{
            $uploadStatus = 0;
            $statusMsg = 'Sorry, only PDF, DOC, JPG, JPEG, & PNG files are allowed to upload.';
        }
    }

    if($uploadStatus == 1){
        // Recipient
        $toEmail = $email;
        // Sender
        $from = 'info@codingbirdsonline.com';
        $fromName = 'Coding Birds Online';
        // Subject
        $emailSubject = 'Email attachment request Submitted by '.$name;
        // Message
        $htmlContent = '<h2>Contact Request Submitted</h2>
                <p><b>Name:</b> '.$name.'</p>
                <p><b>Email:</b> '.$email.'</p>
                <p><b>Subject:</b> '.$subject.'</p>
                <p><b>Message:</b><br/>'.$message.'</p>';

        // Header for sender info
        $headers = "From: $fromName"." <".$from.">";

        if(!empty($uploadedFile) && file_exists($uploadedFile)){
            // Boundary
            $semi_rand = md5(time());
            $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
            // Headers for attachment
            $headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";
            // Multipart boundary
            $message = "--{$mime_boundary}\n" . "Content-Type: text/html; charset=\"UTF-8\"\n" .
                "Content-Transfer-Encoding: 7bit\n\n" . $htmlContent . "\n\n";
            // Preparing attachment
            if(is_file($uploadedFile)){
                $message .= "--{$mime_boundary}\n";
                $fp =    @fopen($uploadedFile,"rb");
                $data =  @fread($fp,filesize($uploadedFile));
                @fclose($fp);
                $data = chunk_split(base64_encode($data));
                $message .= "Content-Type: application/octet-stream; name=\"".basename($uploadedFile)."\"\n" .
                    "Content-Description: ".basename($uploadedFile)."\n" .
                    "Content-Disposition: attachment;\n" . " filename=\"".basename($uploadedFile)."\"; size=".filesize($uploadedFile).";\n" .
                    "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
            }

            $message .= "--{$mime_boundary}--";
            $returnpath = "-f" . $email;
            // Send email
            $mail = mail($toEmail, $emailSubject, $message, $headers, $returnpath);
            // Delete attachment file from the server
            @unlink($uploadedFile);
        }else{
            // Set content-type header for sending HTML email
            $headers .= "\r\n". "MIME-Version: 1.0";
            $headers .= "\r\n". "Content-type:text/html;charset=UTF-8";
            // Send email
            $mail = mail($toEmail, $emailSubject, $htmlContent, $headers);
        }

        // If mail sent
        if($mail){
            $statusMsg = 'Your email attachment request has been submitted successfully !';
        }else{
            $statusMsg = 'Your request submission failed, please try again.';
        }
    }
    echo '<script>alert("'.$statusMsg.'");window.location.href="./";</script>';
}
?>

validation-script.js

function validateEmailSendForm() {
   var name = $("#name").val();
   var email = $("#email").val();
   var subject = $("#subject").val();
   var message = $("#message").val();
   var attachment = $("#attachment").val();

   if (name == ""){
       $("#nameError").show();
       $("#nameError").html("Please enter your name");
       $("#nameError").fadeOut(4000);
       $("#name").focus();
       return false;
   }else  if (email == ""){
       $("#emailError").show();
       $("#emailError").html("Please enter your email");
       $("#emailError").fadeOut(4000);
       $("#email").focus();
       return false;
   }else  if (!validateEmail(email)){
       $("#emailError").show();
       $("#emailError").html("Please enter valid email");
       $("#emailError").fadeOut(4000);
       $("#email").focus();
       return false;
   }else  if (subject == ""){
       $("#subjectError").show();
       $("#subjectError").html("Please enter subject");
       $("#subjectError").fadeOut(4000);
       $("#subject").focus();
       return false;
   }else if (message == ""){
       $("#messageError").show();
       $("#messageError").html("Please enter some message");
       $("#messageError").fadeOut(4000);
       $("#message").focus();
       return false;
   }else if (attachment == ""){
       $("#attachmentError").show();
       $("#attachmentError").html("Please select a attachment");
       $("#attachmentError").fadeOut(4000);
       $("#attachment").focus();
       return false;
   }else{
       return true;
   }

    function validateEmail(inputText) {
        var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
        if(inputText.match(mailformat)) {
            return true;
        } else{
            return false;
        }
    }
}

Run the code!

Now it is time to run and test our code. If you did everything step by step then you will not face any errors and you will get output something like this.

how-to-send-email-with-attachment-in-php-coding-birds-online-output

This form is validated properly like empty fields, valid email and attachment file accepted. When you fill that form and hit the submit button then you will get the alert message of success or errors.

Check this also How to make a dynamic pie chart in PHP in 2 steps.

Attention !!! It may take 1 or 2 minutes to receive email with attachment so please have patience. But I am sure you will receive in primary inbox not to spam.

how-to-send-email-with-attachment-in-php-coding-birds-online-email-sent-output2
how-to-send-email-with-attachment-in-php-coding-birds-online-email-sent-output3

Source Code & Demo

You can download the full 100% working source code from here. You check this demo also.

Conclusion

I hope you learned explained above, If you have any suggestions, are appreciated. And if you have any errors comment here. You can download the full 100% working source code from here.

Ok, Thanks for reading this article, see you in the next post.

Happy Coding 🙂

Making users active inactive is the most important and common feature in web applications and websites. In this tutorial, we are going to learn how to make active inactive users in PHP using jQuery AJAX without page refresh. You check this demo also. You can implement the same code with CodeIgniter as CI follows the MVC pattern.

Why we need it?

Suppose you have a web application in which employees doing registration and then after login and performs their tasks. Now if any user is doing some inappropriate activities then you disable his login account.

consider this example as you have a list of users or employees and you want to disable his account so that he failed to login. To do this just need to press a thumb down button and his status in the database table will be 0. And In the login query, you make check the only those people can log in to the system whose status is 1.

Check these posts also

So what are you waiting for? let’s get started. Check these files and folder structure.

active-inactive-users-in-php-using-jquery-ajax-coding-birds-online-file-and-folder-structure
  • index.php is the main file on which everything is to be performed
  • script.php is a logic file contains the code to perform active inactive operations
  • script.php uses the config.php is the connection file to the database
  • active-inactive-script.js is the javaScript file in which we wrote AJAX to avoid page refresh
  • bird_active_inactive_users.sql is the SQL file which is a database table which the following structure.
active-inactive-users-in-php-using-jquery-ajax-coding-birds-online-table-structure

Don’t worry I will provide the full 100% working source code so that you can download it and implement it to your machine. Let’s create these files. Make sure you use bootstrap and jQuery. Bootstrap is just for styling and optional but jQuery is mandatory since we are making AJAX request.

   <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

And include this custom javaScript AJAX request file to the just below to jQuery. Here I am using version 3.4 of jQuery CDN. Here we are using javaScript and jQuery to enhance user experience.

You can learn more about JavaScript functions from this amazing article.

<script src="active-inactive-script.js"></script>

index.php

    <div class="container">
        <div class="row">
            <div class="col-lg-8 posts-list">
                <div class="card card-signin my-5">
                    <div class="card-body">
                        <center><img src="../website/img/coding-birds-online/coding-birds-online-favicon.png" width="70"></center>
                        <h5 class="card-title text-center">Active Inactive users in PHP</h5>
                    </div>
                    <table id="exampleTable" class="table table-bordered" style="width: 100%">
                        <thead id="thead">
                        <tr style="background-color: #1573ff">
                            <th>Sr.No</th>
                            <th>Name</th>
                            <th>Email</th>
                            <th>Contact</th>
                            <th>Action</th>
                        </tr>
                        </thead>
                        <tbody id="tableBodyData">
                        </tbody>
                    </table>
                    </div>
            </div>
        </div>
   </div>

active-inactive-script.js

$(document).ready(function () {
   $.post("script.php",{key:"getAllUsers"},function (response) {
        $("#tableBodyData").html(response);
   })
});

function activeInactive(recordId,status) {
    var message = ((status == 0?" inactive ":" Active "));
    if (confirm("Are you sure to"+ message+ "the user")){
        $.post("script.php",{key:"activeInactive",status:status,recordId:recordId},function (response) {
            if (response == "success"){
                if (status == 0){
                    $('#activeBtn'+recordId).show();
                    $('#inactiveBtn'+recordId).hide();
                }else if (status == 1){
                    $('#inactiveBtn'+recordId).show();
                    $('#activeBtn'+recordId).hide();
                }
                alert("User is "+ message +"now");
            }
        });
    }
}

script.php

<?php
include "config.php";
if ($_POST['key'] == "getAllUsers") {
    $tableData = '';
    $sr = 1;
    $query = "SELECT * FROM bird_active_inactive_users";
    $result = $connection->query($query);
    if ($result->num_rows>0){
        while ($row = $result->fetch_object()){
            $buttonActive = (($row->status == 0)?'block':'none');
            $buttonInActive = (($row->status == 1)?'block':'none');
            $tableData .='<tr>
                <td>'.$sr.'</td>
                <td>'.$row->name.'</td>
                <td>'.$row->email.'</td>
                <td>'.$row->contact.'</td>
                <td><a href="javaScript:void(0)" title="Active" style="display:'.$buttonActive.'" id="activeBtn'.$row->id.'" onclick="activeInactive(\''.$row->id.'\',1);" class="btn btn-success btn-sm"> <i class="fa fa-thumbs-up"></i></a>
                <a href="javaScript:void(0)" title="In active" style="display:'.$buttonInActive.'" id="inactiveBtn'.$row->id.'" onclick="activeInactive(\''.$row->id.'\',0);" class="btn btn-danger btn-sm"> <i class="fa fa-thumbs-down"></i></a> </td>
            </tr>';
            $sr++;
        }
    }
    echo $tableData;
}

if ($_POST['key'] == "activeInactive"){
    $status = $_POST['status'];
    $recordId = $_POST['recordId'];
    $query = "UPDATE bird_active_inactive_users SET status='$status' WHERE id='$recordId'";
    $result = $connection->query($query);
    if ($result){
        echo "success";
    }
}

config.php

<?php
$connection = new mysqli("localhost","root","","codingbirds");
if (! $connection){
    die("Error in connection".$connection->connect_error);
}

Run the Code!

If you followed the steps and you are confident that everything is fine then its time to check the code. Then you will get the output something like this. Create the table and have some data otherwise you will get blank or you can import the same table as I will provide the source code.

active-inactive-users-in-php-using-jquery-ajax-coding-birds-online-output

The red button is to inactive the user and green is to make the user active. Here I haven’t created a login system. This tutorial is to demonstrate how to make active inactive users in PHP using jQuery AJAX.

Source Code & Demo

You can download the full 100% working source code from here. You check this demo also.

Conclusion

I hope you learned explained above, If you have any suggestions, are appreciated. And if you have any errors comment here. You can download the full 100% working source code from here.

Ok, Thanks for reading this article, see you in the next post.

Happy Coding 🙂

To hide email addresses or contact numbers partially is the most common thing in web application development. If you might have noticed on so many websites when you register by using your email id or contact number, then they shoot a verification code on your email or phone.

And you can’t see the full email address or contact. They make it partially hidden by using some stars *. You can check this demo also.

So If you are looking to do the same thing on PHP and looking for how to partially hide email address in PHP using AJAX then you are in the right place.

Check this post also on how to clone a specific folder from a git repository.

How to do?

Here I will use a simple form accepting email id. When you press the submit button you will get a partially hidden email without page refresh.

To do this I will use AJAX functionality so that we can achieve this without page refresh. So without wasting time lets make out hands dirty with code.

  • Create index.php file is the main file
  • Now create script.php file is the logic file to hide email address partially.

index.php

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="icon" href="https://codingbirdsonline.com/wp-content/uploads/2019/12/cropped-coding-birds-favicon-2-1-192x192.png" type="image/x-icon">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <title>How to partially hide email address in PHP using AJAX - Coding Birds Online</title>
    <style>.required{color: #FF0000;}</style>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-sm-9 col-md-7 col-lg-5 mx-auto">
            <div class="card card-signin my-5">
                <div class="card-body">
                    <center><img width="50" src="https://codingbirdsonline.com/wp-content/uploads/2019/12/cropped-coding-birds-favicon-2-1-192x192.png"></center>
                    <h5 class="card-title text-center">Partially hide email address in php </h5>
                    <form id="myForm">
                        <div class="form-label-group">
                            <label for="inputEmail">Email <span class="required">*</span></label>
                            <input type="text" name="email" id="email" class="form-control" placeholder="Enter email ">
                        </div><br/>
                        <div id="partiallyHiddenEmail"></div><br/>
                        <button type="submit" name="submitBtn" id="submitBtn" class="btn btn-md btn-primary btn-block text-uppercase" >Hide</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<script type="text/javascript">
   $("form#myForm").on("submit",function (e) {
       e.preventDefault();
      var email = $("#email").val();
      if (email == ""){
          alert("Please enter email");
          $("#email").focus();
      }else if (!validateEmail(email)){
          alert("Please enter valid email");
          $("#email").focus();
      } else {
          $.post("script.php",{key:"hideEmailAddress",email:email},function (response) {
            $("#partiallyHiddenEmail").html(response);
          });
      }
   });

   function validateEmail(inputText) {
       var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
       if(inputText.match(mailformat)) {
           return true;
       } else{
           return false;
       }
   }
</script>
</body>
</html>

This file uses the AJAX call, which in turn calls the script.php file.

script.php

<?php

if ($_POST['key'] == "hideEmailAddress"){
    $email = $_POST['email'];
    $partiallyHiddenEmail = mask_email($email);
    echo $partiallyHiddenEmail;

}

/*
Here's the logic:

We want to show X numbers.
If length of STR is less than X, hide all.
Else replace the rest with *.

*/

function mask_email($email) {
    $mail_parts = explode("@", $email);
    $domain_parts = explode('.', $mail_parts[1]);

    $mail_parts[0] = mask($mail_parts[0], 2, 1); // show first 2 letters and last 1 letter
    $domain_parts[0] = mask($domain_parts[0], 2, 1); // same here
    $mail_parts[1] = implode('.', $domain_parts);

    return implode("@", $mail_parts);
}

function mask($str, $first, $last) {
    $len = strlen($str);
    $toShow = $first + $last;
    return substr($str, 0, $len <= $toShow ? 0 : $first).str_repeat("*", $len - ($len <= $toShow ? 0 : $toShow)).substr($str, $len - $last, $len <= $toShow ? 0 : $last);
}

Run the Code!

When you run the code you will get something like this. if you get any errors, don’t worry I will provide the full 100% working source code.

how-to-partially-hide-email-address-in-php-using-ajax-coding-birds-online-output-1

If you enter the email address cs.ankitprajapati@gmail.com, Of course, you can enter your own. You will get the following output.

how-to-partially-hide-email-address-in-php-using-ajax-coding-birds-online-output-2

Source Code & Demo

You can download the full 100% working source code from here. You check this demo also.

Conclusion

I hope you learned explained above, If you have any suggestions, are appreciated. And if you have any errors comment here. You can download the full 100% working source code from here.

Ok, Thanks for reading this article, see you in the next post.

Happy Coding 🙂

If you are looking to learn how to create CRUD application in PHP then you are in the right place. In a web application, 4 operations are mainly performed, Create, Read, Update and Delete. These are called CRUD operations in short.

  • Create – This is to save the data to the database.
  • Read – This is the operation to read or display the saved data from the database.
  • Update – This is to update the existing records in a database.
  • Delete – Last but not least, this is used to perform delete operation in the database.

Each operation has its own query syntax to perform its task. Let’s take a look at each query and we will understand its concepts.

Check this also how to submit form data using AJAX in PHP to learn to perform a single CRUD operation that is to create without page refresh. You check this demo also.

Ultimately we perform CRUD operation in any complex web application or website by different techniques and methods.

Today, I am very happy to share with you CRUD application in PHP using jQuery AJAX from scratch. But today I will show you a very simple way to CRUD using a bootstrap popup model.

How to do that?

In this tutorial, I will use a bootstrap popup model in which I will place a registration form asking to fill name, email, and contact.

After that, I will fetch the records from the database and display them without page refresh that’s why we are using AJAX.

Resources to perform CRUD operations

  • It is mandatory to use jQuery library to use AJAX functionality.
  • Here I will use a popup model on the click of the add button so that we can do this without a page refresh, That’s why we need bootstrap also. This will be good for styling purposes too.
  • That’s enough!

Lets first see the files and folder structure we are going to create for CRUD application in PHP using jQuery AJAX.

crud-application-in-php-using-jquery-ajax-coding-birds-online-files-and-folder-structure

Let’s understand the task of these files. Each file has its own task.

  • config.php is the connection file to the database.
  • crud-app.js is a javaScript file responsible to make AJAX call to accomplish not to page refresh.
  • crud-script.php has the logics of CRUD means to create, read, delete and update.
  • CrudOprations.php is a PHP class that has user-defined functions. Since we are going to use the OOPs methodology.
  • custom.css is CSS file to just to style something nothing else.
  • finally, index.php is the main file on which everything is to be performed.

crud_applications.sql is just an SQL file which is a database table. The table has this structure and you to create this in your database.

crud-application-in-php-using-jquery-ajax-coding-birds-online-table-structure

Don’t worry, I will provide the SQL file, Source code link is at the end of this post. Please include these CDN in the head tag of your index.php file.

<link rel="shortcut icon" href="https://demo.codingbirdsonline.com/website/img/coding-birds-online/coding-birds-online-favicon.png">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"/>

and these JavaScript files to the footer means above the body tag in the index.php.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="crud-app.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

complete index.php file

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>CRUD Application in PHP using AJAX - Coding Birds Online</title>
    <link rel="shortcut icon" href="https://demo.codingbirdsonline.com/website/img/coding-birds-online/coding-birds-online-favicon.png">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"/>
    <link rel="stylesheet" href="custom.css">
</head>
<body>
<div style="margin-top: 10px;"><img width="100" src="https://demo.codingbirdsonline.com/website/img/coding-birds-online/coding-birds-online-favicon.png" class="center-block"/></div>
<div class="container">
    <h3>Delete multiple records from database using PHP </h3>
    <a href="javaScript:void(0);" data-toggle="modal" data-target="#myModal" class="btn btn-primary pull-right bottom-gap">Add New <i class="fa fa-plus" aria-hidden="true"></i></a>
    <table class="table table-bordered">
        <thead id="thead" style="background-color:#135361">
            <tr>
                <th>Sr.No</th>
                <th>Name</th>
                <th>Email</th>
                <th>Contact</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody id="crudData"></tbody>
    </table>
</div>
<div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">×</button>
                <h4 class="modal-title">CRUD Application Form</h4>
            </div>
            <div class="modal-body">
                <form id="crudAppForm">
                   <div class="row">
                       <div class="col-md-4">
                           <div class="form-group">
                               <label for="name">Name <span class="field-required">*</span></label>
                               <input type="text" name="name" id="name" placeholder="Name" class="form-control">
                           </div>
                       </div>
                       <div class="col-md-4">
                           <div class="form-group">
                               <label for="email">Email <span class="field-required">*</span></label>
                               <input type="text" name="email" id="email" placeholder="Email" class="form-control">
                           </div>
                       </div>
                       <div class="col-md-4">
                           <div class="form-group">
                               <label for="contact">Contact <span class="field-required">*</span></label>
                               <input type="text" name="contact" id="contact" placeholder="Contact" class="form-control">
                           </div>
                       </div>
                   </div>
                    <div class="row">
                        <div class="col-md-4">
                            <input type="hidden" name="editId" id="editId" value="" />
                            <button type="submit" name="submitBtn" id="submitBtn" class="btn btn-primary"><i class="fa fa-spinner fa-spin" id="spinnerLoader" ></i> <span id="buttonLabel">Save</span> </button>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="crud-app.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</body>
</html>

crud-app.js file

$( document ).ready(function() {
    getAllData();
    console.log( "ready!" );
});
$("form#crudAppForm").on("submit",function (e) {
    e.preventDefault();
    var name = $("#name").val();
    var email = $("#email").val();
    var contact = $("#contact").val();
    var editId = $("#editId").val();
    if (name == ""){
        alert("Please enter name");
        $("#name").focus();
    }else if (email == "") {
        alert("Please enter email");
        $("#email").focus();
    }else if (contact == "") {
        alert("Please enter contact");
        $("#contact").focus();
    }else{
        $("#buttonLabel").html("Saving...");
        $("#spinnerLoader").show('fast');
        $.post("crud-script.php",{
            crudOperation:"saveData",
            name:name,
            email:email,
            contact:contact,
            editId:editId,
        },function (response) {
            if (response == "saved") {
                $("#buttonLabel").html("Save");
                $("#spinnerLoader").hide('fast');
                $("#myModal").modal('hide');
                $("form#crudAppForm").each(function () {
                    this.reset();
                });
                getAllData();
            }
        });
    }
});

function getAllData() {
    $.post("crud-script.php",{crudOperation:"getData"},function (allData) {
        $("#crudData").html(allData);
    });
}

function editData(editId,name,email,contact) {
    $("#editId").val(editId);
    $("#name").val(name);
    $("#email").val(email);
    $("#contact").val(contact);
    $("#myModal").modal('show');
}

function deleteData(deleteId) {
    if(confirm("Are you sure to delete this ?")){
        $('#deleteSpinner'+deleteId).show('fast');
        $.post("crud-script.php",{crudOperation:"deleteData",deleteId:deleteId},function (response) {
            if (response == "deleted") {
                $('#deleteSpinner'+deleteId).hide('fast');
                getAllData();
            }
        });
    }
}

crud-script.php file

<?php
include "config.php";
include_once "CrudOperations.php";
$crudObj = new CrudOperations();
if ($_POST['crudOperation'] == "saveData") {
    $name = $_POST['name'];
    $email = $_POST['email'];
    $contact = $_POST['contact'];
    $editId = $_POST['editId'];
    $save = $crudObj->saveData($connection,$name,$email,$contact,$editId);
    if ($save){
        echo "saved";
    }
}

if ($_POST['crudOperation'] == "getData") {
    $sr = 1;
    $tableData = '';
    $allData = $crudObj->getAllData($connection);
    if ($allData->num_rows>0) {
        while ($row = $allData->fetch_object()) {
            $tableData .= ' <tr>
                <td>'.$sr.'</td>
                <td>'.$row->name.'</td>
                <td>'.$row->email.'</td>
                <td>'.$row->contact.'</td>
                <td><a href="javaScript:void(0)" onclick="editData(\''.$row->id.'\',\''.$row->name.'\',\''.$row->email.'\',\''.$row->contact.'\');" class="btn btn-success btn-sm">Edit <i class="fa fa-pencil-square-o"></i></a>
                <a href="javaScript:void(0)" onclick="deleteData(\''.$row->id.'\');" class="btn btn-danger btn-sm">Delete <i class="fa fa-trash-o"></i></a>
                <i class="fa fa-spinner fa-spin" id="deleteSpinner'.$row->id.'" style="color: #ff195a;display: none"></i></td>
            </tr>';
            $sr++;
        }
    }
    echo $tableData;
}

if ($_POST['crudOperation'] == "deleteData"){
    $deleteId = $_POST['deleteId'];
    $delete = $crudObj->deleteData($connection,$deleteId);
    if ($delete){
        echo "deleted";
    }
}

config.php file

<?php
$connection = new mysqli("localhost","root","","codingbirds");
if (! $connection){
    die("Error in connection".$connection->connect_error);
}

CrudOperations.php file

<?php
class CrudOperations
{
    public function saveData($connection,$name,$email,$contact,$editId)
    {
        if ($editId == "") {
            $query = "INSERT INTO crud_application SET name='$name',email='$email',contact='$contact'";
        }else{
            $query = "UPDATE crud_application SET name='$name',email='$email',contact='$contact' WHERE id='$editId'";
        }
        $result = $connection->query($query) or die("Error in saving data".$connection->error);
        return $result;
    }

    public function getAllData($connection)
    {
        $query = "SELECT * FROM crud_application";
        $result = $connection->query($query) or die("Error in getting data".$connection->error);
        return $result;
    }

    public function deleteData($connection,$deleteId){
        $query = "DELETE FROM crud_application WHERE id='$deleteId'";
        $result = $connection->query($query) or die("Error in deleting data".$connection->error);
        return $result;
    }
}

custom.css

#thead>tr>th{ color: white; }
.center-block {
    display: block;
    margin-left: auto;
    margin-right: auto;
}
.bottom-gap{
    margin-bottom: 10px;
}

.field-required,.delete-spinner{
    color: red;
}
#spinnerLoader{
    display: none;
}

Run the Code!

Now if you run the code, if there are not any errors you will get something like this.

crud-application-in-php-using-jquery-ajax-coding-birds-online-crud-applications-demo

When you will submit this form you will the complete final output like this. And if you click on the Add New+ button this popup form will have appeared.

crud-application-in-php-using-jquery-ajax-coding-birds-online-crud-add-data-example

If you submit this form filling the asked values then the record will be displayed. And to inform you, everything will be on the same page without any reload. Again if you click on the edit button then the same bootstrap popup will appear with the values which you filled previously.

If you update the values then it will call ajax request, update them to the database and display again to the table.

So if you want to delete you can do it also. It will ask you “Are you sure to delete this ?”. If you confirm this then it will be deleted.

Source Code & Demo

You can download the full 100% working source code from here. You check this demo also.

Conclusion

I hope you learned explained above, If you have any suggestions, are appreciated. And if you have any errors comment here. You can download the full 100% working source code from here.

Ok, Thanks for reading this article, see you in the next post.

Happy Coding 🙂

Most of the time of want to download the desired folder from GitHub repository but not complete repo. So this post is for you if you are looking for the same. In this article, you will learn how to clone a specific folder from a git.

You will be happy to know that this article is not going to be Technical any more. You just need to copy the path of the file/folder of the repository from GitHub and paste it to the input box and click the download button that’s it.

So without wasting much time lets come into the steps to follow.

  • Head over to Google Search Box and type downgit.
  • Click on the first link. You can directly go to this website.
  • Now copy the path of a specific file/folder from the git repository.
  • And paste this path to the input box and hit the download button.
  • You will get a zip file in return.
  • That’s it !!!

If you have checked this article on searchable select dropdown with country flag. Then you might want to download all the flags of countries that are in the folder of a GitHub repository.

So the complete path is: https://github.com/codingbirdsonline/codingbirds_/tree/master/how-to-make-searchable-select-dropdown/flags

When you will open that website, copy this path and paste it the box looking like this. So this is website looks like you are looking for, how to clone a specific folder from a git.

how-to-clone-a-specific-folder-from-a-git-repository-website-coding-birds-online

Conclusion

I hope you learned explained above, If you have any suggestions, are appreciated. And if you have any errors comment here.

Ok, Thanks for reading this article, see you in the next post.

Happy Coding 🙂

Scrolling a big list of countries, states or cities is annoying sometimes when you are filling a form asking your country to select. Today I come up with a solution to make a searchable drop-down list, very happy to share it with you :).

Today in this tutorial I will tell you how to make a searchable drop-down list in HTML, CSS. You can create a static dropdown but I am creating it to dynamic. Check this demo.

Problem

As you know the problem, that’s why you are here for the solution. LOL…, So the problem is this, suppose you have created a form in your website or web application, you have a long dropdown list to select it as you might have seen on a variety of websites. You need to scroll it until you did not find the item you are looking for.

coding-birds-online-how-to-make-a-searchable-drop-down-list-problem

Solution

The solution is select2. Select2 is a jQuery based replacement for select boxes. It supports searching remote data sets and infinite scrolling of results.

When you will integrate this, you will get a search box at the top of the select dropdown list. Now you can search the item you are looking for in a long list. You can check the installation guide also on the official website.

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

Import these CDN links to the head of the HTML page and paste this shortcode to the footer to make your dropdown list searchable.

// In your Javascript (external .js resource or <script> tag)
$(document).ready(function() {
    $('.your-select-dropdown-class').select2();
});

Don’t worry I will show you how to code step by step. I am creating this select 2 dropdown list dynamic by fetching the countries from the database. Let’s check the folder structure.

Addidtionally, I will show country flags in the dropdown, to make it more beautifull and eye catchy to the users.

coding-birds-online-how-to-make-a-searchable-drop-down-list-folder-structure

Step by step to code

  • Create an index.php file to show the select dropdown list.
  • config.php is the connection file to the database.
  • flags folder contains all the flags of the countries. I will provide it.

Now create these files.

index.php complete code

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="icon" href="https://codingbirdsonline.com/wp-content/uploads/2019/12/cropped-coding-birds-favicon-2-1-192x192.png" type="image/x-icon">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/select2@4.0.12/dist/css/select2.min.css" rel="stylesheet" />
    <script src="https://cdn.jsdelivr.net/npm/select2@4.0.12/dist/js/select2.min.js"></script>
    <title>How to make searchable dropdown with country flag - Coding Birds Online</title>
    <style>.required{color: #FF0000;}
           .flag{background-color: #ff884b;padding: 10px;border-radius: 20px;color: white}
    </style>
</head>
<body>
<div class="container">
    <?php
    include "config.php";
    $query = "SELECT * FROM bird_searchable_dropdown";
    $countries = $connection->query($query);
    ?>
    <div class="row">
        <div class="col-sm-9 col-md-7 col-lg-5 mx-auto">
            <div class="card card-signin my-5">
                <div class="card-body">
                    <center><img width="50" src="https://codingbirdsonline.com/wp-content/uploads/2019/12/cropped-coding-birds-favicon-2-1-192x192.png"></center>
                    <h5 class="card-title text-center">Searchable dropdown with country <span class="flag">FLAG</span></h5>
                    <form>
                        <div class="form-label-group">
                            <label for="inputEmail">Country <span class="required">*</span></label>
                            <select  name="select2" id="select2" class="form-control">
                                <option value="">Select</option>
                                <?php
                                if ($countries->num_rows>0){
                                    while ($country = $countries->fetch_object()){ ?>
                                        <option value="<?php echo $country->code;?>"><?php echo $country->countryname;?></option>
                                   <?php  }
                                }
                                ?>
                            </select>
                        </div> <br/>
                        <button type="submit" name="submitBtn" id="submitBtn" class="btn btn-md btn-primary btn-block text-uppercase" >Submit</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript">
    $("#select2").select2({
        templateResult: formatState
    });
    function formatState (state) {
        if (!state.id) {
            return state.text;
        }
        var baseUrl = "flags";
        var $state = $(
            '<span><img src="' + baseUrl + '/' + state.element.value.toLowerCase() + '.png" class="img-flag" /> ' + state.text + '</span>'
        );
        return $state;
    }
</script>
</body>
</html>

config.php

<?php
$connection = new mysqli("localhost","root","","codingbirds");
if (! $connection){
    die("Error in connection".$connection->connect_error);
}

Run the Code to get the searchable drop-down list

When you run the code you will get this output as I told above in the solution.

coding-birds-online-how-to-make-a-searchable-drop-down-list-final-output

Source Code & Demo

You can download the full 100% working source code from here. You check this demo also.

Conclusion

I hope you learned explained above, If you have any suggestions, are appreciated. And if you have any errors comment here. You can download the full 100% working source code from here

Check this https://minhaskamal.github.io/DownGit/ link to download a single folder(flags folder) from a repository on GitHub.

Ok, Thanks for reading this article, see you in the next post.

Happy Coding 🙂

Form submission is very common in websites or web applications. You might have noticed this in a variety of websites and web software. If you want to learn how to submit form data using AJAX, you are in the right place. You can check this demo.

When you fill a form and hit the submit button then you might have seen that page is not refreshed or reloaded instead of it shows registration successful or your message received something like this.

And on some websites, you may have seen that when you hit the submit button the page gets reloaded and then after it shows that success or error message.

Page reloading in form submission is very annoying sometimes, irritates some users and affects user experience also.

Here you will learn to code your form submission with PHP with the feature of without page refresh. This website Coding Birds Online provides simple logic and 100% full working source code without any cost.

Resources to submit form data

In this example we will use simple HTML form, In my case, I have styled this form to look and feel beautiful. And We will use the jQuery library to call the AJAX request.

We need to use AJAX here in order to submit form data using AJAX in PHP. AJAX performs the task silently with page refresh or reloading. So without wasting any time, let’s see the files and folder structure.

coding-birds-online-how-to-submit-form-data-using-ajax-in-php-files-and-folder
  • index.php is the main file which is the simple HTML form.
  • config.php is the connection file to the database.
  • ajax-script.php is a logic file that silently saves the data to the database without page refresh.
  • green-dots.gif is the loading GIF to show processing when we submit the form.

First, see this AJAX code to perform form submission.

<script type="text/javascript">
  $("form#ajaxForm").on("submit",function (e) {
      e.preventDefault();
      var name = $("#name").val();
      var email = $("#email").val();
      var contact = $("#contact").val();
      if (name == ""){
          $("#nameError").show();
          $("#nameError").html("Please enter name");
          $("#nameError").fadeOut(4000);
          $("#name").focus();
      }else if (email == ""){
          $("#emailError").show();
          $("#emailError").html("Please enter email");
          $("#emailError").fadeOut(4000);
          $("#email").focus();
      }else if (!validateEmail(email)){
          $("#emailError").show();
          $("#emailError").html("Please enter valid email");
          $("#emailError").fadeOut(4000);
          $("#email").focus();
      }else if (contact == ""){
          $("#contactError").show();
          $("#contactError").html("Please enter contact");
          $("#contactError").fadeOut(4000);
          $("#contact").focus();
      }else if (!validatePhoneNumber(contact)){
          $("#contactError").show();
          $("#contactError").html("Please enter valid contact");
          $("#contactError").fadeOut(4000);
          $("#contact").focus();
      }else{
          $("#submitBtn").hide('fast');
          $("#loader").show('fast');
          $.ajax({
              url:"ajax-script.php",
              data:{key:"saveData",name:name,email:email,contact:contact},
              method:"POST",
              success:function (response) {
                //alert(response);
                  var data = response.split('^');
                  if (data[1] == "saved") {
                      $("#submitBtn").show('fast');
                      $("#loader").hide('fast');
                      $("#successMessage").show('fast');
                      $("#successMessage").fadeOut(5000);
                      $("form#ajaxForm").each(function () {
                          this.reset();
                      });
                  }
              }
          });
      }
  });

  /*========================================================================================
                                      VALIDATION CODE
   ========================================================================================*/
  function validateEmail(inputText) {
      var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
      if(inputText.match(mailformat)) {
          return true;
      } else{
          return false;
      }
  }
  function validatePhoneNumber(inputtxt) {
      var phonenoPattern = /^\+?([0-9]{2})\)?[-. ]?([0-9]{4})[-. ]?([0-9]{4})$/;
      if( inputtxt.match(phonenoPattern) ) {
          return true;
      }
      else {
          return false;
      }
  }
</script>

** Don’t worry, This javaScript code is the part of index.php file. I just wanted to show you that this is the AJAX request code.

complete index.php file

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="icon" href="https://codingbirdsonline.com/wp-content/uploads/2019/12/cropped-coding-birds-favicon-2-1-192x192.png" type="image/x-icon">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <title>Submit form data with AJAX - Coding Birds Online</title>
    <style> .alert-successs{background-color: #1eaf59;color: white;display: none}
            .required{color: #FF0000;}
            .error-message{font-size: 12px;color: red;display: none;}
    </style>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-sm-9 col-md-7 col-lg-5 mx-auto">
            <div class="card card-signin my-5">
                <div class="card-body">
                    <center>
                        <img width="50 " src="https://codingbirdsonline.com/wp-content/uploads/2019/12/cropped-coding-birds-favicon-2-1-192x192.png">
                    </center>
                    <h5 class="card-title text-center">Submit form data with AJAX</h5>
                    <div class="alert alert-successs" id="successMessage">Form data is saved !</div>
                    <form id="ajaxForm">
                        <div class="form-label-group">
                            <label for="inputEmail">Name<span class="required">*</span></label>
                            <input type="text" name="name" id="name" class="form-control"  placeholder="Name" autocomplete="off">
                            <div id="nameError" class="error-message">nameError</div>
                        </div> <br/>
                        <div class="form-label-group">
                            <label for="inputEmail">Email<span class="required">*</span></label>
                            <input type="text" name="email" id="email" class="form-control"  placeholder="Email" autocomplete="off">
                            <div id="emailError" class="error-message">emailError</div>
                        </div> <br/>
                        <div class="form-label-group">
                            <label for="inputEmail">Contact<span class="required">*</span></label>
                            <input type="text" name="contact" id="contact" class="form-control"  placeholder="Contact" maxlength="10" >
                            <div id="contactError" class="error-message">contactError</div>
                        </div> <br/>
                        <button type="submit" name="submitBtn" id="submitBtn" class="btn btn-md btn-primary btn-block text-uppercase" >Submit Form</button>
                        <center><img src="green-dots.gif" id="loader" style="display: none"/></center>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript">
  $("form#ajaxForm").on("submit",function (e) {
      e.preventDefault();
      var name = $("#name").val();
      var email = $("#email").val();
      var contact = $("#contact").val();
      if (name == ""){
          $("#nameError").show();
          $("#nameError").html("Please enter name");
          $("#nameError").fadeOut(4000);
          $("#name").focus();
      }else if (email == ""){
          $("#emailError").show();
          $("#emailError").html("Please enter email");
          $("#emailError").fadeOut(4000);
          $("#email").focus();
      }else if (!validateEmail(email)){
          $("#emailError").show();
          $("#emailError").html("Please enter valid email");
          $("#emailError").fadeOut(4000);
          $("#email").focus();
      }else if (contact == ""){
          $("#contactError").show();
          $("#contactError").html("Please enter contact");
          $("#contactError").fadeOut(4000);
          $("#contact").focus();
      }else if (!validatePhoneNumber(contact)){
          $("#contactError").show();
          $("#contactError").html("Please enter valid contact");
          $("#contactError").fadeOut(4000);
          $("#contact").focus();
      }else{
          $("#submitBtn").hide('fast');
          $("#loader").show('fast');
          $.ajax({
              url:"ajax-script.php",
              data:{key:"saveData",name:name,email:email,contact:contact},
              method:"POST",
              success:function (response) {
                //alert(response);
                  var data = response.split('^');
                  if (data[1] == "saved") {
                      $("#submitBtn").show('fast');
                      $("#loader").hide('fast');
                      $("#successMessage").show('fast');
                      $("#successMessage").fadeOut(5000);
                      $("form#ajaxForm").each(function () {
                          this.reset();
                      });
                  }
              }
          });
      }
  });

  /*========================================================================================
                                      VALIDATION CODE
    ========================================================================================*/
  function validateEmail(inputText) {
      var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
      if(inputText.match(mailformat)) {
          return true;
      } else{
          return false;
      }
  }

  function validatePhoneNumber(inputtxt) {
      var phonenoPattern = /^\+?([0-9]{2})\)?[-. ]?([0-9]{4})[-. ]?([0-9]{4})$/;
      if( inputtxt.match(phonenoPattern) ) {
          return true;
      }
      else {
          return false;
      }
  }
</script>
</body>
</html>

ajax-script.php

<?php
include "config.php";
if (isset($_POST['key']) == "saveData")
{
    $name = $_POST['name'];
    $email = $_POST['email'];
    $contact = $_POST['contact'];

    $query = "INSERT INTO bird_ajax_register SET name='$name',email='$email',contact='$contact'";
    $result = $connection->query($query);
    if ($result) {
        echo "status^saved";
    }
}
?>

config.php

<?php
$connection = new mysqli("localhost","root","","codingbirds");
if (! $connection){
    die("Error in connection".$connection->connect_error);
}

Run the Code

When you run this code, first you will get this output.

coding-birds-online-how-to-submit-form-data-using-ajax-in-php-output-screen

When you try to submit this form without filling it, To inform I will tell, I have created form validation. Then you will get this error message.

coding-birds-online-how-to-submit-form-data-using-ajax-in-php-error-message

If everything is fine, you fill the complete form and submit, then the submit button gets hidden, and the loading image is placed over there.

coding-birds-online-how-to-submit-form-data-using-ajax-in-php-submit-form

After this you will get a success message also at the top of the form, says this form data is saved!

coding-birds-online-how-to-submit-form-data-using-ajax-in-php-success-message

Source Code

You can download the full 100% working source code from here.

Conclusion

I hope you learned explained above, If you have any suggestions, are appreciated. And if you have any errors comment here. You can download the full 100% working source code from here.

Ok, Thanks for reading this article, see you in the next post.

Happy Coding 🙂

If you are looking for the code to check username availability in PHP using ajax, then you are in the right place. Here I will provide the complete 100% working source code with a demo.

Username or email availability check is the most common feature used by a variety of websites and web applications. You might have seen this feature on most of the websites when you signup or fill a registration form.

Here I will show you an example so that you can understand more. This is a simple form accepts the username. When you type the username in the input box then it automatically searches in the database whether this username already exists or not without page refresh or page reload.

If the username already exists then it will give an error message or success message and vice-versa.

Files and Folder structure

check-username-availability-in-php-using-ajax-coding-birds-onlie-file-and-folders

There are 3 main files index.php,config.php and availability-check-script.php. These files are output file, connection file, and availability check logic file respectively. Others are just icons to show loading, error and success messages.

I will call onchange function of javaScript, which will receive the entered text in the input box and make an AJAX call to validate this username already exists or not.

<input type="text" name="username" id="username" class="form-control" onkeyup="checkUsernameAvailablity();" placeholder="Start typing username" autocomplete="off" required>

When defining this function, It will be like this.

<script type="text/javascript">
    function checkUsernameAvailablity() {
        var username = $("#username").val();
        if (username !="") {
            $("#usernameAvailabilityLoader").show();
            $.post("availability-check-script.php",{key:"usernameCheck",username:username},function (response) {
                var data = response.split('^');
                if (data[1] == "available"){
                    $("#usernameAvailableLabel").show();
                    $("#usernameNotAvailableLabel").hide();
                }else if (data[1] == "notAvailable"){
                    $("#usernameNotAvailableLabel").show();
                    $("#usernameAvailableLabel").hide();
                }
                $("#usernameAvailabilityLoader").hide();
            });
        }else{
            $("#usernameAvailabilityLoader").hide();
            $("#usernameAvailableLabel").hide();
            $("#usernameNotAvailableLabel").hide();
        }
    }
</script>

Complete Code

index.php

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="icon" href="https://codingbirdsonline.com/wp-content/uploads/2019/12/cropped-coding-birds-favicon-2-1-192x192.png" type="image/x-icon">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <title>Check username availability in php using ajax - Coding Birds Online</title>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-sm-9 col-md-7 col-lg-5 mx-auto">
            <div class="card card-signin my-5">
                <div class="card-body">
                    <center>
                        <img width="50 " src="https://codingbirdsonline.com/wp-content/uploads/2019/12/cropped-coding-birds-favicon-2-1-192x192.png">
                    </center>
                    <h5 class="card-title text-center">Check Username Availability</h5>
                    <label>[ankit,manish,rohit not available]</label>
                    <form id="checkingForm" class="form-signin">
                        <div class="form-label-group">
                            <label for="inputEmail">Username<span style="color: #FF0000">*</span></label>
                            <input type="text" name="username" id="username" class="form-control" onkeyup="checkUsernameAvailablity();" placeholder="Start typing username" autocomplete="off" required>
                        </div> <br/>
                        <div class="form-label-group" id="usernameAvailabilityLoader" style="display: none">
                            <img src="loading-icon.gif"/>  <label for="inputEmail">Please Wait a moment...</label>
                        </div>
                        <div class="form-label-group" id="usernameAvailableLabel" style="display: none">
                            <img src="success-icon.png" width="20"/>  <label for="inputEmail">Username available</label>
                        </div>
                        <div class="form-label-group" id="usernameNotAvailableLabel" style="display: none">
                            <img src="error-icon.png" width="20"/>  <label for="inputEmail">Username not available </label>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript">
    function checkUsernameAvailablity() {
        var username = $("#username").val();
        if (username !="") {
            $("#usernameAvailabilityLoader").show();
            $.post("availability-check-script.php",{key:"usernameCheck",username:username},function (response) {
                var data = response.split('^');
                if (data[1] == "available"){
                    $("#usernameAvailableLabel").show();
                    $("#usernameNotAvailableLabel").hide();
                }else if (data[1] == "notAvailable"){
                    $("#usernameNotAvailableLabel").show();
                    $("#usernameAvailableLabel").hide();
                }
                $("#usernameAvailabilityLoader").hide();
            });
        }else{
            $("#usernameAvailabilityLoader").hide();
            $("#usernameAvailableLabel").hide();
            $("#usernameNotAvailableLabel").hide();
        }
    }
</script>
</body>
</html>

Run this Code

When you run this code you will get the following output if there are no errors. When you type any username in the box, then it will show the loader.

check-username-availability-in-php-using-ajax-coding-birds-onlie-checking-username

If the username is already exited it will show like this.

check-username-availability-in-php-using-ajax-coding-birds-onlie-username-not-available

And when username available means it does not exist already, then you will see this.

check-username-availability-in-php-using-ajax-coding-birds-onlie-username-is-available

Source Code & Demo

You can download the full 100% working source code from here. You check this demo also.

Conclusion

I hope you learned explained above, If you have any suggestions, are appreciated. And if you have any errors comment here. You can download the full 100% working source code from here.

Ok, Thanks for reading this article, see you in the next post.

Happy Coding 🙂

The pie chart is the most important part of data visualization. If you are looking for the code to draw the dynamic pie chart according to your data then you are in the right place.

Our website Coding Birds Online provides the very simple, to the point and 100% working source code with a complete guide. You can check this demo also.

What is a pie chart?

A pie chart (or a circle chart) is a circular statistical graphic, which is divided into slices to illustrate numerical proportions. In a pie chart, the arc length of each slice (and consequently its central angle and area), is proportional to the quantity it represents. You can read more about this chart from here.

coding-birds-online-what-is-pie-chart-exmple-image

Why it is used?

If you are using a web application or website or any report generation software then you might have noticed this feature. Graphical or visual representation of data is usually a requirement for this software.

For example, You are using an ERP system of any college you might have seen your attendance in pie chart. If you are making any software for attendance management, then it will be a great feature to that.

Starting to Code 🙂

Sounds interesting? I know surely you are. Now that’s enough to understand. So what are you waiting for? let’s get started. Visit highcharts.com for reference. If you click on this link, it will give you the same code but with static data.

  • Create an HTML page (index.php) to display the pie chart
  • Get the required imports like JavaScripts to draw a pie chart
  • Paste these imports to the head tag of the index file.
  • Paste the javaScript code above the closing tag of the body.

These are the required imports to create a dynamic pie chart.

 <script src="https://code.highcharts.com/highcharts.js"></script>
 <script src="https://code.highcharts.com/modules/exporting.js"></script>
 <script src="https://code.highcharts.com/modules/export-data.js"></script>
 <script src="https://code.highcharts.com/modules/accessibility.js"></script>

Step 1: Create index.php file

index.php

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="icon" href="https://codingbirdsonline.com/wp-content/uploads/2019/12/cropped-coding-birds-favicon-2-1-192x192.png" type="image/x-icon">
    <script src="https://code.highcharts.com/highcharts.js"></script>
    <script src="https://code.highcharts.com/modules/exporting.js"></script>
    <script src="https://code.highcharts.com/modules/export-data.js"></script>
    <script src="https://code.highcharts.com/modules/accessibility.js"></script>
    <title>How to create dynamic pie chart - Coding Birds Online</title>
    <style> .center-block { display: block;margin-left: auto;margin-right: auto; }</style>
</head>
<body>
<div class="container">
    <center>
        <div id="container"></div>
    </center>
    <img class="center-block" src="https://codingbirdsonline.com/wp-content/uploads/2019/12/cropped-coding-birds-favicon-2-1-192x192.png" width="50">
 </div>
<?php
include "config.php"; // connection file with database
$query = "SELECT * FROM bird_pie_chart"; // get the records on which pie chart is to be drawn
$getData = $connection->query($query);
?>
<script>
    // Build the chart
    Highcharts.chart('container', {
        chart: {
            plotBackgroundColor: null,
            plotBorderWidth: null,
            plotShadow: false,
            type: 'pie'
        },
        title: {
            text: 'Programming Language Popularity, 2020'
        },
        tooltip: {
            pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
        },
        accessibility: {
            point: {
                valueSuffix: '%'
            }
        },
        plotOptions: {
            pie: {
                allowPointSelect: true,
                cursor: 'pointer',
                dataLabels: {
                    enabled: false
                },
                showInLegend: true
            }
        },
        series: [{
            name: 'Popularity',
            colorByPoint: true,
            data: [
                <?php
                $data = '';
                if ($getData->num_rows>0){
                    while ($row = $getData->fetch_object()){
                        $data.='{ name:"'.$row->programming.'",y:'.$row->popularity.'},';
                    }
                }
                echo $data;
                ?>
            ]
        }]
    });
</script>
</body>
</html>

In this file, I am including a config.php, which is a connection file to the database. I am fetching records from the bird_pie_chart table. Don’t worry, I will provide the complete source code. The following is the database table structure.

coding-birds-online-table-structure

In this example, I am showing you a comparison of programming languages, with dummy data. This is now the actual data. You can customize this code and database table according to your needs.

Step 2: Run the code to get the desired output !!! That’s it.

Output

when you run the code and make sure everything is fine, then you will get the same output as following.

how-to-make-a-dynamic-pie-chart-in-php-in-2-steps-sample-output

Source Code & Demo to make a dynamic pie chart

You can download the full 100% working source code from here. You check this demo also.

Conclusion

I hope you learned explained above, If you have any suggestions, are appreciated. And if you have any errors comment here. You can download the full 100% working source code from here.

Happy Coding 🙂