How can i insert these multiple row data into mysql database - javascript

This is my html ajax and js code, it's dynamic input field form
i want to insert multiple data into mysql database following these column "pro" "des" "qty" "price" "sub_total" . "qty" and "price" used auto sum value to "sub_total" input field
please see my full html code then Please write a php code for me .
Last time i was failed many time to do it.
so please help me
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="invoice system, php invoice script, invoice script, pro invoice maker, free php invoice/billing script, php Invoice software, php invoice generator script, invoice script open source, invoice generator php script, invoice script in php, javascript invoice script, invoice maker php script, php invoice script tutorial">
<meta name="keywords" content="invoice system, php invoice script, invoice script, pro invoice maker, free php invoice/billing script, php Invoice software, php invoice generator script, invoice script open source, invoice generator php script, invoice script in php, javascript invoice script, invoice maker php script, php invoice script tutorial">
<meta name="author" content="http://tanbhirhossain.me">
<title>AFOJAL MINI MARKET</title>
<!-- Bootstrap -->
<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:400,300,200' rel='stylesheet' type='text/css'>
<link href="css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="css/font-awesome.min.css">
<link href="css/admin.css" rel="stylesheet">
<!-- Script -->
<script src="js/jquery.min.js"></script>
<script src="js/wayfinder.js" ></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script>
$(document).ready(function() {
jQuery('.load-animate').waypoint({
triggerOnce: true,
offset: '80%',
handler: function() {
jQuery(this).addClass('animated fadeInUp');
}
});
});
</script>
</head>
<body>
<!-- Static navbar -->
<div role="navigation" class="navbar navbar-inverse navbar-fixed-top">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" data-toggle="collapse"
data-target=".navbar-collapse" class="navbar-toggle collapsed">
<span class="sr-only">Toggle navigation</span> <span
class="icon-bar"></span> <span class="icon-bar"></span> <span
class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Afojal Mini Market Invoice System</a>
</div>
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav navbar-right">
<li class="dropdown">
<a href="#" data-toggle="dropdown" class="dropdown-toggle">
Hello
muni <span class="caret"></span>
</a>
<ul role="menu" class="dropdown-menu account-menu">
<li> <i class="fa fa-user"></i> My Account </li>
<li class="divider"></li>
<li style="background: #e67e22; color:#fff"> <a class="logout" href="logout.php"> <i class="fa fa-power-off"></i> Signout</a> </li>
</ul>
</li>
</ul>
</div>
<!--/.nav-collapse -->
</div>
</div>
<link href="http://code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.min.css" rel="stylesheet">
<link href="css/datepicker.css" rel="stylesheet">
<!-- Begin page content -->
<div class="container content-invoice">
<form action="invoice.php" id="invoice-form" method="post" class="invoice-form" role="form" novalidate>
<div class="load-animate">
<input type="hidden" value="" name="data[id]">
<div class='row'>
<div class='col-xs-8 col-sm-8 col-md-8 col-lg-8'>
<h1 class="title">PHP Invoice System</h1>
</div>
<div class='col-xs-4 col-sm-4 col-md-4 col-lg-4'>
<input data-loading-text="Saving Invoice..." type="submit" name="invoice_btn" value="Save Invoice" class="btn btn-success submit_btn invoice-save-top form-control"/>
</div>
</div>
<input id="currency" type="hidden" value="RM">
<div class='row'>
<div class='col-xs-12 col-sm-12 col-md-12 col-lg-12'>
<table class="table table-bordered table-hover">
<thead>
<tr>
<th width="2%"><input id="check_all" class="formcontrol" type="checkbox"/></th>
<th width="15%">Product</th>
<th width="38%">Description</th>
<th width="15%">Price</th>
<th width="15%">Quantity</th>
<th width="15%">Total</th>
</tr>
</thead>
<tbody>
<tr>
<td><input class="case" type="checkbox"/></td>
<td><input type="text" data-type="productCode" name="data[Invoice][pro][]" id="ipro_1" class="form-control autocomplete_txt" autocomplete="off"></td>
<td><input type="text" data-type="productName" name="data[Invoice][des][]" id="ides_1" class="form-control autocomplete_txt" autocomplete="off"></td>
<td><input type="number" name="data[Invoice][price][]" id="price_1" class="form-control changesNo" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;"></td>
<td><input type="number" name="data[Invoice][qty][]" id="quantity_1" class="form-control changesNo" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;"></td>
<td><input type="number" name="data[Invoice][sub_total][]" id="total_1" class="form-control totalLinePrice" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;"></td>
</tr>
</tbody>
</table>
</div>
</div>
<div class='row'>
<div class='col-xs-12 col-sm-3 col-md-3 col-lg-3'>
<button class="btn btn-danger delete" type="button">- Delete</button>
<button class="btn btn-success addmore" type="button">+ Add More</button>
</div>
</div>
<div class='row'>
<div class='col-xs-12 col-sm-8 col-md-8 col-lg-8'>
<h3>Notes: </h3>
<div class="form-group">
<textarea class="form-control txt" rows='5' name="data[notes]" id="notes" placeholder="Your Notes"></textarea>
</div>
<div class='form-group text-center'>
<input data-loading-text="Saving Invoice..." type="submit" name="invoice_btn" value="Save Invoice" class="btn btn-success submit_btn invoice-save-btm"/>
</div>
</div>
<div class='col-xs-12 col-sm-4 col-md-4 col-lg-4'>
<span class="form-inline">
<div class="form-group">
<label>Subtotal: </label>
<div class="input-group">
<div class="input-group-addon currency">$</div>
<input value="" type="number" class="form-control" name="data[subTotal]" id="subTotal" placeholder="Subtotal" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;">
</div>
</div>
<div class="form-group">
<label>Tax: </label>
<div class="input-group">
<div class="input-group-addon currency">$</div>
<input value="" type="number" class="form-control" name="data[tax]" id="tax" placeholder="Tax" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;">
</div>
</div>
<div class="form-group">
<label>Tax Amount: </label>
<div class="input-group">
<input value="" type="number" class="form-control" name="data[taxAmount]" id="taxAmount" placeholder="Tax" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;">
<div class="input-group-addon">%</div>
</div>
</div>
<div class="form-group">
<label>Total: </label>
<div class="input-group">
<div class="input-group-addon currency">$</div>
<input value="" type="number" class="form-control" name="data[totalAftertax]" id="totalAftertax" placeholder="Total" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;">
</div>
</div>
</span>
</div>
</div>
<div class="clearfix"></div>
<div class='row'>
<div class='col-xs-12 col-sm-6 col-md-6 col-lg-6 text-center'>
</div>
</div>
</div>
</form>
</div>
<script src="js/jquery-ui.min.js"></script>
<script src="js/ajax.js"></script>
<script>
$('.submit_btn').on('click', function(){
$(this).button('loading');
});
$(document).ready(function(){
$('.currency').html( $('#currency').val() );
});
$('#clientCompanyName').autocomplete({
source: function( request, response ) {
$.ajax({
url : 'ajax.php',
dataType: "json",
method: 'post',
data: {
name_startsWith: request.term,
type: 'customerName'
},
success: function( data ) {
response( $.map( data, function( item ) {
var code = item.split("|");
return {
label: code[1],
value: code[1],
data : item
}
}));
}
});
},
autoFocus: true,
minLength: 1,
select: function( event, ui ) {
var names = ui.item.data.split("|");
$(this).val(names[1]);
getClientAddress(names[0]);
}
});
function getClientAddress(id){
$.ajax({
url: "ajax.php",
method: 'post',
data:{id:id, type:'clientAddress'},
success: function(result){
$("#clientAddress").html(result);
}
});
}
</script>
<div class="clearfix"></div>
<footer class="footer">
<div class="container-fluid">
<!-- <p class="text-center">© Copyright by Smart Tutorials </p> -->
</div>
</footer>
<script src="js/bootstrap.min.js"></script>
<script src="js/bootstrap-datepicker.js"></script>
</body>
</html>
my php code was:
<?php
//insert.php
$connect = mysqli_connect("localhost", "root", "", "inv");
if(isset($_POST["pro"]))
{
$item_name = $_POST["pro"];
$item_code = $_POST["des"];
$item_des = $_POST["qty"];
$item_price = $_POST["price"];
$subtotal = $_POST["sub_total"];
$query = '';
for($count = 0; $count<count($item_name); $count++)
{
$item_name_clean = mysqli_real_escape_string($connect, $item_name[$count]);
$item_code_clean = mysqli_real_escape_string($connect, $item_code[$count]);
$item_des_clean = mysqli_real_escape_string($connect, $item_des[$count]);
$item_price_clean = mysqli_real_escape_string($connect, $item_price[$count]);
$subtotal_clean = mysqli_real_escape_string($connect, $subtotal[$count]);
if($item_name_clean != '' && $item_code_clean != '' && $item_des_clean != '' && $item_price_clean != '')
{
$query .= '
INSERT INTO sell(pro, des, qty, price, sub_total)
VALUES("'.$item_name_clean.'", "'.$item_code_clean.'", "'.$item_des_clean.'", "'.$item_price_clean.'", "'.$subtotal_clean.'");
';
}
}
if($query != '')
{
if(mysqli_multi_query($connect, $query))
{
echo 'Item Data Inserted';
}
else
{
echo 'Error';
}
}
else
{
echo 'All Fields are Required';
}
}
?>

