Simple HTML Form Validation Using JQuery

The form allows you to check whether the input from user is valid or not. This helps you ensure that the  type of data inserted by the user is same as field expects to be.

In this tutorial, we will look on how to Validate a HTML Form with JQuery.

The form collects the user input and perform a simple check if the data matches the field type.If otherwise an error warning is displayed asking user to input correct type of data.

HTML Form Validation Using JQuery (more…)

Easy Ajax Image Upload and view with JQuery, PHP

Today, we will look on how to upload an image with specific extensions into a server using AJAX and PHP. In this project, we will be using AJAX to show the user the uploaded image without refreshing the page. Also, we will be using extension validation using PHP in run time while uploading in order to prevent unknown file formats.

Easy Ajax Image Upload and view with JQuery, PHP

Overview

In order to build an image uploader, we will need to create the below-specified file with the specified code saved in it. Group all the files in the same folder.

  • Index.php
  • Ajaxhandling.php
  • Script.js
  • Jquery min library

Index.php

The index file contains the HTML code which shows the file upload form as well as the file browser and the submit button .
Basically, it is the user end where a user performs the upload.

<!doctype html>
<html>
<head lang="en">
<meta charset="utf-8">
<title>Tutorial-17</title>
<link rel="stylesheet" href="style.css" type="text/css" />
<script type="text/javascript" src="js/jquery-1.11.3-jquery.min.js"></script>
<script type="text/javascript" src="js/Script.js"></script>
</head>
<body>
<div class="container">
<h1><a href="">Image Upload Section</a></h1>
<hr>
<div id="preview"><img src="no-image.jpg" /></div>

<form id="form" action="ajaxhandling.php" method="post" enctype="multipart/form-data">
<input id="uploadImage" type="file" accept="image/*" name="image" />
<input id="button" type="submit" value="Upload">
</form>
<div id="err"></div>
<hr>
</div>
</body>
</html>

Ajaxhandling.php

This file contains all the allowed extension arrays as well as the storing path of images in the server. When images are selected and submit button is pressed it will send the image to this code segment. It will first extract the image into a variable and then pass the image trough extension array in order to validate the file extension of an image. Then if all options are validated it will finally move the file from the temporary location to specified location on the server.

<?php

$valid_extensions = array('jpeg', 'jpg', 'png', 'gif', 'bmp'); // allowed file extensions
$path = 'uploads/'; // file upload directory

if(isset($_FILES['image']))
{
$img = $_FILES['image']['name'];
$tmp = $_FILES['image']['tmp_name'];

// get uploaded file's extension
$ext = strtolower(pathinfo($img, PATHINFO_EXTENSION));

// can upload same image using rand function
$final_image = rand(1000,1000000).$img;

// check's valid format
if(in_array($ext, $valid_extensions))
{
$path = $path.strtolower($final_image);

if(move_uploaded_file($tmp,$path))
{
echo "<img src='$path' />";
}
}
else
{
echo 'invalid file';
}
}

?>

Script.js

The Javascript file is used to make the ajax asynchronous call to ajaxhandling.php file as well as with ajax library. we use fadeIn element code block to show users the uploaded image without refreshing the page and if there is any error in uploading, a message is printed saying invalid upload.

$(document).ready(function (e) {
$("#form").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "ajaxhandling.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
beforeSend : function()
{
$("#err").fadeOut();
},
success: function(data)
{
if(data=='invalid file')
{
// invalid file format.
$("#err").html("Invalid File !").fadeIn();
}
else
{
// view uploaded file.
$("#preview").html(data).fadeIn();
$("#form")[0].reset();
}
},
error: function(e)
{
$("#err").html(e).fadeIn();
}
});
}));
});

Download Source code and complete Working Demo:

Download the complete source code.

Grab the the free working demo Intantly!

You have Successfully Suscribed!

PHP PDO CRUD Tutorial Using OOP with Bootstrap

Want to create a form where you can perform Create, Read, Update, and Delete operations to your database?
Here, we will look into database transactions in PHP using PDO on a Bootstrap website, for this we will be using Bootstrap libraries as well as some third party libraries. Below is the folder structure showing the files used.

 

Overview

In this tutorial we will be creating 6 main files to complete our task. Save the files with the respective codes and place all the files in same directory.

  • Add.php
  • Delete.php
  • Index.php
  • Update.php
  • Config.php
  • Data.inc.php

Database Schema

Let us start by creating a database to store our values, I have named my database “biodata”,
Then add table to your database.

