Friday, 17 March 2017

PRODUCT FORM USING PHP AJAX AND BOOTSTRAP

Database:

database name:product_database

tablename:product

field:
p_id
p_name
p_code

tablename:category

field:
c_id
c_name

tablename:product_category

field:
id(primary key)
product_id(forign key) with p_id
category_id(forign key) with c_id


index.php 


<!DOCTYPE html>
<html lang="en">
<head>
<title>PRODUCT</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="js/bootstrap.min.css">
<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script type="text/javascript" src="js/transaction.js"></script>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>

<div class="container">
<h2 class="text-center">PRODUCT</h2>
<form id="product" method="POST">
    <div class="form-group">
      <label for="name">Name:</label>
      <input id="name" type="text" name="name" class="form-control">
 <span id="error"></span>
    </div>
    <div class="form-group">
      <label for="code">code</label>
      <input id="code" type="number" name="code" class="form-control">
 <span id="error"></span>
    </div>

<div class="form-group">
<label for="category">Category</label>
<?php
include "conn.php";
$res = mysqli_query($con,"SELECT * FROM category");
while($row = mysqli_fetch_assoc($res))
{
?>
&nbsp;&nbsp;&nbsp;&nbsp;
<span><?php echo $row['c_name'] ?></span>
<input type="checkbox" id="<?php echo $row['c_id'];?>" name="cat[]" class="checkbox-inline" value=<?php echo $row['c_id']; ?> />
<?php
}
?>
</div>

<div class="form-group">
            <button id="add" name="add" type="button" class="btn btn-primary btn-md">ADD</button>
            <button id="resetform" name="reset" type="reset" value="Reset" class="btn btn-primary btn-md">Reset</button>
</div>

<div class="form-group">
<table id="display" class="table table-striped table-responsive">
<thead>
<tr>
<th>Update</th>
<th>Delete</th>
<th>Name</th>
<th>Code</th>
<th>Category</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</form>
</div>
</body>
</html>


conn.php


<?php  
$con=mysqli_connect("localhost","root","","product_database");
?>


view.php


<?php
include "conn.php";
?>
<?php 
$json = array(); 
$query = mysqli_query ($con, "SELECT P.p_id AS 'product_id', P.p_name AS 'product_name',P.p_code AS 'product_code', GROUP_CONCAT(C.c_name) AS 'category_name' FROM Product P LEFT JOIN product_category PC ON P.p_id = PC.product_id LEFT JOIN category C ON PC.category_id = C.c_id GROUP BY pc.product_id");
while($row = mysqli_fetch_assoc($query))     
{
$bus = array(
'p_id' => $row['product_id'],
'p_name' => $row['product_name'],
'p_code' => $row['product_code'],
'c_name' => $row['category_name'],
                        'result' => 'success'
);
array_push($json, $bus);
}
        $jsonstring = json_encode($json);
        echo $jsonstring;
?>


insert.php


<?php

include "conn.php";
?>
<?php

//name is set then execute belove code 
if (!empty($_POST['name'])) {
    $p_name = $_POST['name'];
    $p_code = $_POST['code'];
   
    //insert data in product table(name,code)
    mysqli_query($con, "insert into product values('','$p_name','$p_code')");

    //get last insert id from product table
    $p_id = mysqli_insert_id($con);

    //category is selected then execute belove code
    if (!empty($_POST['cat'])) {
        $category = $_POST['cat'];
        $c_name = array();

        //insert selected category in product_category table
        foreach ($category as $cid => $c_id) {
            mysqli_query($con, "insert into product_category (product_id,category_id)values('" . $p_id . "','" . $c_id . "')");
        }

        //using comma sepreted ids c_name select from category table
        $ids = implode(",", $category);
        $query_c = mysqli_query($con, "select c_name from category where c_id in ($ids)");

        //one by one c_name get from $query and store in one array variable
        while ($row = mysqli_fetch_assoc($query_c)) {
            $c_name[] = $row['c_name'];
        }

        //fetched array converted into comma sepreted value and pass into json
        $c_name = implode(',', $c_name);

        //pass the json data to ajax
        $data = array('result' => 'success', 'p_id' => $p_id, 'p_name' => $p_name, 'p_code' => $p_code, 'c_name' => $c_name);
        echo json_encode($data);
    }
    //category is unselected then execute belove code
    else {
        $c_name = "";
        //pass the json data to ajax
        $data = array('result' => 'success', 'p_id' => $p_id, 'p_name' => $p_name, 'p_code' => $p_code, 'c_name' => $c_name);
        echo json_encode($data);
    }
}
//name is blank then execute belove code
else {
    $ename = "name is required";
    $data = array('message' => $ename);
    echo json_encode($data);
}
?>


