Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
The record i just submitted is successfully added to the database. Although we can’t see right
now but it can be checked directly in your MySql.
1 +----+----------------+---------------------------+
2 | id | name | message |
3 +----+----------------+---------------------------+
4 | 1 | Agung Setiawan | Cool comment |
5 | 2 | Nusantara | Indonesia is hot but nice |
+----+----------------+---------------------------+
6
What is the value of the comment feature of web app if visitors can’t see their own comment.
<script type="text/javascript">
$(document).ready(function(){
function showComment(){
$.ajax({
type:"post",
url:"process.php",
data:"action=showcomment",
success:function(data){
$("#comment").html(data);
}
});
}
showComment();
$("#button").click(function(){
var name=$("#name").val();
var message=$("#message").val();
$.ajax({
type:"post",
url:"process.php",
data:"name="+name+"&message="+message+"&action=addcomme
success:function(data){
showComment();
});
});
});
</script>
</head>
<body>
<form>
name : <input type="text" name="name" id="name"/>
</br>
message : <input type="text" name="message" id="message" />
</br>
<input type="button" value="Send Comment" id="button">
$action=$_POST["action"];
if($action=="showcomment"){
$show=mysql_query("Select * from comment order by id desc");
while($row=mysql_fetch_array($show)){
echo "<li><b>$row[name]</b> : $row[message]</li>";
}
}
else if($action=="addcomment"){
$name=$_POST["name"];
$message=$_POST["message"];
if($query){
echo "Your comment has been sent";
}
else{
echo "Error in sending your comment";
}
}
?>
Now it is more cool with visitor’s comment directly show up after Send Button is clicked
The Project
In this project we will create simple form submitting. Whenever users type their name in the
form an then submit it by clicking the submit button. Their name will be shown below the input
form without page refresh process :D. By Using this technique our web application is feels like
desktop application.
ajaxfirst.php
1
2
3 <html>
4 <head>
5
6 <script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
7 <script type="text/javascript">
$(document).ready(function(){
8 $("#submit").click(function(){
9
10 var name=$("#name").val();
11 $.ajax({
12 type:"post",
13 url:"getname.php",
data:"name="+name,
14 success:function(data){
15 $("#info").html(data);
16 }
17 })
});
18 });
19 </script>
20 </head>
21
22 <body>
23 <form method="post" action="">
Name : <input type="text" name="name" id="name"/>
24 <input type="button" name="submit" id="submit" value="Submit"/>
25 </form>
26 <div id="info" />
27 </body>
</html>
28
29
30
and following code is responsible in giving the output that needs to be shown
getname.php
1 <?php
2
3 $name=$_POST["name"];
4 echo "Thank you ".$name." for Register in our site"
5
?>
6
Here is the result
Okay, so far we have learn the basic of Ajax using jQuery. In next cool tutorial we will learn
how to use this technique to be implemented in database application
<html>
<head>
<link href="pagination_style.css" type="text/css" rel="stylesheet"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function get_data(no)
{
$.ajax
({
type:'post',
url:'get_data.php',
data:{
row_no:no
},
success:function(response) {
document.getElementById("pagination_div").innerHTML=response;
}
});
}
</script>
</head>
<body>
<div id="wrapper">
<?php
$host="localhost";
$username="root";
$password="";
$databasename="sample";
$connect=mysql_connect($host,$username,$password);
$db=mysql_select_db($databasename);
<div id="tota_page_div">
<?php
for($i=1;$i<=$total_results;$i++)
{
echo "<input type='button' value='".$i."' onclick='get_data(".$i.")'>";
}
?>
</div>
</div>
</body>
</html>
In this step we create a database table called 'language' and insert some rows in
it and then display the first row and also get total no of rows in our table to create
buttons for pagination to get data.We also create function get_data() which is
used to get data from our 'get_data.php' file and then display the data in our
'pagination_div'.You may also like Load Data From Database Without Page
Refresh Using Ajax.
Step 2.Make a PHP file to get and send the records
We make a PHP file and save it with a name get_data.php
<?php
$host="localhost";
$username="root";
$password="";
$databasename="sample";
$connect=mysql_connect($host,$username,$password);
$db=mysql_select_db($databasename);
if(isset($_POST['row_no']))
{
$row=$_POST['row_no'];
$row=$row-1;
$select_data=mysql_query("select * from language limit $row,1");
$row=mysql_fetch_array($select_data);
echo "<p class='para1'>".$row['language_name']."</p>";
echo "<p class='para2'>".$row['language_description']."</p>";
exit();
}
?>
In this step we get the row_no val and subtract that value to 1 because in mysql
row indexing start with 0 so to get 1st row we have to pass 0 in limit clause and
we have to display 1 record each time so we use 1 in limit clause and after
quering the database we get the results and send back to 'pagination.php' for
display.Always validate data before and after sending the value.
Step 3.Make a CSS file and define styling
We make a CSS file and save it with a name pagination_style.css
body
{
text-align:center;
width:100%;
margin:0 auto;
padding:0px;
font-family:helvetica;
background-color:#D8D8D8;
}
#wrapper
{
text-align:center;
margin:0 auto;
padding:0px;
width:995px;
}
#pagination_div
{
border:1px solid;
margin-top:50px;
border:1px dashed #585858;
width:300px;
padding:10px;
box-sizing:border-box;
margin-left:350px;
min-height:180px;
}
#pagination_div p
{
margin:0px;
}
#pagination_div .para1
{
font-size:45px;
font-weight:bold;
color:#585858;
}
#pagination_div .para2
{
margin-top:20px;
font-size:25px;
font-weight:bold;
color:#585858;
}
#tota_page_div
{
margin-top:20px;
}
#tota_page_div input[type="button"]
{
background-color:#585858;
border:none;
margin:2px;
color:white;
height:35px;
width:35px;
border-radius:50%;
}
Thats all, this is create ajax pagination using jQuery, PHP and MySQL.You can
customize this code further as per your requirement. And please feel free to give
comments on this tutorial.
Automatically Refresh HTML
page or div after specific time
Interval
There are several ways to refresh a complete HTML page after specific time interval, and same is the
case with any specific Div or Span or any HTML element on a page, that we can refresh any specific
part/element of HTML page without reloading the complete page.
First let’s take a look at refreshing HTML page after specific time interval, this can be achieved
using either JavaScript or by meta tags.
A) Using Javascript:
You can use either of the following scripts to refresh after every 5 secounds, say:
Code I:
1 <script>
2
3 function autoRefresh()
4 {
5 window.location = window.location.href;
6 }
7
8 setInterval('autoRefresh()', 5000); // this will reload page after every 5 secounds; Method I
9 </script>
OR
Code II:
1 <script>
2
3 function autoRefresh1()
4 {
5 window.location.reload();
6 }
7
8 setInterval('autoRefresh1()', 5000); // this will reload page after every 5 secounds; Method II
9 </script>
B) Refresh page using Meta tags
Its very easy, you just have to put a meta tag in head tag as follows:
1 <head>
2
3 <meta http-equiv="refresh" content="5" />
4 <!-- This will refresh page in every 5 seconds, change content= x to refresh page after x seconds -->
5 </head>
Refresh Div/Span on HTML page after specific time:
In this part we will use JQuery to perform the task, as its provides few of the best options that can
help us.
Suppose you have a div with ID as result similar to following:
1 <div id="result"></div>
Then JQuery code will be as follows:
1 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
2 <script>
3 function autoRefresh_div()
4 {
5 $("#result").load("load.html");// a function which will load data from other file after x seconds
6 }
7
8 setInterval('autoRefresh_div()', 5000); // refresh div after 5 secs
9 </script>
Similarly you can use $.ajax() or $.post() etc instead of load() function and put the response in a div
or a span.
<script>
$(document).ready(function () {
$('#txtCountry').typeahead({
$.ajax({
url: "server.php",
dataType: "json",
type: "POST",
result($.map(data,
function (item) {
return item;
}));
});
}
});
});
</script>
The following PHP script receives the Typeahead input as the SELECT query
parameter. This will be bound to the query statement to get the related
country name that starts with the query string. This data will be encoded in
JSON format and return to the Typehead source attribute.
<?php
$keyword = strval($_POST['query']);
$search_param = "{$keyword}%";
$sql->bind_param("s",$search_param);
$sql->execute();
$result = $sql->get_result();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$countryResult[] = $row["country_name"];
}
echo json_encode($countryResult);
$conn->close();
?>
</body>
</html>
In this step we create three forms to create, edit and delete file.In first form user
have to enter file name to create new file.In second form user have to enter file
name and text to add in that file.In third form user have to enter file name to
delete that file.You may also like delete multiple records from MySQL using PHP.
if(isset($_POST['edit_file']))
{
$file_name=$_POST['file_name'];
$write_text=$_POST['edit_text'];
$folder="files/";
$ext=".txt";
$file_name=$folder."".$file_name."".$ext;
$edit_file = fopen($file_name, 'w');
fwrite($edit_file, $write_text);
fclose($edit_file);
}
if(isset($_POST['delete_file']))
{
$file_name=$_POST['file_name'];
$folder="files/";
$ext=".txt";
$file_name=$folder."".$file_name."".$ext;
unlink($file_name);
}
?>
In this step we create three isset() function to do three different file operations
like create a file, edit existing file and delete a file.In first isset() function we get
file name entered by the user to create file with that name we specify '.txt' file
extension you can specify any extension or you can ask from user also then we
use fopen function to create file and then using fclose function to close that
file.See fopen is used for both purposes creating and editing a file.In third isset()
function we get file name to delete entered by the user then we use unlink
function to delete that file from folder.You may also like add,edit and delete rows
from table dynamically.
Css auto hide div after 5 seconds
han defining for each browser Jquery is better.
setTimeout(function() {
$('.success').slideUp("slow");
}, 5000);
});
Drag and Drop feature makes web page user-friendly and provides a nice User
Interface for the web application. jQuery UI provides an easy way to add draggable
functionality on DOM element. This tutorial shows you the uses of jQuery drag and
drop feature to sort the list elements.
If we want to control the display order of images in the list, image order needs to be
stored in the database. In this tutorial, we’ll provide a more interactive way to implement
the images reorder functionality. Here we’ll explain how to add jQuery drag and drop
feature to rearrange images order and save images display order to the MySQL
database. You can use this functionality for managing images gallery, managing users
list or any other useful place.
Our example script helps to implement dynamic drag and drop reorder images using
jQuery, Ajax, PHP and MySQL. Using our scripts you can also implement the drag and
drop reorder list, rows or sorting elements.
Before you begin, take a look at the folder and files structure to build drag and drop
reorder images functionality using jQuery, Ajax, PHP and MySQL.
db.php
orderUpdate.php
index.php
style.css
images/
To store uploaded images information with display order, a table is required in MySQL
database. The following SQL creates images table with some basic required fields in
the database.
DB Class (db.php)
The DB class handles all the database related works. Specify your database host
($dbHost), username ($dbUsername), password ($dbPassword), and name
($dbName). The DB class contains two methods to fetch and update images data.
<?php
class DB{
//database configuration
private $dbHost = "localhost";
private $dbUsername = "root";
private $dbPassword = "";
private $dbName = "codexworld";
private $imgTbl = 'images';
function __construct(){
if(!isset($this->db)){
// Connect to the database
$conn = new mysqli($this->dbHost, $this->dbUsername, $this-
>dbPassword, $this->dbName);
if($conn->connect_error){
die("Failed to connect with MySQL: " . $conn->connect_error);
}else{
$this->db = $conn;
}
}
}
function getRows(){
$query = $this->db->query("SELECT * FROM ".$this-
>imgTbl." ORDER BY img_order ASC");
if($query->num_rows > 0){
while($row = $query->fetch_assoc()){
$result[] = $row;
}
}else{
$result = FALSE;
}
return $result;
}
function updateOrder($id_array){
$count = 1;
foreach ($id_array as $id){
$update = $this->db->query("UPDATE ".$this-
>imgTbl." SET img_order = $count WHERE id = $id");
$count ++;
}
return TRUE;
}
}
?>
Update Images Order (orderUpdate.php)
The order_update.php file receive the current images order from the index.php through
Ajax. The images IDs string breaks into array and pass to the DB class to update the
images reorder.
<?php
//include database class
include_once 'db.php';
$db = new DB();
The index.php file display the images and allow the user to reorder images by drag and
drop.
JavaScript
Include the jQuery and jQuery UI library.
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-
ui.min.js"></script>
The following jQuery codes are used to enable the jQuery sortable() features and
implement the drag & drop functionality. When save request is submitted by the user,
current images order send to the orderUpdate.php file using Ajax for update images
order.
<script>
$(document).ready(function(){
$('.reorder_link').on('click',function(){
$("ul.reorder-photos-list").sortable({ tolerance: 'pointer' });
$('.reorder_link').html('save reordering');
$('.reorder_link').attr("id","save_reorder");
$('#reorder-helper').slideDown('slow');
$('.image_link').attr("href","javascript:void(0);");
$('.image_link').css("cursor","move");
$("#save_reorder").click(function( e ){
if( !$("#save_reorder i").length ){
$(this).html('').prepend('<img src="images/refresh-
animated.gif"/>');
$("ul.reorder-photos-list").sortable('destroy');
$("#reorder-helper").html( "Reordering Photos - This could take a
moment. Please don't navigate away from this page."
).removeClass('light_box').addClass('notice notice_error');
var h = [];
$("ul.reorder-photos-list li").each(function() {
h.push($(this).attr('id').substr(9)); });
$.ajax({
type: "POST",
url: "orderUpdate.php",
data: {ids: " " + h + ""},
success: function(){
window.location.reload();
}
});
return false;
}
e.preventDefault();
});
});
});
</script>
PHP & HTML
Initially, all the images are listed from the database using PHP and DB class. Once the
reorder link is clicked, drag & drop feature is enabled for reorder.
<?php
//include database class
include_once 'db.php';
$db = new DB();
?>
<div>
<a href="javascript:void(0);" class="btn outlined mleft_no reorder_link"
id="save_reorder">reorder photos</a>
<div id="reorder-helper" class="light_box" style="display:none;">1. Drag
photos to reorder.<br>2. Click 'Save Reordering' when finished.</div>
<div class="gallery">
<ul class="reorder_ul reorder-photos-list">
<?php
//Fetch all images from database
$images = $db->getRows();
if(!empty($images)){
foreach($images as $row){
?>
<li id="image_li_<?php echo $row['id']; ?>" class="ui-sortable-
handle"><a href="javascript:void(0);" style="float:none;" class="image_link"><img
src="images/<?php echo $row['img_name']; ?>" alt=""></a></li>
<?php } } ?>
</ul>
</div>
</div>
style.css
This file contains some CSS code, which is used to styling the image gallery and links.
.reorder_link {
color: #3675B4;
border: solid 2px #3675B4;
border-radius: 3px;
text-transform: uppercase;
background: #fff;
font-size: 18px;
padding: 10px 20px;
margin: 15px 15px 15px 0px;
font-weight: bold;
text-decoration: none;
transition: all 0.35s;
-moz-transition: all 0.35s;
-webkit-transition: all 0.35s;
-o-transition: all 0.35s;
white-space: nowrap;
}
.reorder_link:hover {
color: #fff;
border: solid 2px #3675B4;
background: #3675B4;
box-shadow: none;
}
#reorder-helper{margin: 18px 10px;padding: 10px;}
.light_box {
background: #efefef;
padding: 20px;
margin: 10px 0;
text-align: center;
font-size: 1.2em;
}
Database Structure
This database consists of two tables, country and city
country table
1 +-------+-------------+------+-----+---------+---------------+
2 | Field | Type | Null | Key | Default | Extra |
3 +-------+-------------+------+-----+---------+---------------+
4 | id | int(5) | NO | PRI | NULL |auto_increment |
5 | name | varchar(30) | NO | | NULL | |
+-------+-------------+------+-----+---------+---------------+
6
city table
1
+------------+-------------+------+-----+---------+----------------+
2 | Field | Type | Null | Key | Default | Extra |
3 +------------+-------------+------+-----+---------+----------------+
4 | id | int(5) | NO | PRI | NULL | auto_increment |
5 | name | varchar(30) | NO | | NULL | |
| id_country | int(5) | NO | MUL | NULL | |
6 +------------+-------------+------+-----+---------+----------------+
7
and this is table relationship that needs to be connected in our sample Dynamic Dependent Select
Box
selectbox.php
This PHP file is used as an html form and also execute client side programming, which is jQuery
to perform dynamic dependent select box
<html>
1 <head>
2 <script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
3 <script type="text/javascript" src="js/jquery-ui-1.8.17.custom.min.js"></script
4
5 <script type="text/javascript">
6 $(document).ready(function(){
7
8
$("#country").change(function(){
9 var country=$("#country").val();
10 $.ajax({
11 type:"post",
12 url:"getcity.php",
13 data:"country="+country,
success:function(data){
14 $("#city").html(data);
15 }
16 });
17 });
});
18 </script>
19 </head>
20 <body>
21 Country :
22 <select name="country" id="country">
<option>-select your country-</option>
23 <?php
24 include "db.php";
25 $result=mysql_query("SELECT id,name from country order by name");
26 while($country=mysql_fetch_array($result)){
27
echo "<option value=$country[id]>$country[name]</option>";
28
29
} ?>
30 </select>
31
32
33 City :
34 <select name="city" id="city">
<option>-select your city-</option>
35 </select>
36 </body>
37 </html>
38
39
40
41
42
43
44
getcity.php
1
<?php
2 include "db.php";
3
4 $country=$_POST["country"];
5 $result=mysql_query("select id,name FROM city where id_country='$country' ");
6 while($city=mysql_fetch_array($result)){
7 echo"<option value=$city[id]>$city[name]</option>";
8
}
9 ?>
10
db.php
1 <?php
2 mysql_connect("localhost","root","");
3 mysql_select_db("php_dependentselectbox");
4 ?>
Screenshot
Dynamic Star Rating with PHP and
jQuery
In this PHP tutorial, we are going to list database records and add a dynamic
star rating to those records by using jQuery star rating script. We are having a
group of stars for each database record. When we add the rating to a record,
an AJAX call will be sent store the current rating to the database.
This PHP code is for reading Database results and adding stars for each.
<?php
require_once("dbcontroller.php");
$result = $db_handle->runQuery($query);
if(!empty($result)) {
?>
<tr>
<td valign="top">
for($i=1;$i<=5;$i++) {
$selected = "";
$selected = "selected";
?>
<?php } ?>
<ul>
</div>
</td>
</tr>
<?php }} ?>
In this example code, we have same four jQuery functions. But, we have added
additional code for calling PHP via AJAX on clicking rating stars. And also, we
have added database row id reference to the “li” selectors for the unique
identification of the rating. The functions are,
function highlightStar(obj,id) {
removeHighlight(id);
$('.demo-table #tutorial-'+id+'
li').each(function(index) {
$(this).addClass('highlight');
return false;
});
function removeHighlight(id) {
$('.demo-table #tutorial-'+id+'
li').removeClass('selected');
$('.demo-table #tutorial-'+id+'
li').removeClass('highlight');
function addRating(obj,id) {
$('.demo-table #tutorial-'+id+'
li').each(function(index) {
$(this).addClass('selected');
$('#tutorial-'+id+' #rating').val((index+1));
if(index == $('.demo-table #tutorial-'+id+'
li').index(obj)) {
return false;
});
$.ajax({
url: "add_rating.php",
data:'id='+id+'&rating='+$('#tutorial-'+id+'
#rating').val(),
type: "POST"
});
function resetRating(id) {
if($('#tutorial-'+id+' #rating').val() != 0) {
$('.demo-table #tutorial-'+id+'
li').each(function(index) {
$(this).addClass('selected');
if((index+1) == $('#tutorial-'+id+'
#rating').val()) {
return false;
});
}
}
This PHP code will be executed via an AJAX request. This code runs an update
query by receiving id and current rating from AJAX.
<?php
require_once("dbcontroller.php");
$result = $db_handle->updateQuery($query);
?>
1 </p>
To connect with database I have created a separate “dbconn.php” file which contains
hostname, mysql username and mysql password to connect with database.
1 </p>
2 <?php
3 $mysql_db_hostname = "localhost";
4 $mysql_db_user = "root";
5 $mysql_db_password = "12345";
6 $mysql_db_database = "dynamicfield";
7
$connection =
8 mysql_connect($mysql_db_hostname, $mysql_db_user, $mysql_db_password) or die(
"Could not connect database");
Our main index.php file contains jQuery and PHP code to submit data into database.
To retrieve data entered in newly generated field I have used array “dynfield[]” and
then using for each loop pass the retrieved data into sql query.
You can use this code in your projects and share this tutorial among your friends. A lot
can be done in this code like validation of fields and validation of entered data. Different
type of fields like drop down, radio buttons etc can be added in the same way.
Jquery Validation is a powerful jQuery plugin to perform form validation in client side. Why
we choose client side validation?, because this approach is more lightweight since no request is
sent to the server. We need 2 JavaScript files to make jquery validation, first the core of jquery
and the second is the plugin it self.
1
2
3
4 <body>
5 <form id="formMahasiswa" method="post">
6 <table>
<tr>
7 <td>Nama</td>
8 <td><input type="text" name="nama" id="nama" class="required"/></td>
9 <td><label for="nama" class="error"></label></td>
10 </tr>
11 <tr>
<td>Nim</td>
12 <td><input type="text" name="nim" id="nim" class="required" /></td>
13 <td><label for="nim" class="error"></label></td>
14 </tr>
15 <tr>
16 <td>Alamat</td>
<td><input type="text" name="alamat" id="alamat" class="required" /></td>
17 <td><label for="alamat" class="error"></label></td>
18 </tr>
19 <tr>
20 <td>Agama</td>
<td><input type="text" name="agama" id="agama" class="required" /></td>
21 <td><label for="agama" class="error"></label></td>
22 </tr>
23 <tr>
24 <td>Jenis Kelamin</td>
25 <td><input type="radio" name="jenis_kelamin" id="jenis_kelamin" value="Laki-L
<input type="radio" name="jenis_kelamin" id="jenis_kelamin" value="Peremp
26 </td>
27 <td><label for="jenis_kelamin" class="error"></label></td>
28 </tr>
29 <tr>
<td></td>
30 <td><input type="submit" value="Submit"/></td>
31 </tr>
32 </table>
33 </form>
34 </body>
35
36
37
Note at line 6 and 7. We add class=”required” to every input that needs to be validated. We also
add label refers to input element to show the error message.
here is the script to do validation, simple enough
1 <script type="text/javascript">
2 $(document).ready(function(){
3 $("#formMahasiswa").validate();
4 });
</script>
5
Next, we create css styling to make the error messages colored in red.
1 <style type="text/css">
2 .error{
3 color: red;
4 }
</style>
5
Now try to submit the form without typing anything in the input elements. Here’s what we get
As we can see from image above, the error messages are still in default format. We can
customize by adding title attribute on input elements.
1 <td><input type="text" name="nama" id="nama" class="required" title="Nama Harus Diisi"/>
Jquery Validation plugin can be used for all types of inputs such as checkboxes, text areas, select
and others. We can also perform more complex validation like input must have 5-10 characters
long, must be email, must be a Url and etc.
In this step we create a form to send text entered by the user to storing the text
and generating QR code.
In this step we get text entered by the user to store in QR code and then we
include qrlib.php file which is the main file to generate code then we specify
folder in which we were going to store QR code as a image and give a name to
that image then we use QRcode::png() predefined function to generate QR code.
That's all, this is how to generate QR code using PHP and HTML.You can
customize this code further as per your requirement. And please feel free to give
comments on this tutorial.
We create an input text and button to facilitate users to search tutorials. Also we create
a list to display the search results.
1
<body>
2 <div id="container">
5 <ul id="result"></ul>
</div>
6
</body>
7
JavaScript
We specify so that when users click button or press enter key the process of searching
data begins. Here we use click and keyup event. As usual we use ajax function to
perform data change in the background.
To limit when users input nothing but click the button or press enter, we create simple
checking using if.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/j
1
<script type="text/javascript">
2
$(document).ready(function(){
3
4
function search(){
5
6
var title=$("#search").val();
7
8
if(title!=""){
9 $("#result").html("<img alt="ajax search" src='ajax-loader.gi
10 $.ajax({
11 type:"post",
12 url:"search.php",
data:"title="+title,
13
success:function(data){
14
$("#result").html(data);
15
$("#search").val("");
16
}
17
});
18 }
19
20
21
22 }
23
24 $("#button").click(function(){
search();
25
});
26
27
$('#search').keyup(function(e) {
28
if(e.keyCode == 13) {
29
search();
30
}
31 });
32 });
33 </script>
34
35
36
PHP Code
Database configuration file used in this tutorial. Adjust the server location, username,
password and database name
file : db.php
1 <?php
4 ?>
This is the code that searchs articles based on the user input and brings the results
in ajax searchway.Once again we performs checking using if to ensure when no data
found it will give an output “No Tutorial Found”
file : search.php
1 <?php
2 include "db.php";
4 $title=$_POST["title"];
6
$result=mysql_query("SELECT * FROM wp_posts where post_title like '%$title%' and pos
7
$found=mysql_num_rows($result);
8
9
if($found>0){
10
while($row=mysql_fetch_array($result)){
11
echo "<li>$row[post_title]</br>
12
<a href=$row[guid]>$row[guid]</a></li>";
13 }
14 }else{
16 }
// ajax search
17
?>
18
19
Css
<style type="text/css">
#container{
width:800px;
margin:0 auto;
}
#search{
width:700px;
padding:10px;
#button{
display: block;
width: 100px;
height:30px;
background: #91B2FA;
ul{
margin-left:-40px;
ul li{
list-style-type: none;
height: 50px;
li:hover{
background: #A592E8;
}
a{
text-decoration: none;
font-size: 18px;
</style>
The following example code shows you how to pass PHP array to JavaScript
using json_encode() function.
The $phpArray variable holds a multidimensional PHP array which needs to pass to
JavaScript.
<?php
$phpArray = array(
array('name'=>'John Doe', 'email'=>'john@gmail.com'),
array('name'=>'Merry Moe', 'email'=>'merry@gmail.com')
);
?>
function getUserInfo(userObj){
alert(userObj[0].name);
}
But nowadays, PHP make this very simple you can do any kind of image
manipulation you want with the help of its GD Library. In this tutorial we will
show you an easy and quick way to PHP image resize before uploading it to the
server.
Before we start you have the knowledge of how to upload image to the server if
you dont know please see our php image uploadtutorial and then start.
There are many other libraries which are also used for image manipulation like
Imagick, jQuery Plugins etc.
You can manipulate the image in just two simple steps:-
1. Make a HTML form to upload the image
2. Recieve The Image And Manipulate
</body>
</html>
You can do javascript form validation to make your code more secure.We submit
the data from this HTML form to resize_image.phpwhere we do image
manipulation.
$folder = "/xampp/htdocs/images/";
// It loads the images we use jpeg function you can use any function like
imagecreatefromjpeg
$thumb = imagecreatetruecolor( $newwidth, $newheight );
$source = imagecreatefromjpeg( $resize_image );
// 100 Represents the quality of an image you can set and ant number in place of 100.
Default quality is 75
$out_image=addslashes(file_get_contents($resize_image));
// After that you can insert the path of the resized image into the database
?>
For more details and PHP image manipulations functions you can learn from this
site.
That's all, this is how to do image resize using PHP before uploading with the
help of PHP GD Library, HTML and MySQL.
You can customize this code further as per your requirement. And please feel
free to give comments on this tutorial.
Table Structure
1 +----------+-------------+------+-----+---------+-------+
2 | Field | Type | Null | Key | Default | Extra |
3 +----------+-------------+------+-----+---------+-------+
4 | username | varchar(50) | NO | PRI | NULL | |
5 | password | varchar(32) | NO | | NULL | |
+----------+-------------+------+-----+---------+-------+
6
username.php
this is the html form and jQuery function
1 <html>
2 <head>
<script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
3 <!-- <script type="text/javascript" src="js/jquery-ui-1.8.17.custom.min.js"></s
4
5 <script type="text/javascript">
6
7 $(document).ready(function(){
8 $("#username").change(function(){
9 $("#message").html("<img src='ajax-loader.gif' /> checking...");
10
11
var username=$("#username").val();
12
13 $.ajax({
14 type:"post",
15 url:"check.php",
16 data:"username="+username,
17 success:function(data){
if(data==0){
18 $("#message").html("<img src='tick.png' /> Username availa
19 }
20 else{
21 $("#message").html("<img src='cross.png' /> Username alrea
}
22 }
23 });
24
25 });
26
27 });
28
29 </script>
30 </head>
31
<body>
32
33 <table>
34 <tr>
35 <td>Username</td>
36 <td>:</td>
<td><input type="text" name="username" id="username"/><td>
37 <td id="message"><td>
38 </tr>
39
40 <tr>
41 <td>Password</td>
42 <td>:</td>
<td><input type="text" name="password" id="password" /><td>
43 </tr>
44 </table>
45 </body>
46 </html>
47
48
49
50
51
52
53
check.php
1
<?php
2
3 mysql_connect("localhost","root","");
4 mysql_select_db("php_usernamelivecheck");
5
6 $username=$_POST["username"];
7 $query=mysql_query("SELECT * from user where username='$username' ");
8
9 $find=mysql_num_rows($query);
10
echo $find;
11
12 ?>
13
Try to type some letters in the username text field and then change focus of the cursor on the
password field. Checking is on the way
If the username you wrote is not yet registered, the system will tell you that it is available to be
used.
However if you pick up username that have been registered the system will tell you too
function loaddata()
{
var name=document.getElementById( "username" );
if(name)
{
$.ajax({
type: 'post',
url: 'loaddata.php',
data: {
user_name:name,
},
success: function (response) {
// We get the element having id of display_info and put the response inside it
$( '#display_info' ).html(response);
}
});
}
else
{
$( '#display_info' ).html("Please Enter Some Words");
}
}
</script>
</head>
<body>
</body>
</html>
You can do validation to make your code more secure or you can view our How
to do validation before and after submitting the formtutorial.
<?php
$name = $_POST['user_name'];
$host = 'localhost';
$user = 'root';
$pass = ' ';
mysql_select_db('student');
$selectdata = " SELECT age,course FROM student_info WHERE name LIKE '$name%' ";
$query = mysql_query($selectdata);
while($row = mysql_fetch_array($query))
{
echo "<p>".$row['age']."</p>";
echo "<p>".$row['course']."</p>";
}
}
?>
Whatever this page echo's it display on the displaydata.html page.You can also
view load more results from database using ajax.
That's all, this is how to load data from database without page refresh using Ajax
and jQuery.You can customize this code further as per your requirement. And
please feel free to give comments on this tutorial.
Autocomplete Php is a cool technic you should learn to make your website or you web
application looks cool and also user friendly. As you might have known, autocomplete gives a
user a list of nearly same data with what he or she is looking for.
In this tutorial we will learn together about how to use this technic in our sample web app using
PHP and JQuery. Before we go to the tutorial, first we make a list of our need to build this app.
Our application will only have one page, that is a form where user try to input a data. In this form
the magic happens. When user inputs data, an autocomplete will show up to help him/her fulfill
the form. We will create 2 PHP files, one for the form and one that is responsible in supplying
data into an autocomplete. We also have a database with a table named “student” that has 2
columns, “id” and “name”.
Now, let’s make our hand dirty by writing the code :D. Prepare your self!
First we make our database tabel. Here is the structure of our “student” tabel
1 +-------+-------------+------+-----+---------+----------------+
2 | Field | Type | Null | Key | Default | Extra |
3 +-------+-------------+------+-----+---------+----------------+
4 | id | int(5) | NO | PRI | NULL | auto_increment |
5 | name | varchar(50) | NO | | NULL | |
+-------+-------------+------+-----+---------+----------------+
6
Next we make our main form page.
autocomplete.php
1 <html>
2 <head>
3 <script type="text/javascript"
4 src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></scrip
<script type="text/javascript"
5 src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js">
6 <link rel="stylesheet" type="text/css"
7 href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui
8
9 <script type="text/javascript">
$(document).ready(function(){
10 $("#name").autocomplete({
11 source:'getautocomplete.php',
12 minLength:1
13 });
14 });
</script>
15 </head>
16
17 <body>
18
19 <form method="post" action="">
20 Name : <input type="text" id="name" name="name" />
</form>
21
22
23 </body>
24 <html>
25
26
27
note that we bind the “name” which is the id of the text input into jquery function
in $(“#name”). In autocomplete function inside jquery, we use two
properties, source and minLength. Source is the file that supplies our data to be shown in
autocomplete. minLength is used to specify the number of character a user has to type to activate
the auto completion.
Now we make our “supplier” file.
getautocomplete.php
1
2 <?php
3 mysql_connect("localhost","root","");
4 mysql_select_db("php_autocomplete");
5
$term=$_GET["term"];
6
7 $query=mysql_query("SELECT * FROM student where name like '%".$term."%' order by nam
8 $json=array();
9
10 while($student=mysql_fetch_array($query)){
11 $json[]=array(
12 'value'=> $student["name"],
'label'=>$student["name"]." - ".$student["id"]
13 );
14 }
15
16 echo json_encode($json);
17
18 ?>
19
That code should be easy to understand. The things you have to get attention are the $json array
values, ‘value’ and ‘label’. ‘value’ is as the value of the input text, where ‘label’ is used as label
text in auto complete. You will know what i mean later.
Now insert some data to your database as a sample. Then navigate your browser to
localhost/yourprojectname/getautocomplete.php
you should see the data in json format
don’t worry about the warning text, it’s only because we didn’t supply the variable with a value.
Try to make some changes by navigating your browser to
localhost/yourprojectname/getautocomplete.php?term=whatyouwanttosearch
Change the whatyouwanttosearch with some name of students and now you should
understand
Now is the time to test our app. Go to
localhost/yourprojectname/autocomplete.php>
and type some letters. Here’s what i got
What you see in pop up auto complete is “label” we talked about some mintues ago. Click one of
those data and what inside text input is “value” we talked above.
PHP CRUD Operations without Page
Refresh using jQuery Ajax MySQL
CRUD stands for Create, Read, Update and Delete database records. Add, Edit,
Update, and Delete functionality is used almost every web project in PHP. You’ve done
it many times, but today we’ll show you the more user-friendly way to implement CRUD
functionality in PHP.
Here we’ll implement PHP CRUD operations without page refresh using jQuery, Ajax,
and MySQL. The functionality of the example script would be read, add, update, and
delete the records from MySQL database.
In this example script, we’ll fetch the users data from the database and display the user
data list with add link, edit link, and delete link. By these links user can add new data to
the database, update previously inserted data and delete the data from the database.
All operations will happen on a single page without page refresh. Also, bootstrap table
structure will be used for styling the list, form fields, and links.
Let’s start the step-by-step guide on creating a CRUD application with PHP using
jQuery Ajax MySQL. Before you begin, take a look at the files structure of CRUD
application.
For this example script, we’ll create a simple table ( users ) with some basic columns
DB class handles all the operations related to the database. For example, connect with
the database, insert, update and delete record from the database. You need to change
the $dbHost , $dbUsername , $dbPassword , and $dbName variables value as per the
database credentials.
<?php
/*
* DB Class
* This class is used for database related (connect, insert, update, and delete)
operations
* @author CodexWorld.com
* @url http://www.codexworld.com
* @license http://www.codexworld.com/license
*/
class DB{
private $dbHost = "localhost";
private $dbUsername = "root";
private $dbPassword = "";
private $dbName = "codexworld";
/*
* Returns rows from the database based on the conditions
* @param string name of the table
* @param array select, where, order_by, limit and return_type conditions
*/
public function getRows($table,$conditions = array()){
$sql = 'SELECT ';
$sql .= array_key_exists("select",$conditions)?$conditions['select']:'*';
$sql .= ' FROM '.$table;
if(array_key_exists("where",$conditions)){
$sql .= ' WHERE ';
$i = 0;
foreach($conditions['where'] as $key => $value){
$pre = ($i > 0)?' AND ':'';
$sql .= $pre.$key." = '".$value."'";
$i++;
}
}
if(array_key_exists("order_by",$conditions)){
$sql .= ' ORDER BY '.$conditions['order_by'];
}
$result = $this->db->query($sql);
/*
* Insert data into the database
* @param string name of the table
* @param array the data for inserting into the table
*/
public function insert($table,$data){
if(!empty($data) && is_array($data)){
$columns = '';
$values = '';
$i = 0;
if(!array_key_exists('created',$data)){
$data['created'] = date("Y-m-d H:i:s");
}
if(!array_key_exists('modified',$data)){
$data['modified'] = date("Y-m-d H:i:s");
}
foreach($data as $key=>$val){
$pre = ($i > 0)?', ':'';
$columns .= $pre.$key;
$values .= $pre."'".$val."'";
$i++;
}
$query = "INSERT INTO ".$table." (".$columns.") VALUES (".$values.")"
;
$insert = $this->db->query($query);
return $insert?$this->db->insert_id:false;
}else{
return false;
}
}
/*
* Update data into the database
* @param string name of the table
* @param array the data for updating into the table
* @param array where condition on updating data
*/
public function update($table,$data,$conditions){
if(!empty($data) && is_array($data)){
$colvalSet = '';
$whereSql = '';
$i = 0;
if(!array_key_exists('modified',$data)){
$data['modified'] = date("Y-m-d H:i:s");
}
foreach($data as $key=>$val){
$pre = ($i > 0)?', ':'';
$colvalSet .= $pre.$key."='".$val."'";
$i++;
}
if(!empty($conditions)&& is_array($conditions)){
$whereSql .= ' WHERE ';
$i = 0;
foreach($conditions as $key => $value){
$pre = ($i > 0)?' AND ':'';
$whereSql .= $pre.$key." = '".$value."'";
$i++;
}
}
$query = "UPDATE ".$table." SET ".$colvalSet.$whereSql;
$update = $this->db->query($query);
return $update?$this->db->affected_rows:false;
}else{
return false;
}
}
/*
* Delete data from the database
* @param string name of the table
* @param array where condition on deleting data
*/
public function delete($table,$conditions){
$whereSql = '';
if(!empty($conditions)&& is_array($conditions)){
$whereSql .= ' WHERE ';
$i = 0;
foreach($conditions as $key => $value){
$pre = ($i > 0)?' AND ':'';
$whereSql .= $pre.$key." = '".$value."'";
$i++;
}
}
$query = "DELETE FROM ".$table.$whereSql;
$delete = $this->db->query($query);
return $delete?true:false;
}
}
userAction.php
This file handles the requests coming from the view file ( index.php ) and returns the
add insert the record in the database and return the status.
edit updates the record in the database and returns the status.
delete deletes the record from the database and returns the status.
<?php
include 'DB.php';
$db = new DB();
$tblName = 'users';
if(isset($_POST['action_type']) && !empty($_POST['action_type'])){
if($_POST['action_type'] == 'data'){
$conditions['where'] = array('id'=>$_POST['id']);
$conditions['return_type'] = 'single';
$user = $db->getRows($tblName,$conditions);
echo json_encode($user);
}elseif($_POST['action_type'] == 'view'){
$users = $db->getRows($tblName,array('order_by'=>'id DESC'));
if(!empty($users)){
$count = 0;
foreach($users as $user): $count++;
echo '<tr>';
echo '<td>#'.$count.'</td>';
echo '<td>'.$user['name'].'</td>';
echo '<td>'.$user['email'].'</td>';
echo '<td>'.$user['phone'].'</td>';
echo '<td><a href="javascript:void(0);" class="glyphicon glyphico
n-
edit" onclick="editUser(\''.$user['id'].'\')"></a><a href="javascript:void(0);" c
lass="glyphicon glyphicon-
trash" onclick="return confirm(\'Are you sure to delete data?\')?userAction(\'del
ete\',\''.$user['id'].'\'):false;"></a></td>';
echo '</tr>';
endforeach;
}else{
echo '<tr><td colspan="5">No user(s) found......</td></tr>';
}
}elseif($_POST['action_type'] == 'add'){
$userData = array(
'name' => $_POST['name'],
'email' => $_POST['email'],
'phone' => $_POST['phone']
);
$insert = $db->insert($tblName,$userData);
echo $insert?'ok':'err';
}elseif($_POST['action_type'] == 'edit'){
if(!empty($_POST['id'])){
$userData = array(
'name' => $_POST['name'],
'email' => $_POST['email'],
'phone' => $_POST['phone']
);
$condition = array('id' => $_POST['id']);
$update = $db->update($tblName,$userData,$condition);
echo $update?'ok':'err';
}
}elseif($_POST['action_type'] == 'delete'){
if(!empty($_POST['id'])){
$condition = array('id' => $_POST['id']);
$delete = $db->delete($tblName,$condition);
echo $delete?'ok':'err';
}
}
exit;
}
index.php
This is the main view file which is visible to the user. In this single page, the user can do
all the CRUD operations. For better understanding we’ve divided this script into two
parts.
<link rel="stylesheet"
href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script
src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script
>
getUsers() function is used to get the users data from the userAction.php file using
ajax and render the received HTML in the user data list.
function getUsers(){
$.ajax({
type: 'POST',
url: 'userAction.php',
data: 'action_type=view&'+$("#userForm").serialize(),
success:function(html){
$('#userData').html(html);
}
});
}
the userAction.php file using ajax and give the response to the user.
function userAction(type,id){
id = (typeof id == "undefined")?'':id;
var statusArr = {add:"added",edit:"updated",delete:"deleted"};
var userData = '';
if (type == 'add') {
userData =
$("#addForm").find('.form').serialize()+'&action_type='+type+'&id='+id;
}else if (type == 'edit'){
userData = $("#editForm").find('.form').serialize()+'&action_type='+type;
}else{
userData = 'action_type='+type+'&id='+id;
}
$.ajax({
type: 'POST',
url: 'userAction.php',
data: userData,
success:function(msg){
if(msg == 'ok'){
alert('User data has been '+statusArr[type]+' successfully.');
getUsers();
$('.form')[0].reset();
$('.formData').slideUp();
}else{
alert('Some problem occurred, please try again.');
}
}
});
}
editUser() function is used to get the particular user data from the userAction.php file
function editUser(id){
$.ajax({
type: 'POST',
dataType:'JSON',
url: 'userAction.php',
data: 'action_type=data&id='+id,
success:function(data){
$('#idEdit').val(data.id);
$('#nameEdit').val(data.name);
$('#emailEdit').val(data.email);
$('#phoneEdit').val(data.phone);
$('#editForm').slideDown();
}
});
}
HTML:
Initially already inserted users data is fetched from the users table and listed with edit &
delete links. At the top of the user list, add link would be displayed. The add and edit
form HTMl would be visible if add or edit link is clicked.
<div class="container">
<div class="row">
<div class="panel panel-default users-content">
<div class="panel-heading">Users <a href="javascript:void(0);"
class="glyphicon glyphicon-plus" id="addLink"
onclick="javascript:$('#addForm').slideToggle();">Add</a></div>
<div class="panel-body none formData" id="addForm">
<h2 id="actionLabel">Add User</h2>
<form class="form" id="userForm">
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" name="name"
id="name"/>
</div>
<div class="form-group">
<label>Email</label>
<input type="text" class="form-control" name="email"
id="email"/>
</div>
<div class="form-group">
<label>Phone</label>
<input type="text" class="form-control" name="phone"
id="phone"/>
</div>
<a href="javascript:void(0);" class="btn btn-warning"
onclick="$('#addForm').slideUp();">Cancel</a>
<a href="javascript:void(0);" class="btn btn-success"
onclick="userAction('add')">Add User</a>
</form>
</div>
<div class="panel-body none formData" id="editForm">
<h2 id="actionLabel">Edit User</h2>
<form class="form" id="userForm">
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" name="name"
id="nameEdit"/>
</div>
<div class="form-group">
<label>Email</label>
<input type="text" class="form-control" name="email"
id="emailEdit"/>
</div>
<div class="form-group">
<label>Phone</label>
<input type="text" class="form-control" name="phone"
id="phoneEdit"/>
</div>
<input type="hidden" class="form-control" name="id"
id="idEdit"/>
<a href="javascript:void(0);" class="btn btn-warning"
onclick="$('#editForm').slideUp();">Cancel</a>
<a href="javascript:void(0);" class="btn btn-success"
onclick="userAction('edit')">Update User</a>
</form>
</div>
<table class="table table-striped">
<thead>
<tr>
<th></th>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
<th>Action</th>
</tr>
</thead>
<tbody id="userData">
<?php
include 'DB.php';
$db = new DB();
$users = $db-
>getRows('users',array('order_by'=>'id DESC'));
if(!empty($users)): $count = 0; foreach($users as $user):
$count++;
?>
<tr>
<td><?php echo '#'.$count; ?></td>
<td><?php echo $user['name']; ?></td>
<td><?php echo $user['email']; ?></td>
<td><?php echo $user['phone']; ?></td>
<td>
<a href="javascript:void(0);" class="glyphicon
glyphicon-edit" onclick="editUser('<?php echo $user['id']; ?>')"></a>
<a href="javascript:void(0);" class="glyphicon
glyphicon-trash" onclick="return confirm('Are you sure to delete
data?')?userAction('delete','<?php echo $user['id']; ?>'):false;"></a>
</td>
</tr>
<?php endforeach; else: ?>
<tr><td colspan="5">No user(s) found......</td></tr>
<?php endif; ?>
</tbody>
</table>
</div>
</div>
</div>
CSS:
CSS for .none class is required and the other CSS is optional.
/* required style*/
.none{display: none;}
/* optional styles */
table tr th, table tr td{font-size: 1.2rem;}
.row{ margin:20px 20px 20px 20px;width: 100%;}
.glyphicon{font-size: 20px;}
.glyphicon-plus{float: right;}
a.glyphicon{text-decoration: none;}
a.glyphicon-trash{margin-left: 10px;}
Conclusion
In this tutorial, we’re trying to make PHP CRUD operations more simple and user-
friendly. You can share your thought to improve this script or the DB class.
Live Demo
Note: Don’t use this script into your live projects, the motive of the script is to just provide basic
ideas to the beginners for learning, if you want to use this feature in the live projects then you
should focus on following points:
Tutorial Features:
1. Insert records into MySQL Database
2. Read the records from Database and list
3. Update the record
4. Delete the record.
Technologies Used:
1. HTML
2. PHP with MySQL
3. jQuery
4. Bootstrap
5. CSS
6. JSON
Before starting let’s download basic lib files needed : ( if you already having this lib files you
can use your existing files )
6 ) ENGINE = MYISAM ;
Take a note: test.users – where test is the database name and users is a table name.
Users Table Structure
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
9 </head>
10 <body>
11
13
14 <!-- /Content Section -->
15
18
21
24 </body>
25 </html>
So we have our basic file ready to go, now let’s add button to open add new record popup along
with basic formatting like to have page heading and record container, refer following code:
2 <div class="container">
3 <div class="row">
4 <div class="col-md-12">
6 <div class="pull-right">
8 </div>
9 </div>
10 </div>
11 <div class="row">
12 <div class="col-md-12">
13 <h4>Records:</h4>
14 <div class="records_content"></div>
15 </div>
16 </div>
17 </div>
The above code is actually part of our index.php file, if you look at it, you will notice we have
application heading and Add New Record button which
refers to add_new_record_modal modal popup. we also have records_content div, this div
is going to display the data rendering from Ajax, we are going to see that next.
Now we need to add modal popup, we are using bootstrap modal popups here, go a head and use
following code to include popup in the index.php page.
If you’re not familiar with Bootstrap no worries you just need to copy this code later on you can
read about it, so now go ahead and add below modal to you index.php page.
1
<!-- Bootstrap Modal - To Add New Record -->
2
<!-- Modal -->
3
<div class="modal fade" id="add_new_record_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
4
<div class="modal-dialog" role="document">
5
<div class="modal-content">
6
<div class="modal-header">
7
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-
hidden="true">×</span></button>
8
<h4 class="modal-title" id="myModalLabel">Add New Record</h4>
9
</div>
10
<div class="modal-body">
11
12
13 <div class="form-group">
16 </div>
17
18 <div class="form-group">
21 </div>
22
23 <div class="form-group">
26 </div>
27
28 </div>
29 <div class="modal-footer">
32 </div>
33 </div>
34 </div>
</div>
If you notice in the above code we have popup called add_new_record_modal which includes
different input field in the ‘modal-body’ tag. so we have first name, last name and email address
here.
modal-footer – that’s the important part of the popup to call action such as addRecord, we
have button with JS method call with onclick event.
let’s save index.page page and try to load on browser.
Index.php Page:
Next Step is to create Add New Record and Read Records feature.
We have seen the basic setup of our application now we are going to look at the CREATE and
READ operation. That is also called as INSERT and SELECT operation in MySQL, basically to
create new record in the table.
js/script.js
1 // Add Record
2 function addRecord() {
3 // get values
8 // Add record
9 $.post("ajax/addRecord.php", {
10 first_name: first_name,
11 last_name: last_name,
12 email: email
15 $("#add_new_record_modal").modal("hide");
16
18 readRecords();
19
21 $("#first_name").val("");
22 $("#last_name").val("");
23 $("#email").val("");
24 });
25 }
26
27 // READ records
28 function readRecords() {
30 $(".records_content").html(data);
31 });
32 }
If you notice in the above code, we have addRecord() function which is doing following
operation: Get the Values from the input fields and send it to addRecord.php file using Ajax call.
After that it’s closing the popup and reading records using readRecords() that is next function
to it.
1 <?php
3 {
5 include("db_connection.php");
7 // get values
8 $first_name = $_POST['first_name'];
9 $last_name = $_POST['last_name'];
10 $email = $_POST['email'];
11
14 exit(mysqli_error($con));
15 }
17 }
18 ?>
Process: Accept the values from the POST variablea and insert record into the database.
1 <?php
3 include("db_connection.php");
7 <tr>
8 <th>No.</th>
9 <th>First Name</th>
10 <th>Last Name</th>
11 <th>Email Address</th>
12 <th>Update</th>
13 <th>Delete</th>
14 </tr>';
15
17
19 exit(mysqli_error($con));
20 }
21
23 if(mysqli_num_rows($result) > 0)
24 {
25 $number = 1;
26 while($row = mysqli_fetch_assoc($result))
27 {
28 $data .= '<tr>
29 <td>'.$number.'</td>
30 <td>'.$row['first_name'].'</td>
31 <td>'.$row['last_name'].'</td>
32 <td>'.$row['email'].'</td>
33 <td>
35 </td>
36 <td>
38 </td>
39 </tr>';
40 $number++;
41 }
42 }
43 else
44 {
47 }
48
49 $data .= '</table>';
50
51 echo $data;
52 ?>
In both files above I have included the db_connection.php file using php include()function,
this files is use to define our database connection string. It is better practice to add repetitive code
in the separate file, let’s create the file.
1 <?php
3 // Connection variables
6 $password = ""; // MySQL user password (if password is not set for your root user then keep it empty )
8
9 // Connect to MySQL Database
11
12 // Check connection
13 if ($con->connect_error) {
15 }
16
17 ?>
Test the application: try to add new record, you will need to be able to add the record and have it
listed, have a look on below screen shoot I have added few dummy records:
1 $(document).ready(function () {
4 });
1 function DeleteUser(id) {
2 var conf = confirm("Are you sure, do you really want to delete User?");
3 if (conf == true) {
4 $.post("ajax/deleteUser.php", {
5 id: id
6 },
9 readRecords();
10 }
11 );
12 }
13 }
1 <?php
2 // check request
3 if(isset($_POST['id']) && isset($_POST['id']) != "")
4 {
6 include("db_connection.php");
8 // get user id
9 $user_id = $_POST['id'];
10
11 // delete User
14 exit(mysqli_error($con));
15 }
16 }
17 ?>
UPDATE Feature
How does it work?
Go ahead and use the following html code and add to the index.php page, next to the existing
modal popup.
1
<!-- Modal - Update User details -->
2
<div class="modal fade" id="update_user_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
3
<div class="modal-dialog" role="document">
4
<div class="modal-content">
5
<div class="modal-header">
6
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-
hidden="true">×</span></button>
7
<h4 class="modal-title" id="myModalLabel">Update</h4>
8
</div>
9
<div class="modal-body">
10
11
<div class="form-group">
12
<label for="update_first_name">First Name</label>
13
<input type="text" id="update_first_name" placeholder="First Name" class="form-control"/>
14
</div>
15
16
<div class="form-group">
17
<label for="update_last_name">Last Name</label>
18
<input type="text" id="update_last_name" placeholder="Last Name" class="form-control"/>
19
</div>
20
21
<div class="form-group">
22
<label for="update_email">Email Address</label>
23
<input type="text" id="update_email" placeholder="Email Address" class="form-control"/>
24
</div>
25
26
27 </div>
28 <div class="modal-footer">
32 </div>
33 </div>
34 </div>
35 </div>
1 function GetUserDetails(id) {
3 $("#hidden_user_id").val(id);
4 $.post("ajax/readUserDetails.php", {
5 id: id
6 },
11 $("#update_first_name").val(user.first_name);
12 $("#update_last_name").val(user.last_name);
13 $("#update_email").val(user.email);
14 }
15 );
17 $("#update_user_modal").modal("show");
18 }
1 <?php
3 include("db_connection.php");
5 // check request
7 {
8 // get User ID
9 $user_id = $_POST['id'];
10
14 exit(mysqli_error($con));
15 }
16 $response = array();
17 if(mysqli_num_rows($result) > 0) {
19 $response = $row;
20 }
21 }
22 else
23 {
24 $response['status'] = 200;
26 }
28 echo json_encode($response);
29 }
30 else
31 {
32 $response['status'] = 200;
34 }
Update Action:
Add another JS function called UpdateUserDetails() in to the script.js file:
1 function UpdateUserDetails() {
2 // get values
8 var id = $("#hidden_user_id").val();
11 $.post("ajax/updateUserDetails.php", {
12 id: id,
13 first_name: first_name,
14 last_name: last_name,
15 email: email
16 },
19 $("#update_user_modal").modal("hide");
21 readRecords();
22 }
23 );
24 }
1 <?php
5 // check request
6 if(isset($_POST))
7 {
8 // get values
9 $id = $_POST['id'];
10 $first_name = $_POST['first_name'];
11 $last_name = $_POST['last_name'];
12 $email = $_POST['email'];
13
15 $query = "UPDATE users SET first_name = '$first_name', last_name = '$last_name', email = '$email' WHERE id = '$id'";
17 exit(mysqli_error($con));
18 }
19 }
Folder Structure:
Folder Structure
Complete Source code of script.js file:
1 // Add Record
2 function addRecord() {
3 // get values
8 // Add record
9 $.post("ajax/addRecord.php", {
10 first_name: first_name,
11 last_name: last_name,
12 email: email
15 $("#add_new_record_modal").modal("hide");
16
18 readRecords();
19
21 $("#first_name").val("");
22 $("#last_name").val("");
23 $("#email").val("");
24 });
25 }
26
27 // READ records
28 function readRecords() {
31 });
32 }
33
34
35 function DeleteUser(id) {
36 var conf = confirm("Are you sure, do you really want to delete User?");
37 if (conf == true) {
38 $.post("ajax/deleteUser.php", {
39 id: id
40 },
43 readRecords();
44 }
45 );
46 }
47 }
48
49 function GetUserDetails(id) {
51 $("#hidden_user_id").val(id);
52 $.post("ajax/readUserDetails.php", {
53 id: id
54 },
60 $("#update_last_name").val(user.last_name);
61 $("#update_email").val(user.email);
62 }
63 );
65 $("#update_user_modal").modal("show");
66 }
67
68 function UpdateUserDetails() {
69 // get values
73
75 var id = $("#hidden_user_id").val();
76
78 $.post("ajax/updateUserDetails.php", {
79 id: id,
80 first_name: first_name,
81 last_name: last_name,
82 email: email
83 },
86 $("#update_user_modal").modal("hide");
89 }
90 );
91 }
92
93 $(document).ready(function () {
96 });
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>PHP and MySQL CRUD
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <title>PHP and MySQL CRUD Operations Demo</title>
6
7 <!-- Bootstrap CSS File -->
8 <link rel="stylesheet" type="text/css" href="bootstrap-3.3.5-dist/css/bootstrap.css"/>
9 </head>
10 <body>
11
12 <!-- Content Section -->
13 <div class="container">
14 <div class="row">
15 <div class="col-md-12">
16 <h1>Demo: PHP and MySQL CRUD Operations using Jquery</h1>
17 </div>
18 </div>
19 <div class="row">
20 <div class="col-md-12">
21 <div class="pull-right">
22 <button class="btn btn-success" data-toggle="modal" data-target="#add_new_record_modal">Add New Record</button>
23 </div>
24 </div>
25 </div>
26 <div class="row">
27 <div class="col-md-12">
28 <h3>Records:</h3>
29
30 <div class="records_content"></div>
31 </div>
32 </div>
33 </div>
34 <!-- /Content Section -->
35
36
37 <!-- Bootstrap Modals -->
38 <!-- Modal - Add New Record/User -->
39 <div class="modal fade" id="add_new_record_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
40 <div class="modal-dialog" role="document">
41 <div class="modal-content">
42 <div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-
hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Add New Record</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="first_name">First Name</label>
<input type="text" id="first_name" placeholder="First Name" class="form-control"/>
</div>
<div id="file_div">
<?php
$folder = "images/";
if ($dir = opendir($folder))
{
while (($file = readdir($dir)) !== false)
{
echo "<p>".$file."</p>";
echo "<form method='post' action='delete_file.php'>";
echo "<input type='hidden' name='file_name' value='".$file."'>";
echo "<input type='submit' name='delete_file' value='Delete File'>";
echo "</form>";
}
closedir($dir);
}
?>
</div>
</div>
</body>
</html>
In this step we read all the files from images folder and create a delete button for
each file to delete that file from folder.We use opendir() function to open the
folder for file reading and then use while() loop and readdir() function to read all
the files and then we use closedir() function to close the directory.You may also
like remove file extension using htaccess.
That's all, this is how to read and delete file from folder using PHP.You can
customize this code further as per your requirement. And please feel free to give
comments on this tutorial.
Step 1.Make a Text file and add some HTML code for reading
We make a Text file and save it with a name content.text
<h1>Sample Text File</h1>
<p>This is used by our PHP file to read HTML content</p>
<br>
<table align=center>
<tr>
<td>Suresh</td><td>PHP Developer</td>
</tr>
<tr>
<td>Pooja</td><td>Web Designer</td>
</tr>
<tr>
<td>Amit</td><td>HTML Developer</td>
</tr>
<tr>
<td>Ram</td><td>Data Analyst</td>
</tr>
</table>
In this step we create a text file and write some HTML content for reading.You
can also add inline styling to your HTML code to display content in style.You may
also like read and write csv file using PHP.
Step 2.Make a PHP file to read HTML content from a text file
We make a PHP file and save it with a name read_html.php
<html>
<body>
<div id="wrapper">
<?php
$myfile = fopen("content.txt", "r") or die("Unable to open file!");
echo fread($myfile,filesize("content.txt"));
fclose($myfile);
?>
</div>
</body>
</html>
In this step we use PHP fopen function to open our 'content.txt' file in read mode
and then use fread() function to display file content.You may also like read and
delete file from folder using PHP.
That's all, this is how to read HTML content from text file using PHP .You can
customize this code further as per your requirement. And please feel free to give
comments on this tutorial.
<p class="img_wrapper">
<img src="images/image1.jpg">
<span><input type="button" value="PLAY"></span>
</p>
<p class="img_wrapper">
<img src="images/image2.jpg">
<span><input type="button" value="PAUSE"></span>
</p>
<p class="img_wrapper">
<img src="images/image3.jpg">
<span><input type="button" value="RESUME"></span>
</p>
</div>
</div>
</body>
</html>
In this step we add three images and then create three buttons to show.We use
images because we want to show button when user hover on images you can
use anything you want in place of images and wrap both image and button in <p>
tag it is must to have a container for image and button other wise your button will
not going to be show over image. You may also like enable disable submit button
using jQuery.
In this step we use simple styling to show button over image when user hover on
image. One of the most important thing we use is position:relative in
img_wrapper and position:absolute in span so that our button will be shown
inside the image container. You may also like display text over image.
That's all, this is how to show button on hover using HTML and CSS.You can
customize this code further as per your requirement. And please feel free to give
comments on this tutorial.
Simple And Best Delete
Confirmation Message Using
jQuery HTML And CSS.
To Create Delete Confirmation Message It Takes Two steps:-
1. Make a HTML file and write markup and script for Delete Confirmation
Message
2. Make a CSS file and define styling for Delete Confirmation Message
Step 1.Make a HTML file and write markup and script for Delete
Confirmation Message
We make a HTML file and save it with a name message.html
<html>
<head>
<link rel="stylesheet" type="text/css" href="message_style.css">
<script type="text/javascript" src="jquery.js">
<script type="text/javascript">
$(document).ready(function(){
$("#test_delete").click(function(){
message();
});
$("#cancel").click(function(){
hide();
});
});
function message()
{
$("#delete_message").slideDown();
}
function hide()
{
$("#delete_message").slideUp();
}
</script>
</head>
<body>
<div id="delete_message">
<h2>Are You Sure You Want To Delete This</h2>
<input type="button" value="Delete" id="delete">
<input type="button" value="Cancel" id="cancel">
</div>
<h1>Simple And Best Delete Confirmation Message Using jQuery,HTML And CSS</h1>
<center>
<input type="button" id="test_delete" value="Click To Test Delete Confirmation
Message">
</center>
</body>
</html>
In this step we make a confirmation message div which is hidden and on this we
made two buttons both are just for testing purpose and we make a third button to
show the confirmation message.We use
jQuery slideUp(); and slideDown(); functions for showing and hiding message
with animation you can use any kind of effect.You may also like simple
notification bar using jQuery.
Step 2.Make a CSS file and define styling for Delete Confirmation Message
We make a CSS file and save it with name message_style.css.
body
{
margin:0px;
padding:0px;
background-color:#E6E6E6;
font-family:helvetica;
}
#delete_message
{
display:none;
position:fixed;
top:0px;
width:100%;
height:150px;
background-color:#5882FA;
text-align:center;
}
#delete_message h2
{
color:#0431B4;
}
#delete,#cancel
{
border:none;
background:none;
width:100px;
height:40px;
font-size:18px;
border-radius:5px;
border:2px solid white;
margin:10px;
color:#CED8F6;
}
h1
{
text-align:center;
margin-top:200px;
color:#819FF7;
width:600px;
margin-left:200px;
}
#test_delete
{
border:none;
background:none;
width:400px;
height:50px;
font-size:18px;
border-radius:5px;
border:2px solid #819FF7;
margin:10px;
color:#045FB4;
}
You can connect to any existing database from which you want to get the data. In
this step we use sample database named "demo".
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
mysql_select_db('demo');
?>
if($_GET['pageno'])
{
$page_value = $_GET['pageno'];
if($page_value > 1)
{
$offset = ($page_value - 1) * $page_result;
}
}
$page_value = $_GET['pageno'] it is the value of the page when the user wants
to change the page and click the pagination page number. Then if the
$page_value is greater than 1 we change the $offset value to the value of this
code ($page_value - 1) * $page_result.
Then we query the database we select details from student_info table and limit
the results returned by the query for more details of limit clause visit our MySQL
clause tutorial.You may also like load more results from database using ajax.
while($row = mysql_fetch_array($result))
{
echo $row[' student_name '];
echo $row[' student_rollno '];
echo $row[' student_course '];
}
if($_GET['pageno'] > 1)
{
echo "<a href = 'samepage.php?pageno = ".($_GET['pageno'] - 1)." '> Prev </a>";
}
for($i = 1 ; $i <= $num ; $i++)
{
echo "<a href = "samepage.php?pageno = ". $i ." >". $i ."</a>";
}
if($num! = 1)
{
echo "<a href = 'samepage.php?pageno = ".($_GET['pageno'] + 1)." '> Next </a>";
}
?>
In this step we get the results from student_info table, in student_info table we
have three columns student_name, student_rollno, student_course.
The first if statement display the Prev page link if the pageno is greater than 1
and then we display all the pagination links using for loop upto the $num value.
The second if statement display the Next page link if the pageno is not equal to
1. Remember always do proper form validation before and after submitting the
form.
That's all, this is how to create and implete the basic PHP Pagination with
MySQL. You can customize this code further as per your requirement. And
please feel free to give comments on this tutorial.
And if you like this tutorials please share it with your friends via Email or Social
Media.
Ok, let's proceed this way, we are doing from scratch so we require to create
database configration file that way we can use that file in many other file. so let's
create api directory and create db_config.php file in api directory and put bellow
code:
api/db_config.php
<?php
?>
In Above file please make sure to check your batabase configuration because
could problem you find somewhere. that's way i tell you check it two times. It was
just for your kind information.
Step 2: Create index.php File
Ok, now we also require to create index.php file in our root directory. In this file i
added "url" variable in js for site root URL. You can update also with your site
URL. so let's create index.php file and put bellow content in that file.
index.php
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript"
src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.j
s"></script>
<script type="text/javascript"
src="https://cdnjs.cloudflare.com/ajax/libs/twitter-
bootstrap/4.0.0-alpha/js/bootstrap.min.js"></script>
<script type="text/javascript"
src="https://cdnjs.cloudflare.com/ajax/libs/twbs-
pagination/1.3.1/jquery.twbsPagination.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/1000hz-
bootstrap-validator/0.11.5/validator.min.js"></script>
<script type="text/javascript"
src="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/js/toastr.
min.js"></script>
<link
href="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toast
r.min.css" rel="stylesheet">
<script type="text/javascript">
<script src="/js/item-ajax.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="pull-left">
</div>
<div class="pull-right">
Create Item
</button>
</div>
</div>
</div>
<thead>
<tr>
<th>Title</th>
<th>Description</th>
<th width="200px">Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title"
id="myModalLabel">Create Item</h4>
</div>
<div class="modal-body">
<form data-toggle="validator"
action="api/create.php" method="POST">
<div class="form-group">
<label
class="control-label" for="title">Title:</label>
<input type="text"
name="title" class="form-control" data-error="Please enter
title." required />
<div class="help-
block with-errors"></div>
</div>
<div class="form-group">
<label
class="control-label" for="title">Description:</label>
<textarea
name="description" class="form-control" data-error="Please enter
description." required></textarea>
<div class="help-
block with-errors"></div>
</div>
<div class="form-group">
<button
type="submit" class="btn crud-submit btn-success">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title"
id="myModalLabel">Edit Item</h4>
</div>
<div class="modal-body">
<form data-toggle="validator"
action="api/update.php" method="put">
<div class="form-group">
<label
class="control-label" for="title">Title:</label>
<input type="text"
name="title" class="form-control" data-error="Please enter
title." required />
<div class="help-
block with-errors"></div>
</div>
<div class="form-group">
<label
class="control-label" for="title">Description:</label>
<textarea
name="description" class="form-control" data-error="Please enter
description." required></textarea>
<div class="help-
block with-errors"></div>
</div>
<div class="form-group">
<button
type="submit" class="btn btn-success crud-submit-
edit">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
$( document ).ready(function() {
var page = 1;
var current_page = 1;
var total_page = 0;
var is_ajax_fire = 0;
manageData();
function manageData() {
$.ajax({
dataType: 'json',
url: url+'api/getData.php',
data: {page:page}
}).done(function(data){
total_page = Math.ceil(data.total/10);
current_page = page;
$('#pagination').twbsPagination({
totalPages: total_page,
visiblePages: current_page,
page = pageL;
if(is_ajax_fire != 0){
getPageData();
}
});
manageRow(data.data);
is_ajax_fire = 1;
});
function getPageData() {
$.ajax({
dataType: 'json',
url: url+'api/getData.php',
data: {page:page}
}).done(function(data){
manageRow(data.data);
});
}
/* Add new Item table row */
function manageRow(data) {
});
$("tbody").html(rows);
$(".crud-submit").click(function(e){
e.preventDefault();
var form_action = $("#create-
item").find("form").attr("action");
$.ajax({
dataType: 'json',
type:'POST',
data:{title:title, description:description}
}).done(function(data){
$("#create-
item").find("input[name='title']").val('');
$("#create-
item").find("textarea[name='description']").val('');
getPageData();
$(".modal").modal('hide');
});
}else{
});
/* Remove Item */
$("body").on("click",".remove-item",function(){
var id = $(this).parent("td").data('id');
$.ajax({
dataType: 'json',
type:'POST',
data:{id:id}
}).done(function(data){
c_obj.remove();
getPageData();
});
});
/* Edit Item */
$("body").on("click",".edit-item",function(){
var id = $(this).parent("td").data('id');
var title =
$(this).parent("td").prev("td").prev("td").text();
$("#edit-item").find("input[name='title']").val(title);
$("#edit-
item").find("textarea[name='description']").val(description);
$("#edit-item").find(".edit-id").val(id);
});
$(".crud-submit-edit").click(function(e){
e.preventDefault();
var id = $("#edit-item").find(".edit-id").val();
$.ajax({
dataType: 'json',
type:'POST',
data:{title:title, description:description,id:id}
}).done(function(data){
getPageData();
$(".modal").modal('hide');
});
}else{
});
});
<?php
require 'db_config.php';
$num_rec_per_page = 5;
$result = $mysqli->query($sql);
while($row = $result->fetch_assoc()){
$json[] = $row;
}
$data['data'] = $json;
$result = mysqli_query($mysqli,$sqlTotal);
$data['total'] = mysqli_num_rows($result);
echo json_encode($data);
?>
api/create.php
<?php
require 'db_config.php';
$post = $_POST;
VALUES ('".$post['title']."','".$post['description']."')";
$result = $mysqli->query($sql);
$sql = "SELECT * FROM items Order by id desc LIMIT 1";
$result = $mysqli->query($sql);
$data = $result->fetch_assoc();
echo json_encode($data);
?>
api/update.php
<?php
require 'db_config.php';
$id = $_POST["id"];
$post = $_POST;
,description = '".$post['description']."'
WHERE id = '".$id."'";
$result = $mysqli->query($sql);
$result = $mysqli->query($sql);
$data = $result->fetch_assoc();
echo json_encode($data);
?>
api/delete.php
<?php
require 'db_config.php';
$id = $_POST["id"];
$result = $mysqli->query($sql);
echo json_encode([$id]);
?>
php -S localhost:8000
http://localhost:8000
Step 2.Make a PHP file and define markup and script for Star Rating System
We make a PHP file and save it with a name ratings.php
<html>
<head>
<link rel="stylesheet" type="text/css" href="rating_style.css">
<script type="text/javascript">
function change(id)
{
var cname=document.getElementById(id).className;
var ab=document.getElementById(id+"_hidden").value;
document.getElementById(cname+"rating").innerHTML=ab;
for(var i=ab;i>=1;i--)
{
document.getElementById(cname+i).src="star2.png";
}
var id=parseInt(ab)+1;
for(var j=id;j<=5;j++)
{
document.getElementById(cname+j).src="star1.png";
}
}
</script>
</head>
<body>
<h1>Star Rating System Using PHP and JavaScript</h1>
<?php
$host="localhost";
$username="root";
$password="";
$databasename="sample";
$connect=mysql_connect($host,$username,$password);
$db=mysql_select_db($databasename);
while($row=mysql_fetch_array($select_rating))
{
$phpar[]=$php;
$aspar[]=$asp;
$jspar[]=$jsp;
}
$total_php_rating=(array_sum($phpar)/$total);
$total_asp_rating=(array_sum($aspar)/$total);
$total_jsp_rating=(array_sum($jspar)/$total);
?>
<div class="div">
<p>ASP (<?php echo $total_asp_rating;?>)</p>
<input type="hidden" id="asp1_hidden" value="1">
<img src="images/star1.png" onmouseover="change(this.id);" id="asp1"
class="asp">
<input type="hidden" id="asp2_hidden" value="2">
<img src="images/star1.png" onmouseover="change(this.id);" id="asp2"
class="asp">
<input type="hidden" id="asp3_hidden" value="3">
<img src="images/star1.png" onmouseover="change(this.id);" id="asp3"
class="asp">
<input type="hidden" id="asp4_hidden" value="4">
<img src="images/star1.png" onmouseover="change(this.id);" id="asp4"
class="asp">
<input type="hidden" id="asp5_hidden" value="5">
<img src="images/star1.png" onmouseover="change(this.id);" id="asp5"
class="asp">
</div>
<div class="div">
<p>JSP (<?php echo $total_jsp_rating;?>)</p>
<input type="hidden" id="jsp1_hidden" value="1">
<img src="images/star1.png" onmouseover="change(this.id);" id="jsp1"
class="jsp">
<input type="hidden" id="jsp2_hidden" value="2">
<img src="images/star1.png" onmouseover="change(this.id);" id="jsp2"
class="jsp">
<input type="hidden" id="jsp3_hidden" value="3">
<img src="images/star1.png" onmouseover="change(this.id);" id="jsp3"
class="jsp">
<input type="hidden" id="jsp4_hidden" value="4">
<img src="images/star1.png" onmouseover="change(this.id);" id="jsp4"
class="jsp">
<input type="hidden" id="jsp5_hidden" value="5">
<img src="images/star1.png" onmouseover="change(this.id);" id="jsp5"
class="jsp">
</div>
</form>
</body>
</html>
In this step we made 3 div element to rate three programming language
PHP,ASP,JSP and put the star image in them whenever the user wants to give
ratings user has to put the mouse over the star and we call a change function
which get the star id and change the star image to coloured means.You may also
like live voting system using Ajax and PHP.
In javascript change(id) function we get the id of star which the user put the
mouse over that and then we make 2 for loops one is to blink all the previous star
including him and second one is to blank all the next star excluding him.
And after that we use connect to the database and get Total votes and there
rating by getting total ratings per language and then divide then divide each
rating with total votes.You can also view our create captcha system using
PHP tutorial to add captcha on rating system.
Step 3.Make a PHP file to store the ratings for Star Rating System
We make a PHP file named insert_rating.php
<?php
if(isset($_POST['submit_rating']))
{
$host="localhost";
$username="root";
$password="";
$databasename="sample";
$connect=mysql_connect($host,$username,$password);
$db=mysql_select_db($databasename);
$php_rating=$_POST['phprating'];
$asp_rating=$_POST['asprating'];
$jsp_rating=$_POST['jsprating'];
$insert=mysql_query("insert into rating
values('','$php_rating','$asp_rating','jsp_rating')");
}
?>
In this step we get the value and store them to database.You can do validation to
make your code more secure or you can view our How to do validation before
and after submitting the form tutorial.
Step 4.Make a CSS file and define styling for Star Rating System
We make a CSS file and save it with name rating_style.css.
body
{
background-color:#0B4C5F;
font-family:helvetica;
text-align:center;
}
h1
{
margin-top:20px;
font-size:40px;
color:#E6E6E6;
}
#total_votes
{
font-size:30px;
color:#FE2E2E;
font-weight:bold;
}
.div
{
border:1px solid #E6E6E6;
clear:both;
margin-top:20px;
height:100px;
width:400px;
padding:10px;
margin-left:300px;
border-radius:3px;
}
.div p
{
margin:0px;
font-size:20px;
text-align:left;
color:#E6E6E6;
}
img
{
margin-top:10px;
width:50px;
height:50px;
float:left;
}
input[type="submit"]
{
border:none;
background:none;
background-color:#585858;
width:100px;
height:50px;
color:white;
border-radius:3px;
font-size:17px;
margin-top:20px;
}
Thats all, this is how to create a Star Rating System Using PHP and
JavaScript.You can customize this code further as per your requirement. And
please feel free to give comments on this tutorial.
Sharing webpage to the social media is used to gain enormous reach for our
webpage. So adding social icons to the webpage is very important to let the
readers share your article. Readers want to share the website at any moment
while they are reading your page. So, it would be better to give high visibility
for the social share icons of your page.
In this tutorial, we create sticky social share icons in the sidebar to be visible at
any moment while scrolling. We use jQuery to get the CSS properties of the
social share icon element and manipulating its position on page scroll. On the
page scroll, the code will compare the position of the window and the social
icon element. Based on the comparison, it will change the social icons position
to make it sticky. In a previous tutorial, we have seen how to create floating
contact form on page scroll using jQuery.
view demo
The following code shows the HTML for the webpage with the sticky social
icons in the sidebar. The social icons in the left sidebar are displayed after the
list of menu items.
<div>
<div class="left-side-bar">
<ul>
<li>Integer Vitae</li>
<li>Vivamus Lacinia</li>
<li>Donec Rutrum</li>
<li>Sed Lacinia</li>
<li>Morbi ut Turpis</li>
<li>Rhoncus Nunc</li>
<li>Sed id Turpis</li>
<li>Vestibulum Commodo</li>
<li>Pellentesque Nec</li>
<li>Fusce Amet</li>
<li>Donec Sem</li>
<li>Praesent Iaculis</li>
<li>Tellus Tincidunt</li>
<li>Nunc Mollis</li>
<li>Quisque Urna</li>
</ul>
<div class="social-icon">
<img src="icon/facebook-social.png"
<img src="icon/linkedin-social.png"
src="icon/email-social.png" title="Share on
Email" />
</div>
</div>
<div class="main-content">
eu dolor.</p>
</div>
</div>
<style>
body {
font-family: Arial;
.left-side-bar {
width: 250px;
float: left;
}
.main-content {
float: left;
width: 80%;
height:100px;
font-size: 1.2em;
line-height: 70px;
color: #919c9e;
.left-side-bar ul li {
padding: 15PX;
background: #bdcacc;
margin: 0px;
COLOR: #5c6567;
.left-side-bar ul {
list-style: none;
padding: 0PX;
}
.social-icon {
padding: 20px;
.social-icon img {
</style>
The following jQuery code is used to make the social share icons in the
sidebar to be sticky. The code gets the window scroll top and the Social icons
top position and compares them on page scroll event. When the top of the
scrolling window exceeds than that of the social icons, the code manipulates
the social icons element top position to make it sticky.
<script>
$(document).ready(function(){
$( window ).scroll(function() {
$( ".social-icon" ).css("position",
"relative");
});
});
</script>
The following screenshot shows the web page output with the sticky social
share icons in the sidebar.
Live Demo
It is very interesting and easy to code. Use it to enrich your web application.
The Html
This is our html file. Simple enough, just using textarea, button and a span to
dynamically change the number of remaining characters.
1
<body>
2 <div id="box">
3 <p>(Maximum Allowed Characters : 160)</p>
4 <p><textarea id="area" rows="10" cols="40"></textarea></p>
5 <span id="message"> 160 </span> Characters Remaining
6 <input type="button" id="tweet" value="Tweet"/>
</div>
7 <body>
8
The Java Script
On the first load page of our count remaining character using jquery, we set the button
to be disabled and also when the characters is greater than 160 or equal or less than 0.
There are two other methods that are invoked when characters are greater than 160 or
equal or less than 0, it is a method to make the text inside textarea become line through
and a method to make the number of remaining characters become red.
1
<script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
2 <script type="text/javascript">
3 $(document).ready(function(){
4 $("#tweet").attr("disabled","disabled");
5 $("#area").keyup(function(){
var chars=$(this).val().length;
6
7 $("#message").text(160-chars);
8
9 if(chars > 160 || chars <=0){
10 $("#tweet").attr("disabled","disabled");
11 $("#message").addClass("minus");
12 $(this).css("text-decoration","line-through");
13
}else{
14 $("#tweet").removeAttr("disabled");
15 $("#message").removeClass("minus");
16 $(this).css("text-decoration","");
17 }
18 });
});
19 </script>
20
21
22
The CSS
This Css make our web application looks beautiful, not only a white page. .minus class
is added and removed dynamically when application is running. It depends on
remaining characters, whether remaining characters are greater than 160 or equal to or
less than zero like i said above.
1
2
3 <style type="text/css">
#box{
4
width:400px;
5 height:230px;
6 background-color: pink;
7 margin:50 auto 0;
8 padding-top:20px;
padding-left:40px ;
9 }
10
11 p{
12 margin: 0;
13 }
14
15 #area{
margin-bottom: 10px;
16 }
17
18 #tweet{
19 margin-left: 130px;
20 }
21
.minus{
22 color: red;
23 }
24 </style>
25
26
Here’s some screenshot of our web app
Upload multiple images using jQuery, Ajax and
PHP
We’ve received many requests from followers for publishing the tutorial on How to upload
multiple images without refreshing the page. We’ll try to simplify the multiple images upload
without refreshing the page. In this simple tutorial, we’ll discuss multiple images uploads using
jQuery, Ajax and PHP. Using our script, you can upload multiple images at once without page
refresh using jQuery, Ajax and PHP.
We’ll show you two ways to display images after upload. Once the images are uploaded to the
server via jQuery, you can display images without stored in a folder or stored in a folder. This
script is very short, easy and useful which can easily be implemented in your web projects.
Read the following step-by-step guide to understanding the whole process of Upload multiple
images using jQuery, Ajax and PHP. Also, you can see the live demo from the Demo link and
download the source code from the Download link at the end of the tutorial.
index.html File
index.html file contains some JavaScript and HTML codes. All codes are given below.
JavaScript Code:
At first include the two external JavaScript library
files, jquery.min.js and jquery.form.js . jquery.min.js is the main jQuery library and
another jquery.form.js file is used to submit the form with files for uploading using jQuery
Ajax.
Now write some JavaScript code for form submission and displaying the uploaded images.
<script type="text/javascript">
$(document).ready(function(){
$('#images').on('change',function(){
$('#multiple_upload_form').ajaxForm({
//display the uploaded images
target:'#images_preview',
beforeSubmit:function(e){
$('.uploading').show();
},
success:function(e){
$('.uploading').hide();
},
error:function(e){
}
}).submit();
});
});
</script>
HTML Code
Input file field name is defined as an array for accept multiple file name and also used multiple
attributes for multiple upload support.
Create div with target id which is defined at the above JavaScript code. The uploaded images
would be displayed at this div. Also you can change this div id, but remember that the JavaScript
target option value ( target:'#images_preview' ) will be same with this div id.
<div id="images_preview"></div>
upload.php file:
upload.php file contain some PHP codes for process the uploading and generates the images
view. There are two way to upload images and display the images.
One Way is to create a folder named uploads/ . Upload the images and stored in the folder.
<?php
$images_arr = array();
foreach($_FILES['images']['name'] as $key=>$val){
//upload and stored images
$target_dir = "uploads/";
$target_file = $target_dir.$_FILES['images']['name'][$key];
if(move_uploaded_file($_FILES['images']['tmp_name'][$key],$target_file)){
$images_arr[] = $target_file;
}
}
?>
You can upload the images and display the images without stored in the folder.
<?php
$images_arr = array();
foreach($_FILES['images']['name'] as $key=>$val){
//display images without stored
$extra_info = getimagesize($_FILES['images']['tmp_name'][$key]);
$images_arr[] = "data:" . $extra_info["mime"] . ";base64," . base64_encod
e(file_get_contents($_FILES['images']['tmp_name'][$key]));
}
?>
<?php
if(!empty($images_arr)){
foreach($images_arr as $image_src){ ?>
<ul>
<li >
<img src="<?php echo $image_src; ?>" alt="">
</li>
</ul>
<?php }
}
?>
Conclusion
This tutorial and script helps to upload multiple images using jQuery Ajax and PHP. If you’re
looking the advanced uploading feature in your web project, you can implement Drag and drop
file upload using Dropzone JS and PHP. Otherwise, for simple image upload, you can Upload an
image and create thumbnail using PHP.
<script type="text/javascript">
function validate()
{
var error="";
var name = document.getElementById( "name_of_user" );
if( name.value == "" )
{
error = " You Have To Write Your Name. ";
document.getElementById( "error_para" ).innerHTML = error;
return false;
}
else
{
return true;
}
}
</script>
</head>
<body>
</body>
</html>
You can do more validation on Client-Side as per your need to make your code
more secure.We submit the data from this HTML form to getdata.php where we
do Server-Side validation and then insert out data in database.You may also
like validate email and password using jQuery.
<?php
if( isset( $_POST['submit_form'] ) )
{
validate_data($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = strip_tags($data);
$data = htmlspecialchars($data);
$data = mysqli_real_escape_string($data);
return $data;
}
$host = 'localhost';
$user = 'root';
$pass = ' ';
You can do more validation on Server-Side as per your need to make your code
more secure.Use only MySQLi or PDO where possible because they are more
secure than MySQL.
You can also add google recaptcha in form to make your form more secure and
prevent from spamming.That's all, this is how to validate the form data before
and after submitting the form using JavaScript and PHP. You can customize this
code further as per your requirement. And please feel free to give comments on
this tutorial.