CREATE TABLE IF NOT EXISTS `users` (
`username` varchar(50) NOT NULL,
`email` varchar(50) NOT NULL,
`password` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Add.php

Add.php file contains the code which renders the Add data html form as well as the Server-side code which is used to perform the Create function. As soon as the user press the submit button, the form will send data to server using POST method. That data is captured then assigned into variables which will be further stored in the database using PDO statements.

<?php
include_once 'includes/config.php';

$database = new Config();
$db = $database->getConnection();

include_once 'includes/data.inc.php';
$product = new Data($db);

?>
<!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>Tutorial-06</title>

<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>

</head>
<body>
<p><br/></p>
<div class="container">
<p>
<a class="btn btn-primary" href="index.php" role="button">Back</a>
</p><br/>
<?php
if ($_POST) {

$product->name = $_POST['name'];
$product->gender = $_POST['gender'];
$product->contactNum = $_POST['contact'];
$product->address = $_POST['address'];

if ($product->create()) {
?>
<div class="alert alert-success alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span
aria-hidden="true">&times;</span></button>
<strong>Success!</strong> <a href="index.php">View Data</a>.
</div>
<?php
} else {
?>
<div class="alert alert-danger alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span
aria-hidden="true">&times;</span></button>
<strong>Fail!</strong>
</div>
<?php
}
}
?>
<form method="post">
<div class="form-group">
<label for="nm">Name</label>
<input type="text" class="form-control" id="nm" name="name">
</div>
<div class="form-group">
<label for="gd">Gender</label>
<input type="text" class="form-control" id="gd" name="gender">
</div>
<div class="form-group">
<label for="tl">Phone</label>
<input type="text" class="form-control" id="tl" name="contact">
</div>
<div class="form-group">
<label for="ar">Address</label>
<textarea class="form-control" rows="3" id="ar" name="address"></textarea>
</div>
<button type="submit" class="btn btn-success">Submit</button>
</form>
</div>

<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</body>
</html>

Delete.php

Delete file contains the code which perform delete function. For the delete function to execute, we need to make a GET call embedding the relevant ID of the field needed to delete. Then, the PDO function delete will remove the specific entry from database.

<?php
// check if value was posted
// include database and object file
include_once 'includes/config.php';
include_once 'includes/data.inc.php';

// get database connection
$database = new Config();
$db = $database->getConnection();

// prepare product object
$product = new Data($db);

// set product id to be deleted
$product->id = isset($_GET['id']) ? $_GET['id'] : die('Need Product ID');

// delete the product
if($product->delete()){
echo "<script>location.href='index.php'</script>";
}

// if unable to delete the product
else{
echo "<script>alert('Failed to Deleted Data')</script>";

}
?>

Index.php

Index file contains the main HTML form as well as the Server side code which performs the Read function in order to populate form with data. In order to populate with data, first server issues a PDO statement to query and return all the data from the database. Then according to the count of entries the User interface will generate rows and columns and display them.

<?php
$page = isset($_GET['page']) ? $_GET['page'] : 1;

$records_per_page = 5;

$from_record_num = ($records_per_page * $page) - $records_per_page;

include_once 'includes/config.php';
include_once 'includes/data.inc.php';

$database = new Config();
$db = $database->getConnection();

$product = new Data($db);

$stmt = $product->readAll($page, $from_record_num, $records_per_page);
$num = $stmt->rowCount();

?>
<!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>Tutorial-06</title>

<link href="css/bootstrap.min.css" rel="stylesheet">

<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>

</head>
<body>
<p><br/></p>
<div class="container">
<p>
<a class="btn btn-primary" href="add.php" role="button">Add Data</a>
</p>
<?php
if($num>0){
?>
<table class="table table-bordered table-hover table-striped">
<caption>Personal Data Table</caption>
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Gender</th>
<th>Phone</th>
<th>Address</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
?>
<tr>
<?php echo "<td>{$id_pdo}</td>" ?>
<?php echo "<td>{$nm_pdo}</td>" ?>
<?php echo "<td>{$gd_pdo}</td>" ?>
<?php echo "<td>{$tl_pdo}</td>" ?>
<?php echo "<td>{$ar_pdo}</td>" ?>
<?php echo "<td width='100px'>
<a class='btn btn-warning btn-sm' href='update.php?id={$id_pdo}' role='button'><span class='glyphicon glyphicon-pencil' aria-hidden='true'></span></a>
<a class='btn btn-danger btn-sm' href='delete.php?id={$id_pdo}' role='button'><span class='glyphicon glyphicon-trash' aria-hidden='true'></span></a>
</td>" ?>
</tr>
<?php
}
?>
</tbody>
</table>
<?php
$page_dom = "index.php";
include_once 'includes/pagination.inc.php';
}
else{
?>
<div class="alert alert-warning alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
<strong>Warning!</strong> Data is still empty
</div>
<?php
}
?>
</div>
<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</body>
</html>