edit.php


<?php
include "conn.php";
?>
<?php  
$ids=$_POST['edit_id'];   //get the id of selected table row edit button
$c_id = array();
//get p_name & p_code from product database using specific table row id and store into $p_name & $p_code variable
$query_p = mysqli_query ($con, "SELECT p_name, p_code  FROM Product where p_id = '".$ids."'");
while($row = mysqli_fetch_assoc($query_p))     
{
$p_name = $row['p_name'];
$p_code = $row['p_code'];
}
//get category id from product_category database using specific table row id and store into $c_id array variable
$query_pc = mysqli_query($con,"SELECT category_id FROM product_category where product_id = '".$ids."'");
while($row = mysqli_fetch_assoc($query_pc))     
{
$c_id[] = $row['category_id'];
}
//if category is get from database
if(!empty($c_id))
{
//array($c_id) converted into comma sepreted category id and store into $c_id
$c_id = implode(',',$c_id);
//pass the json data to ajax
$data = array('result' => 'success', 'p_name' => $p_name, 'p_code' => $p_code, 'c_id' => $c_id);
echo json_encode($data);
}
//if category is not get from database
else{
//pass the json data to ajax
$data = array('p_name' => $p_name, 'p_code' => $p_code);
echo json_encode($data);
}
?>


update.php


<?php
include "conn.php";
?>
<?php 
//name is set then execute belove code 
if(!empty($_POST['name'])) 
{
$p_name=$_POST['name'];
$p_code=$_POST['code'];
$ids=$_POST['update_id'];   //get click edit button row id from form custom attribute update_id(get from ajax header)
//update value in product table(name,code) using ids
mysqli_query($con, "update product set p_name = '$p_name',p_code = '$p_code' where p_id = '".$ids."'");
//delete all old category value from product_category table using ids
mysqli_query($con,"delete from product_category where product_id = $ids");
//category is selected then execute belove code
if(!empty($_POST['cat']))
{
$category=$_POST['cat'];
$c_name = array();
//insert new selected category in product_category table using ids
foreach($category as $cid => $c_id)
{
                            mysqli_query($con,"insert into product_category (product_id,category_id)values('".$ids."','".$c_id."')");
}
//using comma sepreted id c_name select from category table
$ids = implode(",",$category);
$query_c = mysqli_query($con,"select c_name from category where c_id in ($ids)");
//one by one c_name get from $query and store in one array variable
while($row = mysqli_fetch_assoc($query_c))     
{
$c_name[] = $row['c_name'];
}
//fetched array converted into comma sepreted value and pass into json
$c_name = implode(',',$c_name);
//pass the json data to ajax
$data = array('result'=>'success', 'p_name' => $p_name, 'p_code' => $p_code, 'c_name' => $c_name);
echo json_encode($data);
}
//category is unselected then execute belove code
else{
$c_name = "";
//pass the json data to ajax
$data = array('result'=>'success', 'p_name' => $p_name, 'p_code' => $p_code, 'c_name' => $c_name);
echo json_encode($data); 
}
}
//name is blank then execute belove code
else{
$ename = "name is required";
$data = array('message' => $ename);
echo json_encode($data);
}
?>

delete.php


<?php 
include "conn.php";
?>
<?php
//get the id of selected table row delete button
$ids=$_POST['del_id'];
//delete data in product table(name,code) and also delete on product_category table
mysqli_query($con, "delete from product where p_id='".$ids."'");
?>