You will get your post data in $_POST['data']['Invoice'] array so change your script like :
//insert.php
$connect = mysqli_connect("localhost", "root", "", "inv");
if(isset($_POST['data']['Invoice']['pro']))
{
$item_name = $_POST['data']['Invoice']['pro'];
$item_code = $_POST['data']['Invoice']["des"];
$item_des = $_POST['data']['Invoice']["qty"];
$item_price = $_POST['data']['Invoice']["price"];
$subtotal = $_POST['data']['Invoice']["sub_total"];
$query = '';
for($count = 0; $count<count($item_name); $count++)
{
$item_name_clean = mysqli_real_escape_string($connect, $item_name[$count]);
$item_code_clean = mysqli_real_escape_string($connect, $item_code[$count]);
$item_des_clean = mysqli_real_escape_string($connect, $item_des[$count]);
$item_price_clean = mysqli_real_escape_string($connect, $item_price[$count]);
$subtotal_clean = mysqli_real_escape_string($connect, $subtotal[$count]);
if($item_name_clean != '' && $item_code_clean != '' && $item_des_clean != '' && $item_price_clean != '')
{
$query .= '
INSERT INTO sell(pro, des, qty, price, sub_total)
VALUES("'.$item_name_clean.'", "'.$item_code_clean.'", "'.$item_des_clean.'", "'.$item_price_clean.'", "'.$subtotal_clean.'");
';
}
}
if($query != '')
{
if(mysqli_multi_query($connect, $query))
{
echo 'Item Data Inserted';
}
else
{
echo 'Error';
}
}
}

Related

I am implementing image-preview functionality but during that unable to reset relevant file input