Update.php

Update file contains the code which renders the Update form as well as the Server-side code which enables the update function. For the update form to be loaded we need to pass the relevant ID via a GET method when loading the page. Then the PDO will issue a update query in order to finish update of data.

<?php
include_once 'includes/config.php';

$id = isset($_GET['id']) ? $_GET['id'] : die('Need Product ID');

$database = new Config();
$db = $database->getConnection();

include_once 'includes/data.inc.php';
$product = new Data($db);

$product->id = $id;
$product->readOne();
?>
<!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>Tutorial-06</title>
<link href="css/bootstrap.min.css" rel="stylesheet">

<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>

</head>
<body>
<p><br/></p>
<div class="container">
<p>
<a class="btn btn-primary" href="index.php" role="button">Back</a>
</p><br/>
<?php
if($_POST){

$product->name = $_POST['name'];
$product->gender = $_POST['gender'];
$product->contactNum = $_POST['contact'];
$product->address = $_POST['address'];

if($product->update()){
?>
<script>window.location.href='index.php'</script>
<?php
}else{
?>
<div class="alert alert-danger alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
<strong>Fail!</strong>
</div>
<?php
}
}
?>
<form method="post">
<div class="form-group">
<label for="nm">Name</label>
<input type="text" class="form-control" id="nm" name="name" value='<?php echo $product->name; ?>'>
</div>
<div class="form-group">
<label for="gd">Gender</label>
<input type="text" class="form-control" id="gd" name="gender" value='<?php echo $product->gender; ?>'>
</div>
<div class="form-group">
<label for="tl">Phone</label>
<input type="text" class="form-control" id="tl" name="contact" value='<?php echo $product->contactNum; ?>'>
</div>
<div class="form-group">
<label for="ar">Address</label>
<textarea class="form-control" rows="3" id="ar" name="address"><?php echo $product->address; ?></textarea>
</div>
<button type="submit" class="btn btn-success">Submit</button>
</form>
</div>

<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>

</body>
</html>

Config.php

Config file contains the code which keep the connection with the database, in every PHP file where there is a need to interact with database we need to include this configuration file.

<?php

class Config
{

// specify your own database credentials
private $host = "localhost";
private $db_name = "biodata";
private $username = "root";
private $password = "";
public $conn;

// get the database connection
public function getConnection()
{

$this->conn = null;

try {
$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
} catch (PDOException $exception) {
echo "Connection error: " . $exception->getMessage();
}

return $this->conn;
}
}

?>

Data.inc.php

This file contains the Code for all the CRUD operations written against the database. Every other file uses an object of this class to call the operations. This class act as the base class which is written on top of the PDO data class With this it perform all the Database CRUD operations that are written in a more relevant way to this web service logic.

<?php

class Data
{

// database connection and table name
private $conn;
private $table_name = "crudpdo";

// object properties
public $id;
public $name;
public $gender;
public $contactNum;
public $address;

public function __construct($db)
{
$this->conn = $db;
}

// create product
function create()
{

//write query
$query = "INSERT INTO " . $this->table_name . " values('',?,?,?,?)";

$stmt = $this->conn->prepare($query);

$stmt->bindParam(1, $this->name);
$stmt->bindParam(2, $this->gender);
$stmt->bindParam(3, $this->contactNum);
$stmt->bindParam(4, $this->address);

if ($stmt->execute()) {
return true;
} else {
return false;
}

}

// read products
function readAll($page, $from_record_num, $records_per_page)
{

$query = "SELECT * FROM " . $this->table_name . " ORDER BY nm_pdo ASC LIMIT {$from_record_num}, {$records_per_page}";

$stmt = $this->conn->prepare($query);
$stmt->execute();

return $stmt;
}

// used for paging products
public function countAll()
{

$query = "SELECT id_pdo FROM " . $this->table_name . "";

$stmt = $this->conn->prepare($query);
$stmt->execute();

$num = $stmt->rowCount();

return $num;
}

// used when filling up the update product form
function readOne()
{

$query = "SELECT * FROM " . $this->table_name . " WHERE id_pdo = ? LIMIT 0,1";

$stmt = $this->conn->prepare($query);
$stmt->bindParam(1, $this->id);
$stmt->execute();

$row = $stmt->fetch(PDO::FETCH_ASSOC);

$this->name = $row['nm_pdo'];
$this->gender = $row['gd_pdo'];
$this->contactNum = $row['tl_pdo'];
$this->address = $row['ar_pdo'];
}

// update the product
function update()
{
$query = "UPDATE
" . $this->table_name . "
SET
nm_pdo = :nm,
gd_pdo = :gd,
tl_pdo = :tl,
ar_pdo = :ar
WHERE
id_pdo = :id";

$stmt = $this->conn->prepare($query);

$stmt->bindParam(':nm', $this->name);
$stmt->bindParam(':gd', $this->gender);
$stmt->bindParam(':tl', $this->contactNum);
$stmt->bindParam(':ar', $this->address);
$stmt->bindParam(':id', $this->id);

// execute the query
if ($stmt->execute()) {
return true;
} else {
return false;
}
}

// delete the product
function delete()
{

$query = "DELETE FROM " . $this->table_name . " WHERE id_pdo = ?";

$stmt = $this->conn->prepare($query);
$stmt->bindParam(1, $this->id);

if ($result = $stmt->execute()) {
return true;
} else {
return false;
}
}
}