transaction.js


$(document).ready(function () {
//view data on table row from database
    $.ajax({
        url: "view.php",
        type: "POST",
        contentType: "application/json",
        success: function (jsonStr)
        {
            var obj = jQuery.parseJSON(jsonStr);
            var new_row = '';
            $.each(obj, function (index, value) {
                new_row = "<tr id=" + value.p_id + ">" +
                        "<td>" + "<button id='edit' editId=" + value.p_id + " name='edit' type='button' class='btn btn-primary btn-sm'><span class='glyphicon glyphicon-pencil'></span>&nbsp&nbspEdit</button>" + "</td>" +
                        "<td>" + "<button id='delete' deleteId=" + value.p_id + " name='delete' type='button' class='btn btn-primary btn-sm'><span class='glyphicon glyphicon-remove-circle'></span>&nbsp&nbspDELETE</button>" + "</td>" +
                        "<td id='name'>" + value.p_name + "</td>" +
                        "<td id='code'>" + value.p_code + "</td>" +
                        "<td id='c_name'>" + value.c_name + "</td></tr>";
                $("#display").append(new_row);
            });
        }
    });
    //click on add button new row add on table as well as add record in database
    $(document).on("click", "#add", function () {
        var form1 = $("#product").serialize();
        $.ajax({
            type: "POST",
            url: "insert.php",
            data: form1,
            dataType: "json",
            success: function (jsonStr) {
                if (jsonStr.result == 'success')
                {
                    $('#error').empty();
                    var new_row = '';
                    new_row = "<tr id=" + jsonStr.p_id + ">" +
                            "<td>" + "<button id='edit' editId=" + jsonStr.p_id + " name='edit' type='button' class='btn btn-primary btn-sm'><span class='glyphicon glyphicon-pencil'></span>&nbsp&nbspEdit</button>" + "</td>" +
                            "<td>" + "<button id='delete' deleteId=" + jsonStr.p_id + " name='delete' type='button' class='btn btn-primary btn-sm'><span class='glyphicon glyphicon-remove-circle'></span>&nbsp&nbspDELETE</button>" + "</td>" +
                            "<td>" + jsonStr.p_name + "</td>" +
                            "<td>" + jsonStr.p_code + "</td>" +
                            "<td>" + jsonStr.c_name + "</td></tr>";
                    $("#display tr:last").after(new_row);
                } else {
                    $('#error').html(jsonStr.message);
                }
            }
        });
    });
    //click on update button updated row display on table and also update in database
    $(document).on("click", "#UPDATE", function () {
        var update_id = $("#product[update_id]").attr("update_id"); //get custom attribute value from form
        $.ajax({
            type: "POST",
            url: "update.php",
            data: $("#product").serialize() + "&update_id=" + update_id,
            dataType: "json",
            success: function (jsonStr) {
                if (jsonStr.result == 'success')
                {
                    $('#error').empty();
                    var new_row = '';
                    new_row = "<tr id=" + update_id + ">" +
                            "<td>" + "<button id='edit' editId=" + update_id + " name='edit' type='button' class='btn btn-primary btn-sm'><span class='glyphicon glyphicon-pencil'></span>&nbsp&nbspEdit</button>" + "</td>" +
                            "<td>" + "<button id='delete' deleteId=" + update_id + " name='delete' type='button' class='btn btn-primary btn-sm'><span class='glyphicon glyphicon-remove-circle'></span>&nbsp&nbspDELETE</button>" + "</td>" +
                            "<td>" + jsonStr.p_name + "</td>" +
                            "<td>" + jsonStr.p_code + "</td>" +
                            "<td>" + jsonStr.c_name + "</td></tr>";
                    $('#display').find('#' + update_id).replaceWith(new_row);
                    $("#UPDATE").html("ADD"); //use for change name of UPDATE button
                    $("#UPDATE").attr("id", "add"); //use for change id of UPDATE button
                } else {
                    $('#error').html(jsonStr.message);
                }
            }
        });
    });
    //click on reset button clear form and custom attribute
    $(document).on('click', '#resetform', function () {
        $("#product").removeAttr("update_id");
    });
    //click on edit button particular row data fill on form
    $(document).on('click', '#edit', function () {
        var editId = $(this).closest("tr").attr("id");
        $("#add").off("click"); //use for stop add button click event
        $("#add").html("UPDATE"); //use for change name of add button
        $("#add").attr("id", "UPDATE"); //use for change id of add button
        $("#product").attr("update_id", editId); //set custom attribute update_id value using form id
        $.ajax({
            type: "POST",
            url: "edit.php",
            data: {edit_id: editId},
            dataType: "json",
            success: function (jsonStr) {
                //clicked edit button id row data fill on form field
                $("#name").val(jsonStr.p_name);
                $("#code").val(jsonStr.p_code);
                $('input[type="checkbox"]:checked').prop('checked', false); //before check new checkbox value old value remove
                if (jsonStr.result == 'success')
                {
                    $.each(jsonStr.c_id.split(','), function (_, val) {
                        $(':input[value=' + val + ']').prop("checked", true);
                    });
                } else
                {
                    $('input[type="checkbox"]:checked').prop('checked', false);
                }
            }
        });
    });
    //click on delete button particular row delete on form table
    $(document).on('click', '#delete', function () {
        var deleteId = $(this).closest("tr").attr("id");
        $.ajax({
            type: "POST",
            url: "delete.php",
            data: {del_id: deleteId},
            success: function (data) {
                $("#" + deleteId).remove();
            }
        });
    });
});