I am implementing image-preview functionality (for multiple hidden-browse buttons with dynamic ids) but during that unable to reset relevant file input
Everything working fine..
HTML Part:
<div class="col-sm-12">
<?php
$prd_imgs_sql = "SELECT * FROM `ci_product_images` WHERE `added_by` = '".$this->session->userdata('user_id')."' AND `is_prod_submited` = '0'";
$prd_imgs_res = $this->home->customQuery($prd_imgs_sql);
$chk_img = 1;
foreach($prd_imgs_res as $res){
if($res->prod_img != "" ){
$prdImgThumb = BASE_URL.'uploads/productImages/150x150/'.$res->prod_img_thumb;
}else{
$prdImgThumb = BASE_IMAGE.'plbtn.jpg';
}
if($res->prod_img_link != "" ){
$prdImgLinkTxt = $res->prod_img_link;
$prdImgLink = $res->prod_img_link;
}else{
$prdImgLinkTxt = '';
$prdImgLink = BASE_IMAGE.'preview.png';
}
?>
<div class="row">
<div class="col-sm-2">
<img src="<?=$prdImgLink?>" class="img-responsive primg" id="preview_img_<?php echo $chk_img;?>">
</div>
<div class="col-sm-6">
<div class="input-group" style="margin-top: 20px">
<input type="text" class="form-control imgLnk" placeholder="Image Url.." id="url_input_<?php echo $chk_img;?>" name="url_input[]" value="<?=$prdImgLinkTxt?>" autocomplete="off">
<span class="input-group-btn">
<button class="btn btn-default findbtn" type="button" id="find_btn_<?php echo $chk_img;?>">Find</button>
</span>
</div><!-- /input-group -->
<div class="err" id="valmsg_<?php echo $chk_img;?>" style="display: none;"></div>
</div>
<div class="col-sm-1">
<h2 style="text-align: center;">Or</h2>
</div>
<div class="col-sm-3">
<div class="form-group">
<img src="<?=$prdImgThumb?>" class="edi_prd_img rk" id="brws_btn_<?php echo $chk_img;?>" />
<?php if($res->prod_img != "" ){ ?>
<a class="topright imgDelete" href="<?php echo BASE_URL;?>admin/products/delete_prd_img/<?php echo base64_encode($res->id);?>" id="imgdel_<?php echo $chk_img;?>">X</a>
<?php } ?>
<input type="file" name="prod_images[]" id="ip_<?php echo $chk_img;?>" class="hidBrws" style="display: none;" />
</div>
</div>
</div>
<?php
$chk_img++;
}
?>
<?php
while($chk_img<5){
?>
<div class="row">
<div class="col-sm-2">
<img src="<?php echo BASE_IMAGE."preview.png"; ?>" class="img-responsive primg" id="preview_img_<?php echo $chk_img;?>">
</div>
<div class="col-sm-6">
<div class="input-group" style="margin-top: 20px">
<input type="text" class="form-control imgLnk" placeholder="Image Url.." id="url_input_<?php echo $chk_img;?>" name="url_input[]" autocomplete="off">
<span class="input-group-btn">
<button class="btn btn-default findbtn" type="button" id="find_btn_<?php echo $chk_img;?>">Find</button>
</span>
</div><!-- /input-group -->
<div class="err" id="valmsg_<?php echo $chk_img;?>" style="display: none;"></div>
</div>
<div class="col-sm-1">
<h2 style="text-align: center;">Or</h2>
</div>
<div class="col-sm-3">
<div class="form-group">
<img src="<?php echo BASE_IMAGE."plbtn.jpg"; ?>" class="edi_prd_img rk" id="brws_btn_<?php echo $chk_img;?>" />
<input type="file" name="prod_images[]" id="ip_<?php echo $chk_img;?>" class="hidBrws" style="display: none;" />
</div>
</div>
</div>
<?php
$chk_img++;
}
?>
</div>
My jQuery Script:
$(".edi_prd_img").click(function() {
var id = $(this).attr("id");
var tmp = id.split('_');
$("input[id='ip_"+tmp[2]+"']").click();
});
$(".hidBrws").change(function() {
if (this.files && this.files[0]) {
var reader = new FileReader();
var id = $(this).attr("id");
var tmp = id.split('_');
reader.onload = function(e) {
$('#preview_img_'+tmp[1]).attr('src','<?=base_url()?>preview.png');
$('#url_input_'+tmp[1]).val('');
$('#brws_btn_'+tmp[1]).attr('src', e.target.result);
}
reader.readAsDataURL(this.files[0]);
}
});
But when I want to reset one of the browse-button (file) on some specific event then I am getting issue.. its not getting reset.
My browse-button (file) reset jquery script:
$('.imgLnk').keyup(function(e){
var id = $(this).attr("id");
var tmp = id.split('_');
$('ip_'+tmp[2]).val(''); //tried with this but not happening
$('#brws_btn_'+tmp[2]).attr('src', '<?=base_url()?>plbtn.jpg');
$('#imgdel_'+tmp[2]).hide();
});
But relevant reset jquery script not working..
not working: $('ip_'+tmp[2]).val('');
please suggest me changes or any idea
There is only one issue with your code. You need to change your line $('ip_'+tmp[2]).val(''); to $('#ip_'+tmp[2]).val('');. As this is your identifier, you have slight issue in syntax.
I just have updated your code to static code and created the fiddle. Try below. For testing purpose, I have enabled the file input.
$(function(){
$('.imgLnk').keyup(function(e){
var id = $(this).attr("id");
var tmp = id.split('_');
$('#ip_'+tmp[2]).val(''); //tried with this but not happening
$('#brws_btn_'+tmp[2]).attr('src', '<?=base_url()?>plbtn.jpg');
$('#imgdel_'+tmp[2]).hide();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
<img src="<?=$prdImgThumb?>" class="edi_prd_img rk" id="brws_btn_1" />
<input type="text" class="form-control imgLnk" placeholder="Image Url.." id="url_input_1" name="url_input[]" autocomplete="off">
<input type="file" name="prod_images[]" id="ip_1" class="hidBrws" style="display: block;" />
</div>
<div class="row">
<img src="<?=$prdImgThumb?>" class="edi_prd_img rk" id="brws_btn_2" />
<input type="text" class="form-control imgLnk" placeholder="Image Url.." id="url_input_1" name="url_input[]" autocomplete="off">
<input type="file" name="prod_images[]" id="ip_2" class="hidBrws" style="display: none;" />
</div>

How to save Dynamically Generated table rows to database

This is My HTML Code
<form method="POST" action="backend/backup.php">
<div class="box-body col-sm-12">
<input type="hidden" name="txtSlNo" id="txtSlNo" value="1">
<div class="col-sm-2">
<label for="Date" class="control-label">Date:</label>
<input type="text" class="text-right" name="date[]" id="date"
value="<?php echo date(" Y/M/D ")?>">
</div>
<div class="col-sm-1">
<label for="name" class="control-label">Amount:</label>
<input type="text" size="7" class="text-right" name="txtAmount[]"
id="txtAmount" oninput="calculate()" onkeypress="return isNumber(event);">
</div>
<div class="col-sm-1">
<label for="name" class="control-label">Unit:</label>
<input type="text" size="7" name="txtUnit[]" class="text-right"
id="txtUnit" oninput="calculate()" value="1" onkeypress="return
isNumber(event);">
</div>
<div class="col-sm-1">
<label for="name" class="control-label">Total:</label>
<input type="text" size="7" name="txtTotal[]" class="text-right"
id="txtTotal" oninput="calculate();" oninput="addTotal();" readonly>
</div>
<div class="col-sm-2">
<br>
<!-- <button name="add" id="add" class="btn btn-primary"
hidden="hidden">Add</button> -->
</div>
<div class="col-sm-2">
<input type="button" value="add" name="tableAdd" id="tableAdd"
class="btn btn-primary add add1">
</div>
</div>
<div class="col-xs-12">
<table id="tabledata" name="tabledata">
<thead>
<tr>
<th style="width: 50px; text-align: center !important;"
id="select">select</th>
<th style="width: 50px; text-align: center
!important;">Sl.No</th>
<th style="width: 125px; text-align: center
!important;">Date</th>
<th style="width: 175px; text-align: center
!important;">Service</th>
<th style="width: 80px; text-align: center
!important;">Charge</th>
<th style="width: 80px;">Amount</th>
<th style="width: 80px;">Unit</th>
<th style="width: 80px;">Total</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<button type="button" id="delete-row" class="delete-row">Delete Row</button>
<button class="print" onclick="myFunction()">Print this page</button>
<br>
<label class="GrandTotalLabel" id="GrandTotalLabel">GRAND TOTAL</label>
<input type="text" name="txtGrandTotal" value="00.00" class="txtGrandTotal"
oninput="addTotal();" id="txtGrandTotal" readonly/>
</form>
This is My PHP code
<?php
$servername = "localhost";
$username = "1234";
$password = "";
$dbname = "tad";
$conn = new mysqli($servername, $username, $password, $dbname);
if(isset($_POST["save"]))
{
$numberOfRows = count($_POST['date']); // get the number of rows
for ($i = 0; $i < $numberOfRows; $i++) {
$date = $_POST["date"][$i];
$amount = $_POST["txtAmount"][$i];
$unit = $_POST["txtUnit"][$i];
$total = $_POST["txtTotal"][$i];
$sql = "INSERT INTO backup_master (backup_date, backup_amount,
backup_unit, backup_total) VALUES ('$date', '$amount', '$unit', '$total')";
$result = mysqli_query($conn, $sql);
}
}
?>
This is MY JAVASCRIPT CODE
<script type="text/javascript">
var lclCount=0;
$("#tableAdd").click(function(){
var sl_no = ($('#tabledata tr').length) - 1;
lclCount++;
sl_no++;
var date = $("#date").val();
var amount = $("#txtAmount").val();
var unit = $("#txtUnit").val();
var total = $("#txtTotal").val();
var markup = "<tr><td><input type='checkbox'
name='record' id='"+ lclCount +"'></td><td name='slno' class='slno' id
='slno-"+sl_no+"'>"
+ sl_no + "</td><td>"
+ date + "</td><td>"
+ amount + "</td><td>"
+ unit + "</td><td>"
+ parseFloat(total).toFixed(2) + "</td></tr>";
$("#tabledata").append(markup);
addTotal();
refreshAdd();
});
Here I want to save whatever is generated from dynamically created table data to the database. I tried a lot but unable to do so. Am getting an error saying undefined index date amount etc. Here I want to generate id for every automatically generated table row but unable to figure out how to do so.
Is there any other solution for this ?
Thank in Advance.
Okay....
In my code I'm created a div with class data in which I put four inputs date,amount,unit and total.
I add plus and minus buttons in last for add/remove row.
by clicking plus button clone of previous row appear in last
On submit data of all input will be send to the submit URL.
<?php
$servername = "localhost";
$username = "1234";
$password = "";
$dbname = "tad";
$conn = new mysqli($servername, $username, $password, $dbname);
if(isset($_POST["save"])){
$value = '';
for ($i=0;$i<count($_POST['date']);$i++) {
$value .= '("'.$_POST["date"][$i].'","'.$_POST["amount"][$i].'","'.$_POST["unit"][$i].'","'.$_POST["total"][$i].'"),';
}
$value = rtrim($value,",");
$sql = "INSERT INTO backup_master (backup_date, backup_amount, backup_unit, backup_total) VALUES ".$value;
$result = mysqli_query($conn, $sql);
}
echo '
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body><br />
<div class="container">
<h2>Vertical (basic) form</h2>
<form action="/action_page.php">
<div class="row data" divid="1">
<div class="col-md-3">
<div class="input-group">
<span class="input-group-addon">Date</span>
<input type="text" class="form-control date" value="'.date('Y/M/d').'" id="date-1" placeholder="Enter date" name="date[0]" />
</div>
</div>
<div class="col-md-3">
<div class="input-group">
<span class="input-group-addon">Amount</span>
<input type="text" class="form-control amount" data-id="1" value="0" id="amount-1" placeholder="Enter Amount" name="amount[0]" />
</div>
</div>
<div class="col-md-3">
<div class="input-group">
<span class="input-group-addon">Unit</span>
<input type="text" class="form-control unit" data-id="1" id="unit-1" value="0" placeholder="Enter Unit" name="unit[0]" />
</div>
</div>
<div class="col-md-2">
<div class="input-group">
<span class="input-group-addon">Total</span>
<input type="text" class="form-control total" id="total-1" readonly="readonly" name="total[0]" />
</div>
</div>
<div class="col-md-1">
<button class="btn btn-success btn-block plus" type="button" id="p-1">+</button>
<button class="btn btn-danger btn-block minus hide" type="button" id="m-1">-</button>
</div>
</div>
<div class="row"><div class="col-md-3"> </div></div>
<div class="row">
<div class="col-md-3">
<div class="input-group">
<span class="input-group-addon">Grand Total</span>
<input type="text" class="form-control" value="0" id="g-total" readonly="readonly" name="g_total" />
</div>
</div>
<div class="col-md-3">
<button type="submit" class="btn btn-default" name="save">Submit</button>
</div>
</div>
</form>
</div>
</body>
</html>';
?>
<script type="text/javascript">
$(document).on('change','.unit,.amount',function(e) {
id = parseInt($(this).attr("id").replace("unit-", "").replace("amount-",""));
get_total(id);
});
function get_total(id){
unit_d = parseInt($('#unit-'+id).val());
amount = parseInt($('#amount-'+id).val());
total = Math.ceil(amount*unit_d);
$('#total-'+id).val(total);
var g_total = 0;
jQuery('.total').each(function(){
g_total = g_total+parseInt($(this).val());
});
$('#g-total').val(g_total);
}
/****************************JS for add new row****************************/
$(document).on('click','.plus',function(e) {
var thisRow = $('.data').last(".data");
var newid = parseInt(thisRow.attr('divid'))+1;
var cid = parseInt(thisRow.attr('divid'));
var date = $('#date-'+cid).val();
var amount = $('#amount-'+cid).val();
var n_unit = $('#unit-'+cid).val();
var total = $('#total-'+cid).val();
if(date=="") $('#date-'+cid).addClass('error'); else $('#date-'+cid).removeClass('error');
if(amount=="") $('#amount-'+cid).addClass('error'); else $('#amount-'+cid).removeClass('error');
if(n_unit=="") $('#unit-'+cid).addClass('error'); else $('#unit-'+cid).removeClass('error');
if(total=="") $('#total-'+cid).addClass('error'); else $('#total-'+cid).removeClass('error');
if((date!="")&&(amount!="")&&(n_unit!="")&&(total!="")){
$('#date-'+cid+',#amount-'+cid+',#unit-'+cid).attr('readonly','readonly');
newRow = thisRow.clone(true).insertAfter(thisRow).find('input').val('').end().
find('.date').each(function(){
$(this).attr('id', 'date-'+newid);
$(this).attr('name','date['+(newid-1)+']');
$(this).val($('#date-'+cid).val());
$(this).removeAttr('readonly');
}).end().find('.amount').each(function(){
$(this).attr('id', 'amount-'+newid);
$(this).attr('name','amount['+(newid-1)+']');
$(this).attr('data-id',newid);
$(this).val(0);
$(this).removeAttr('readonly');
}).end().find('.unit').each(function(){
$(this).attr('id', 'unit-'+newid);
$(this).attr('name','unit['+(newid-1)+']');
$(this).attr('data-id',newid);
$(this).val(0);
$(this).removeAttr('readonly');
}).end().find('.total').each(function(){
$(this).attr('id', 'total-'+newid);
$(this).attr('name','total['+(newid-1)+']');
$(this).val(0);
}).end().find('.plus').each(function(){
$(this).attr('id', 'p-'+newid);
$(this).attr('data-id', newid);
}).end().find('.minus').each(function(){
$(this).attr('id', 'm-'+newid);
}).end();
thisRow.next('.data').attr("divid",newid).addClass('child');
$('.minus').removeClass('hide');
$('.plus').addClass('hide');
$('#m-'+newid).addClass('hide');
$('#p-'+newid).removeClass('hide');
}
});
/****************************JS for add new row****************************/
/****************************JS for delete row****************************/
$('.minus').click(function(e) {
$(this).closest('.data').remove();
});
/****************************JS for delete row****************************/ </script>

How to get dynamic buttons value when button is click in PHP?

I have created dynamic buttons in php. I need to get the value of that button when particular button is click. And when we click the button, all information is fetch in to the form.
Here is my code for buttonclick
<?php
function dash()
{
include 'config.php';
$sql = "SELECT roomno FROM roombook";
if($result = mysqli_query($db, $sql))
{
$str = '';
while($row = mysqli_fetch_array($result))
{
// generate array from comma delimited list
$rooms = explode(',', $row['roomno']);
//create the dynamic button and set the value
foreach ( $rooms as $k=>$v )
{
$str .= '<input type="button" onClick="showDiv()" name="btn_'.$k.'" value="'.$v.'" id="btn_'.$k.'"/>';
}
}
return $str;
}
else {
echo "ERROR: Could not able to execute $sql. " . mysqli_error($db);
}
mysqli_close($db);
}
?>
<!Doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>room boking</title>
<link href="css/bootstrap1.min.css" rel="stylesheet">
<link rel="stylesheet" href="css/front.css">
</head>
<body>
<form method="post" action="">
<div class =" row box col-md-4" >
<div style="color:black"><?php echo dash();?></div>
</div>
</form>
Here fetching the value in form code
<!DOCTYPE html>
<?php
include 'config.php';
if(isset($_POST['book']))
{
$roomno=$_POST['roomno'];
$roomtype=$_POST['roomtype'];
$location=$_POST['location'];
$charges=$_POST['charges'];
$firstname=$_POST['firstname'];
$lastname=$_POST['lastname'];
$address=$_POST['address'];
$city=$_POST['city'];
$state=$_POST['state'];
$pincode=$_POST['pincode'];
$mobilenumber=$_POST['mobilenumber'];
$idtype=$_POST['idtype'];
$idnumber=$_POST['idnumber'];
$Adate=$_POST['Adate'];
$Ldate=$_POST['Ldate'];
//echo $roomno."<br>".$roomtype."<br>".$location."<br>".$charges."<br>".$firstname."<br>".$lastname."<br>";
if(strlen($firstname)<3)
{
echo "<script>alert('First name is to short')</script>";
}
else if(strlen($lastname)<3)
{
echo "<script>alert('Last name is to short')</script>";
}
else if(strlen($address)<3)
{
echo "<script>alert('UserName name is to short')</script>";
}
else
{
$query=" INSERT INTO customerbook(roomno,roomtype,location,charges,firstname,lastname,address,city,state,pincode,mobilenumber,idtype,idnumber,Adate,Ldate) VALUES('$roomno','$roomtype','$location','$charges','$firstname','$lastname','$address','$city','$state','$pincode','$mobilenumber','$idtype','$idnumber','$Adate','$Ldate')";
//$query="INSERT INTO customerbook(roomno,roomtype,location,charges,firstname,lastname,address,state,city,pincode,mobilenumber,idtype,idnumber,Adate,Ldate) VALUES('$roomno','$roomtype','$location','$charges','$firstname','$lastname','$address','$state,','$city','$pincode','$mobilenumber','$idtype','$idnumber','$Adate','$Ldate')";
if(mysqli_query($db, $query))
{
echo "<script>alert('booking seccessfully')</script>";
//header("Location:login.php");
}
else echo "error";
}
}
$sql = "SELECT roomno,roomtype,location,charges FROM roombook where roomno='101'";
if($result = mysqli_query($db, $sql)){
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_array($result)){
$roomno=$row['roomno'];
$roomtype=$row['roomtype'];
$location=$row['location'];
$charges=$row['charges'];
}
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($db);
?>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>booking Form</title>
<!-- Bootstrap -->
<link href="css/bootstrap1.min.css" rel="stylesheet">
<link href="css/book.css" rel="stylesheet">
</style>
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="js/jquery-1.12.4.js"></script>
<script src="js/book1.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="head" id="link">
<div class="panel panel-primary" style="margin:20px;">
<div class="panel-heading">
<center><h3 class="panel-title">booking Form</h3></center>
</div>
<div class="panel-body">
<form method="post" action="">
<div class="col-md-12">
<div class="form-group col-md-12 ">
<label for="roomno">Room Number* </label>
<input type="text" class="form-control input-sm" name="roomno" value='<?php echo $roomno; ?>' placeholder="">
</div>
<div class="form-group col-md-6">
<label for="type">Room Type*</label>
<input type="text" class="form-control input-sm" name="roomtype" value='<?php echo $roomtype; ?>' placeholder="">
</div>
<div class="form-group col-md-6">
<label for="location">Location*</label>
<input type="text" class="form-control input-sm" name="location" placeholder="">
</div>
<div class="form-group col-md-12">
<label for="charges">charges*</label>
<input type="text" class="form-control input-sm" name="charges" placeholder="">
</div>
<div class="form-group col-md-6">
<label for="customer name">First Name*</label>
<input type="text" class="form-control input-sm" name="firstname" placeholder="">
</div>
<div class="form-group col-md-6">
<label for="customer name">Last Name*</label>
<input type="text" class="form-control input-sm" name="lastname" placeholder="">
</div>
<div class="form-group col-md-12">
<label for="address">Address*</label>
<textarea class="form-control input-sm" name="address" rows="3"></textarea>
</div>
<div class="form-group col-md-4">
<label for="city">City*</label>
<input type="text" class="form-control input-sm" name="city" placeholder="">
</div>
<div class="form-group col-md-4">
<label for="state">State*</label>
<input type="text" class="form-control input-sm" name="state" placeholder="">
</div>
<div class="form-group col-md-4">
<label for="pincode">Pincode</label>
<input type="text" class="form-control input-sm" name="pincode" placeholder="">
</div>
<div class="form-group col-md-12">
<label for="mobile">Mobile Number*</label>
<input type="text" class="form-control input-sm" name="mobilenumber" placeholder="">
</div>
<div class = "form-group col-md-12">
<label for="years">Id Type *</label>
<select class="form-control input-sm" name="idtype">
<option>-- Select Id Card --</option>
<option>Pancard</option>
<option>Adhar Card</option>
<option>voting card</option>
</select>
</div>
<div class="form-group col-md-12">
<label for="idnumber">Id Number</label>
<input type="text" class="form-control input-sm" name="idnumber" placeholder="">
</div>
<div class="form-group col-md-6">
<label for="arrival">Arrival Date</label>
<input type="text" class="form-control input-sm datepicker" name="Adate" placeholder="">
</div>
<div class="form-group col-md-6">
<label for="arrival">Leaving Date</label>
<input type="text" class="form-control input-sm datepicker" name="Ldate" placeholder="">
</div>
</div>
<div class="col-md-12">
<div class="form-group col-md-12 " >
<center><input type="submit" class="btn btn-primary" value="Submit" name="book"/><center>
</div>
</div>
</form>
</div>
</div>
</script>
</body>
</html>
You can create your button like this
$str .= '<input type="button" onClick="showDiv()" data-atribute-id="valueyouwant" name="btn_'.$k.'" value="'.$v.'" id="btn_'.$k.'"/>';
Script should be like
$("button").click(function() {
alert(this.id); OR
alert($(this).attr('id')); OR
alert($(this).attr('data')); OR
var btnid = $(this).attr('data');//which give you current clicked btn id
});
You can use this:
// is going to select all elements that its name start with *btn_* (your dynamic buttons)
$('[name^="btn_"]').click(function() {
//get the value of the button that was clicked
var buttonValue = $(this).val();
// send data to the other file using the action attribute of the form
$('form').submit();
});
Hope that can help.

How to reload table content only whenever a database record is added/changed

I have a PHP page which contains 2 tabs Entry and View. From the Entry tab I can insert data in a database and on my View tab I have an HTML table which displays the data. There is also a provision to insert data from my View tab as well.
I want to reload my table every time some new data is added. I tried this using jQuery but the problem is that it reloads my entire page and sends me back to my Entry tab, even if I have inserted the data from my View tab. Can anyone tell me if there is any provision to reload just HTML table every time I add new data to the database and stay on the same tab from wherever I have added my data?
Here is what I have tried:
$(document).ready(function(e) {
var refresher = setInterval("update_content();", 60000);
})
function update_content(){
$.ajax({
type: "GET",
url: "main.php",
cache: false,
}).done(function( page_html ) {
// alert("LOADED");
var newDoc = document.open("text/html", "replace");
newDoc.write(page_html);
newDoc.close();
});
}
main.php code goes here-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>Logsheet-Dhanraj & Co.</title>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/custom.css" rel="stylesheet">
<link href="css/table_edit.css" rel="stylesheet">
<link href="css/styleinputcontainer.css" rel="stylesheet">
<link href="css/footable.standalone.css" rel="stylesheet">
<link href="css/footable.core.css" rel="stylesheet">
<link rel="stylesheet" href="jquery-ui\jquery-ui-themes-1.11.4\jquery-ui-themes-1.11.4\themes/smoothness/jquery-ui.css" />
</head>
<body>
<header>
<div class="container-fluid">
<div class="panel panel-info">
<div class="panel-heading">
<div class="panel-title ">Logsheet-Dhanraj
<button type="button" class="close" data-dismiss="panel">×</button></div>
</div><!--panel heading-->
<div class="panel-body">
<ul class="nav nav-tabs">
<li class="active">Entry</li>
<li >View</li>
</ul>
<div class="tab-content">
<div class="tab-pane fade in active" id="Entry">
<div class="container-fluid">
<form id="dataentry" action="insert_data.php" method="post">
<div class="row">
<br />
<br />
</div><!--empty row-->
<div class="row">
<div class="form-group col-md-2">
<label for="Date">Date</label></br>
<input type="text" name="date" id="date" autocomplete="off"/>
</div><!--col 1-->
<div class="form-group col-md-3">
<div class="input_container">
<label for="Clientname">Client Name</label></br>
<input type="text" name="clientname" id="clientname" onkeyup="autocomplete_client()" autocomplete="off" />
<ul id="clientlist_id"></ul>
</div><!--inputcontainer client-->
</div><!--col 2-->
<div class="form-group col-md-4">
<div class="input_container">
<label for="Staff">Staff</label></br>
<input type="text" name="staff" id="staff" onkeyup="autocomplete_staff()" autocomplete="off"/>
<ul id="stafflist_id"></ul>
</div><!--inputcontainer staff-->
</div><!--col 3-->
</div><!--row1-->
<div class="row">
<div class="form-group col-md-12">
<label for="Matter">Matter</label></br>
<textarea rows="4" cols="60" name="matter" id="matter" ></textarea>
</div><!--matter col-->
</div><!--row2-->
<div class="row">
<div class="col-md-9">
<button id="sub" name="submit" class="btn btn-info">Submit</button>
<button id="cancel" class="btn btn-danger">Cancel</button>
</div><!--button col-->
</div><!--row3-->
</form>
<div class="container-fluid">
<br />
<div class="row">
<br />
<p id="result"></p>
</div>
</div><!--result-container-->
</div><!--entry container-->
</div><!--entry tab-->
<div class="tab-pane fade" id="View">
<div class="container-fluid" id="view_result"><br />
<form id="viewentry" action="view_insert.php" method="post">
<div class="inputWrapper">
<div class="row">
<div class="col-md-3">
<div class="input_container">
<label for="Client Name">Client Name</label><br />
<input type="text" name="viewclientname" id="viewclientname" onkeyup="viewautocomplete_client()" autocomplete="off"/>
<ul id="viewclientlist_id"></ul>
</div>
</div>
<div class="col-md-3">
<div class="input_container">
<label for="Staff Name">Staff Name</label><br />
<input type="text" id="viewstaff" name="viewstaff" onkeyup="viewautocomplete_staff()" autocomplete="off"/>
<ul id="viewstafflist_id"></ul>
</div>
</div>
<div class="col-md-4">
<label for="Matter">Matter</label><br />
<input type="text" id="matter" name="matter" />
</div>
<div class="col-md-1">
<br />
<button id="add" class="btn btn-info">Add New</button>
</div>
<div class="col-md-1">
<br />
<button id="can" class="btn btn-danger">Cancel</button>
</div>
</div>
</div>
</form>
<p id="done"></p>
<div class="row">
<br /><br /><label for="Search">Search:</label>
<input type="text" id="filter" /><br><br>
</div>
<div id="divGrid">
<table class="footable" data-filter="#filter" id="tableresult">
<thead>
<th>Client name</th>
<th>Staff name</th>
<th>Matter</th>
<th> Delete</th>
</thead>
<?php
include('db.php');
$sql=mysql_query("SELECT * FROM newdata ORDER BY client_name ASC");
while($row=mysql_fetch_array($sql))
{
$id=$row['id'];
$clientname=$row['client_name'];
$staff=$row['staff'];
$matter=$row['matter'];
?>
<tr id="<?php echo $id; ?>" class="edit_tr">
<td class="edit_td" >
<span id="client_<?php echo $id; ?>" class="text"><?php echo $clientname; ?></span>
<input type="text" value="<?php echo $clientname; ?>" class="editbox" id="client_input_<?php echo $id; ?>" />
</td>
<td class="edit_td">
<span id="staff_<?php echo $id; ?>" class="text"><?php echo $staff; ?></span>
<input type="text" value="<?php echo $staff; ?>" class="editbox" id="staff_input_<?php echo $id; ?>"/>
</td>
<td class="edit_td">
<span id="matter_<?php echo $id; ?>" class="text"><?php echo $matter; ?></span>
<input type="text" value="<?php echo $matter; ?>" class="editbox" id="matter_input_<?php echo $id; ?>"/>
</td>
<td class="delete_td"><input type="button" id="del" class="btn btn-danger" value="×"></input></td>
</tr>
<?php
}
?>
</tbody>
<tfoot class="hide-if-no-paging">
<th> </th>
<th>
<div class="pagination pagination-centered"></div>
</th>
<th> </th>
<th> </th>
</tfoot>
</table>
</div>
</div>
</div><!--view tab-->
</div><!--tab content-->
</div><!--panel body-->
</div><!--panel info-->
</div><!--container-->
</header>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script type="text/javascript" src="js/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="js/footable.js"></script>
<script type="text/javascript" src="js/jquery-ui.js"></script>
<script type="text/javascript" src="js/footable.filter.js"></script>
<script type="text/javascript" src="js/footable.paginate.js"></script>
<script type="text/javascript" src="scripts/autocomplete.js"></script>
<script type="text/javascript" src="scripts/view_autocomplete.js"></script>
<script type="text/javascript" src="scripts/footable.js"></script>
<script type="text/javascript" src="scripts/insert_submit.js"></script>
<script type="text/javascript" src="scripts/view_insert.js"></script>
<!--<script type="text/javascript" src="scripts/selected_row.js"></script>-->
<script type="text/javascript" src="scripts/table_edit.js"></script>
<script type="text/javascript" src="scripts/deletefootable_row.js"></script>
<script type="text/javascript">
$(function() {
$( "#date" ).datepicker({
dateFormat: 'yy/mm/dd',
changeMonth: true,
changeYear: true
});
});
</script>
<script>
$(document).ready(function(e) {
var refresher = setInterval("update_content();",60000); // 60 seconds
})
function update_content(){
$.ajax({
type: "GET",
url: "main.php", // post it back to itself - use relative path or consistent www. or non-www. to avoid cross domain security issues
cache: false, // be sure not to cache results
})
.done(function( page_html ) {
// alert("LOADED");
var newDoc = document.open("text/html", "replace");
newDoc.write(page_html);
//alert(page_html);
newDoc.close();
});
}
</script>
</body>
</html>
jquery's .load() method does exactly this:
function update_content() {
$('#divGrid').load('main.php #divGrid>table');
}

Can't create table in HTML using AJAX and JSON response

I'm trying to get data from DB with PHP and export it to JSON file, I'm also trying to display it in my HTML file using AJAX but without success.
I tried to use external JS file and calling for it from Success in AJAX and I tried also to write the function into Success part.
What I did wrong ?
<!DOCTYPE html>
<html>
<head>
<title>DataBase Project - Tom Yahav</title>
<link rel="stylesheet" href="include/style.css"/>
<link rel="stylesheet" href="showTable.js"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
</head>
<header>
<h1>Database - Students</h1>
</header>
<body>
<div id="wrapper">
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header"> </div>
<div>
<ul class="nav navbar-nav">
<li>Home</li>
<li class="active">Add/Remove Students</li>
<li>Add/Remove Teachers</li>
<li>Add/Remove Courses</li>
<li>Top 3 Students</li>
</ul>
</div>
</div>
</nav>
<div class="container">
<div class="insertData">
<form class="form-horizontal">
<div class="form-group">
<label for="" class="col-sm-2 control-label">Student ID:</label>
<div class="col-sm-10">
<input type="number" class="form-control" id="" placeholder="Student ID">
</div>
</div>
<div class="form-group">
<label for="" class="col-sm-2 control-label">Student Name:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="" placeholder="Student name">
</div>
</div>
<div class="form-group">
<label for="" class="col-sm-2 control-label">Student Address:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="" placeholder="Student Address">
</div>
</div>
<div class="form-group">
<label for="" class="col-sm-2 control-label">Student Birth Date:</label>
<div class="col-sm-10">
<input type="datetime" class="form-control" id="" placeholder="Student Birth Date">
</div>
</div>
<div class="rightButtons">
<button type="button" class="btn btn-success">Add</button>
<button type="button" class="btn btn-danger">Erase</button>
<button type="button" class="btn btn-warning">Update</button>
</div>
</form>
</div>
<br>
<br>
<script>
$(function() {
$("#posts").submit(function() {
var txt = $("#txt").val();
var title = $("#title").val();
var dataString = 'txt=' + txt + '&title=' + title;
$("#loader").show();
$("#loader").fadeIn(300).html('<span class="loading">Loading..</span>');
$.ajax({
type: "GET",
url: "jsonStudent.php",
data: dataString,
cache: true,
success: function(html){
$("#loader").after(html);
$("#loader").hide();
}
});
return false;
});
});
</script>
<form method="post" id="posts" action="">
<input type="submit" value="Display Students" name="submit" class="btnSubmit">
</form>
<div id="loader"></div>
<table id="table1">
<thead></thead>
</table>
</div>
</div>
</body>
</html>
And the External JS file is:
function createTableByForLoop(data)
{
var eTable="<table><thead><tr><th colspan='3'>Created by for loop</th></tr><tr><th>Name</th><th>Title</th><th>Salary</th</tr></thead><tbody>"
for(var i=0; i<data.length;i++)
{
eTable += "<tr>";
eTable += "<td>"+data[i]['name']+"</td>";
eTable += "<td>"+data[i]['title']+"</td>";
eTable += "<td>"+data[i]['salary']+"</td>";
eTable += "</tr>";
}
eTable +="</tbody></table>";
$('#forTable').html(eTable);
}
The PHP file:
function printStudents() {
$host="127.0.0.1";
$port=3306;
$user="root";
$password="root";
$dbname="courcessystem";
$con = new mysqli($host, $user, $password, $dbname, $port)
or die ('Could not connect to the database server' . mysqli_connect_error());
$sql = "SELECT * FROM teacher";
$result = mysqli_query($con, $sql) or die("Error in Selecting " . mysqli_error($con));
$emparray = array();
while($row =mysqli_fetch_assoc($result)) {
$emparray[] = $row;
}
echo json_encode($emparray);
$con->close();
}
printStudents();
?>
Thank you!
Given that jsonStudent.php outputs something like:
[
{
"name": "X",
"title": "X",
"salary": 0
}
]
Change the ajax code to something like this:
$.ajax({
type: "GET",
dataType: "json",
url: "jsonStudent.php",
data: dataString,
cache: false, // You don't want to use cache for this
success: function(data){
createTableByForLoop( data );
$("#loader").hide();
}
});
Also, #forTable doesn't exist in the html.

Categories