?><

Download complete working modes/Source Code Here:

Download the complete source code.

Grab the the free working demo Intantly!

You have Successfully Suscribed!

JQuery Username Availability Live Check with PHP and Ajax

Want to check the Username availability for your membership site without re-loading the Page using AJAX J Query and MySQL database with PHP? If Yes is your answer you definitely need to read this post.

Username Availability

Overview

To continue in this tutorial we will need the files mentioned below,

  • Index.php
  • Style.css
  • Username-Check.php
  • jquery-1.11.3-jquery.min.js

Database Schema

Adding a table

--
-- Database: `dbtest`
--
CREATE TABLE `users` (
`id` INT( 5 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`user_name` VARCHAR( 25 ) NOT NULL
) ENGINE = MYISAM ;

Inserting values into table

INSERT INTO `users` (`id`, `user_name`) VALUES (1, 'lplp');

You can add some more data to the table according to need.

Index.php

This file contains the code which imports CSS codes from “style.css” file,
Render a form which is needed to input data by the user, also this contains the Ajax code which takes the input and validate it by passing it to “username-check.php” file. You need to import the J Query library in order to make the AJAX code work Properly.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Live Username Availability Check using PHP PDO and jQuery</title>
<script type="text/javascript" src="jquery-1.11.3-jquery.min.js"></script>
<link rel="stylesheet" href="style.css"/>
<script type="text/javascript">

$(document).ready(function()
{
$("#name").keyup(function()
{
var name = $(this).val();

if(name.length > 3)
{
$("#result").html('Validating');

$.ajax({

type : 'POST',
url : 'Username-Check.php',
data : $(this).serialize(),
success : function(data)
{
$("#result").html(data);
}
});
return false;

}
else
{
$("#result").html('');
}
});

});
</script>

</head>

<body>
<form id="reg-form" action="" method="post" autocomplete="off">
<fieldset>
<div>
<input type="text" name="name" id="name" placeholder="Username" />
<span id="result"></span>
</div>
</fieldset>
</form>
</body>
</html>

Style.css

This file contains the styling code which is used to render the form in index.php file.

@charset "utf-8";
/* CSS Document */

*{margin:0; padding:0;}
#reg-form
{
margin:100px auto;
padding:25px;
border:solid #cfcfcf 1px;
width:50%;
background:#f9f9f9;
}
fieldset
{
padding:5px;
width:60%;
margin:0 auto;
border:0;
}
input
{
width:100%;
height:35px;
border:solid #00a2d1 1px;
padding-left:10px;
font-family:Verdana, Geneva, sans-serif;
font-weight:bold;
font-size:15px;
}
span
{
font-family:Verdana, Geneva, sans-serif;
font-weight:bold;
font-size:15px;
}

Username-Check.php

Username-Check.php file contains the code which is needed to take the data from index.php and run a query against the mysql to validate if data is already present in database. When AJAX code sends data with the method POST to the server side file (current file) it extract the data and then send them to validate with the database. If the database sends result, the code will show that the Username is already taken.

<?php

$host="localhost";
$user="root";
$pass="";
$dbname="dbtest";

$dbcon = new PDO("mysql:host={$host};dbname={$dbname}",$user,$pass);

if($_POST)
{
$name = strip_tags($_POST['name']);

$stmt=$dbcon->prepare("SELECT user_name FROM users WHERE user_name=:name");
$stmt->execute(array(':name'=>$name));
$count=$stmt->rowCount();

if($count>0)
{
echo "<span style='color:brown;'>Username is not available</span>";
}
else
{
echo "<span style='color:green;'>Username Available</span>";
}
}
?>

Jquery-1.11.3-jquery.min.js

This is the jQuery library which we need to import in order to make the AJAX functions work.

<script type="text/javascript" src="jquery-1.11.3-jquery.min.js"></script>

Download The codes here.

Download the complete source code.

Grab the the free working demo Intantly!

You have Successfully Suscribed!