Thursday, 19 January 2017

JAVASCRIPT

JAVASCRIPT
What is JavaScript?
JavaScript is a dynamic computer programming language. It is lightweight and most commonly used as a part of web pages, whose implementations allow client-side script to interact with the user and make dynamic pages. It is an interpreted programming language with object-oriented capabilities.

JavaScript was first known as LiveScript, but Netscape changed its name to JavaScript, possibly because of the excitement being generated by Java. JavaScript made its first appearance in Netscape 2.0 in 1995 with the name LiveScript. The general-purpose core of the language has been embedded in Netscape, Internet Explorer, and other web browsers.

ü The ECMA-262 Specification defined a standard version of the core JavaScript language.
ü JavaScript is a lightweight, interpreted programming language.
ü Designed for creating network-centric applications.
ü Complementary to and integrated with Java.
ü Open and cross-platform


Client-side JavaScript
Client-side JavaScript is the most common form of the language. The script should be included in or referenced by an HTML document for the code to be interpreted by the browser.
It means that a web page need not be a static HTML, but can include programs that interact with the user, control the browser, and dynamically create HTML content.
The JavaScript client-side mechanism provides many advantages over traditional CGI server-side scripts. For example, you might use JavaScript to check if the user has entered a valid e-mail address in a form field.
The JavaScript code is executed when the user submits the form, and only if all the entries are valid, they would be submitted to the Web Server.
JavaScript can be used to trap user-initiated events such as button clicks, link navigation, and other actions that the user initiates explicitly or implicitly.





Advantages of JavaScript
The merits of using JavaScript are −
Less server interaction − You can validate user input before sending the page off to the server. This saves server traffic, which means less load on your server.
Immediate feedback to the visitors − They don't have to wait for a page reload to see if they have forgotten to enter something.
Increased interactivity − You can create interfaces that react when the user hovers over them with a mouse or activates them via the keyboard.
Richer interfaces − You can use JavaScript to include such items as drag-and-drop components and sliders to give a Rich Interface to your site visitors.

Limitations of JavaScript

We cannot treat JavaScript as a full-fledged programming language. It lacks the following important features −
ü Client-side JavaScript does not allow the reading or writing of files. This has been kept for security reason.
ü JavaScript cannot be used for networking applications because there is no such support available.
ü JavaScript doesn't have any multithreading or multiprocessor capabilities.
ü Once again, JavaScript is a lightweight, interpreted programming language that allows you to build interactivity into otherwise static HTML pages.

Why we use JavaScript?

       JavaScript is most commonly used as a client side scripting language. This means that JavaScript code is written into an HTML page. When a user requests an HTML page with JavaScript in it, the script is sent to the browser and it's up to the browser to do something with it.

JavaScript Can Change HTML Content:

       One of many JavaScript HTML methods is getElementById().

This example uses the method to "find" an HTML element (with id="demo") and changes the element content (innerHTML) to "Hello JavaScript":




<!DOCTYPE html>
<html>
<body>

<h1>What Can JavaScript Do?</h1>

<p id="demo">JavaScript can change HTML content.</p>

<button type="button" onclick="document.getElementById('demo').innerHTML = 'Hello JavaScript!'">Click Me!</button>

</body>
</html>





EXAMPLE:
<!DOCTYPE html>
<html>
<body>
<h1>What Can JavaScript Do?</h1>

<p id="demo">JavaScript can change HTML content.</p>

<button type="button" onclick="document.getElementById('demo').innerHTML = 'Hello JavaScript!'">Change HTML content</button>

<button onclick="document.getElementById('myImage').src='pic_bulbon.gif'">Turn on the light</button>
<img id="myImage" src="pic_bulboff.gif" style="width:100px">
<button onclick="document.getElementById('myImage').src='pic_bulboff.gif'">Turn off the light</button>

<button type="button" onclick="document.getElementById('demo').style.fontSize='35px'"> Change HTML Styles</button>

<button type="button" onclick="document.getElementById('demo').style.display='none'">Hide HTML Elements</button>

<button type="button" onclick="document.getElementById('demo').style.display='block'">Hide HTML Elements</button>

</body>
</html>






JavaScript Where To:
In HTML, JavaScript code must be inserted between <script> and </script> tags.

<script>
                    document.getElementById("demo").innerHTML = "My First JavaScript";
</script>

JavaScript Functions and Events:

A JavaScript function is a block of JavaScript code, that can be executed when "asked" for.

For example, a function can be executed when an event occurs, like when the user clicks a button.




JavaScript in <head> or <body>:

ü You can place any number of scripts in an HTML document.
ü Scripts can be placed in the <body>, or in the <head> section of an HTML page, or in both.

JavaScript in <head>:

In this example, a JavaScript function is placed in the <head> section of an HTML page.
The function is invoked (called) when a button is clicked:

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>
<h1>A Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
</body>
</html>

JavaScript in <body>:

In this example, a JavaScript function is placed in the <body> section of an HTML page.
The function is invoked (called) when a button is clicked:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>A Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>

<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</body>
</html>

External JavaScript:
Scripts can also be placed in external files:
External file: myScript.js
function myFunction() {
   document.getElementById("demo").innerHTML = "Paragraph changed.";
}       
ü External scripts are practical when the same code is used in many different web pages.
ü JavaScript files have the file extension .js.
ü To use an external script, put the name of the script file in the src (source) attribute of a <script> tag:

<!DOCTYPE html>
<html>
<body>

<h1>External JavaScript</h1>

<p id="demo">A Paragraph.</p>

<button type="button" onclick="myFunction()">Try it</button>

<p>(myFunction is stored in an external file called "myScript.js")</p>

<script src="myScript.js"></script>

</body>
</html>



ü You can place an external script reference in <head> or <body> as you like.

ü The script will behave as if it was located exactly where the <script> tag is located.

NOTE: External scripts cannot contain <script> tags.

External JavaScript Advantages:

Placing scripts in external files has some advantages:

ü It separates HTML and code
ü It makes HTML and JavaScript easier to read and maintain
ü Cached JavaScript files can speed up page loads
ü To add several script files to one page  - use several script tags:

EXAMPLE:

<script src="myScript1.js"></script>
<script src="myScript2.js"></script>
External References:

ü External scripts can be referenced with a full URL or with a path relative to the current web page.

This example uses a full URL to link to a script:
<script      
                      src="http://www.w3schools.com/js/myScript1.js">
</script>

This example uses a script located in a specified folder on the current web site:
<script src="/js/myScript1.js"></script>

This example links to a script located in the same folder as the current page:
<script src="myScript.js"></script>