fetching rows from ajax and append in existing last row - javascript

This is my view of page.
This is the code of above page.
When i click on any page button i got that page script in alert(data). but i want from here only rows of this page and
append below the existing rows
.
<script>
$( document ).ready(function() {
$('button[id^="next"]').on('click', function() {
var page = ($(this).attr('value'));
$.ajax({
type: "GET",
url: 'index.php?act=product',
data: ({page:page}),
success: function(data) {
alert(data); // what to do i here. please suggest me.
}
});
});
});
</script>
My existing rows is here
<tbody>
<?php foreach($products as $product){ ?>
<tr>
<td class="text-center"><input name="checkbox[]" type="checkbox" value="<?php echo $product['product_id']; ?>"></td>
<td class="text-center"><?php echo $product['name']; ?></td>
<td class="text-center"><?php echo $product['sku']; ?></td>
<td class="text-center"><?php echo $product['status']; ?></td>
<td class="text-center"><?php echo $product['date_time']; ?></td>
<td class="text-center"> Edit</td>
</tr>**//here in the last but this is dynamic <tr>.**
<?php } ?>
</tbody>
Sample of alert(data) is below.
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!----amit bootstrap---->
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="utf-8">
<link rel="stylesheet" href="view/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="view/css/style.css">
<script src="view/js/jquery.min.js"></script>
<script src="view/bootstrap/js/bootstrap.min.js"></script>
<!--validation code start------->
<link rel="stylesheet" href="view/css/jquery-ui.css"/>
<script src="view/js/jquery-ui.js"></script>
<script src="view/js/jquery.validate.min.js"></script>
<script src="view/js/additional-methods.min.js"></script>
<!-- amit bootstrap end ---->
</head>
<script>
function ToggleAll(source) {
var checkboxes = document.getElementsByName('checkbox[]');
for(var i=0, n=checkboxes.length;i<n;i++) {
checkboxes[i].checked = source.checked;
}
}
</script>
<script>
$( document ).ready(function() {
$('button[id^="next"]').on('click', function() {
var page = ($(this).attr('value'));
$.ajax({
type: "GET",
url: 'index.php?act=product',
data: ({page:page}),
success: function(data) {
alert(data);
}
});
});
});
</script>
<body>
<div class="jumbotron text-center">
<h2>View Upload Product</h2>
</div>
<div class="col-sm-12 menu">
<div class="row">
<div class="col-sm-1"></div>
<div class="col-sm-9 text-right"> Back </div>
<div class="col-sm-1 text-right"> Logout </div>
<div class="col-sm-1"></div>
</div><br/>
</div>
<div class="col-sm-12">
<div class="row">
<div class="col-sm-1"></div>
<form role="form" name="deleteproduct" id="deleteproduct" method="POST" action="index.php?act=deleteproduct" class="form-horizontal">
<div class="col-sm-10">
<div class="row">
<div class="col-sm-10"> </div>
<div class="col-sm-2 text-center"><button class="btn btn-primary btn-md" type="submit" name="delete" value="delete">Delete</button></div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="table-responsive">
<table class="table table-bordered table-hover">
<thead>
<tr>
<th class="text-center"><input type='checkbox' name='checkall' onclick='ToggleAll(this);'></th>
<th class="text-center">Name</th>
<th class="text-center">SKU</th>
<th class="text-center">Status</th>
<th class="text-center">Date & Time</th>
<th class="text-center">Action</th>
</tr>
</thead>
<tbody>
<tr>
<td class="text-center"><input name="checkbox[]" type="checkbox" value="27"></td>
<td class="text-center">test</td>
<td class="text-center">123</td>
<td class="text-center">Y</td>
<td class="text-center">2015-08-14 17:38:29</td>
<td class="text-center"> Edit</td>
</tr>
<tr>
<td class="text-center"><input name="checkbox[]" type="checkbox" value="28"></td>
<td class="text-center">test2</td>
<td class="text-center">1qas</td>
<td class="text-center">Y</td>
<td class="text-center">2015-08-14 17:38:29</td>
<td class="text-center"> Edit</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12 text-center">
<button class="btn btn-default btn-md" type="submit" name="magento" value="magento">Magento Upload</button>
</div>
</div>
</div>
</form>
<div class="col-sm-1"></div>
</div>
</div>
<div class="col-sm-12"><br/>
<div class="row">
<div class="col-sm-2"></div>
<div class="col-sm-8 text-center">
<button class='btn page' id='next1' value='1'>1</button><button class='btn page' id='next2' value='2'>2</button> </div>
<div class="col-sm-2"></div>
</div>
</div>
</body>
</html>

Depending on your ajax response format, if it where json, it could be done like this:
$.ajax({
type: "GET",
url: 'index.php?act=product',
data: ({page:page}),
success: function(data) {
var my_data = jQuery.parseJSON(data);
for (var i = 0; i < my_data.length; i++) {
var my_row = $('<tr>');
var my_html = '<td>'+my_data[i].field+'</td>';
my_html += '<td>'+my_data[i].field2+'</td>';
my_row.html(my_html);
$('tbody').append(my_row);
}
}
});
EDIT: But given your code, you need to parse the and append them to your DOM
-EDIT: If you need to make the call just once:
var requestDone = false;
$( document ).ready(function() {
$('button[id^="next"]').on('click', function() {
if( !requestDone) {
$.ajax({
type: "GET",
url: 'index.php?act=product',
data: ({page:page}),
success: function(data) {
var my_rows = $(data).find('tbody').html();
$('tbody').append(my_rows);
requestDone = true;
}
});
}
});
});

Related

How to save multiple form data using jquery ajax in laravel?

I am a bit confused with this. How to save multiple row data in laravel using ajax? The idea is to add products and when click on submit button I want to save the table data in database. I am getting an error as invalid argument supplied for foreach in my controller.
This is my blade template with script.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>Products Invoice</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
</head>
<body>
<div class="container mt-5">
<div class="row" id="invoice-data">
<div class="col-md-12">
<table class="table table-bordered" id="main_table">
<thead>
<tr>
<th scope="col">Product Name</th>
<th scope="col">Description</th>
<th scope="col">Price</th>
<th scope="col">Qty</th>
{{--<th scope="col">Discount</th>--}}
<th scope="col">Amount</th>
<th scope="col">
<button class="btn btn-success addRow">Add More</button>
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<select name="product_name[]" class="form-control productname" id="row_0">
<option>Select Product</option>
#foreach($products as $product)
<option name="product_name[]" value="{{$product->id}}">{{$product->name}}</option>
#endforeach
</select>
</td>
<td><input type="text" name="description[]" class="form-control description" readonly></td>
<td><input type="text" id="price" name="price[]" class="form-control price"
onkeyup="rateChange($(this));" readonly></td>
<td><input type="text" name="qty[]" class="form-control qty" onkeyup="qtyChange($(this));"
onkeypress='return onlynumbers(event);'></td>
{{--<td><input type="text" name="dis[]" class="form-control dis"></td>--}}
<td><input type="text" name="amount[]" id="amount" class="form-control amount" readonly></td>
<td><a class="btn btn-danger remove">X</a></td>
</tr>
</tbody>
</table>
</div>
<div class="col-md-12">
<div class="form-group float-right">
<label for="discount"><b>SubTotal</b></label>
<input type="text" name="subTotal[]" id="subTotal" class="subTotal">
</div>
</div>
<div class="col-md-12">
<div class="form-group float-right">
<label for="discount"><b>Discount <span>%</span></b></label>
<input type="text" name="discount[]" id="discount" class="discount" onkeyup="amount_discount();"
onkeypress='return onlynumbers(event);'>
</div>
</div>
<div class="col-md-12">
<div class="form-group float-right">
<label for="SubTotal"><b>Total</b></label>
<input type="text" name="total[]" id="total" class="total" readonly>
</div>
</div>
<div class="col-md-12">
<div class="form-group float-right">
<button type="button" id="saveInvoice" name="saveInvoice" class="btn btn-success float-right">Submit</button>
</div>
</div>
</div>
</div>
</body>
<script>
$("#saveInvoice").click(function () {
$.ajax({
url: "{{ route('invoice.store') }}",
method: "POST",
data: $("#invoice-data").serialize(),
dataType: "json",
success: function (data) {
console.log(data);
}
});
});
</script>
</html>
And this is my controller to store the data.
public function store(Request $request)
{
$invoices = [];
foreach ($request->input('product_name') as $key => $value) {
$invoices["product_name.{$key}"] = 'required';
$invoices["description.{$key}"] = 'required';
$invoices["price.{$key}"] = 'required';
$invoices["qty.{$key}"] = 'required';
$invoices["amount.{$key}"] = 'required';
$invoices["subTotal.{$key}"] = 'required';
$invoices["discount.{$key}"] = 'required';
$invoices["total.{$key}"] = 'required';
}
$validator = Validator::make($request->all(), $invoices);
if ($validator->passes()) {
foreach ($request->input("product_name") as $key => $value) {
$invoice = new Invoice;
$invoice->product_name = $request->get("product_name")[$key];
$invoice->description = $request->get("description")[$key];
$invoice->price = $request->get("price")[$key];
$invoice->qty = $request->get("qty")[$key];
$invoice->amount = $request->get("amount")[$key];
$invoice->subTotal = $request->get("subTotal")[$key];
$invoice->discount = $request->get("discount")[$key];
$invoice->total = $request->get("total")[$key];
$invoice->save();
}
}
}
It returns me 500 internal server error.
I think you need to print the "$request->input('product_name')" before foreach loop to check product name is coming is an array or not? because error you are getting is " invalid argument supplied for foreach in my controller". Just write print_r($request->input('product_name')) and check value is coming is an array or not?

PHP & Jquery - Set row status as approved/pending via modal

My status column should read Approved or Pending per user row. Upon click of edit button, at bottom of modal should say current status and Yes/No radio buttons to keep as is or change status, and have that reflected in the table.
Right now it's only setting to Pending in the modal upon selecting No, and I need the same logic but upon click of Yes for Approved. Help!
PHP Function:n
public function approve(){
$id = $this->input->get("user_id");
$this->db->where("id", $id);
$data = [
"approved" => 1
];
if (isset($data['approved']) && $data['approved'] == 1) {
$this->db->update("User_Inputs", $data);
redirect("/myform/getdatabase");
}
else {
echo 0;
}
HTML/JQuery:
<html>
<head>
<title>Admin View</title>
<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/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body background=http://wallpapercave.com/wp/ItmVuT6.jpg>
<!-- container with table headers / user records / edit function / approve function -->
<div class="container">
<table class="table table-hover table-striped">
<center>
<thead>
<tr style="font-size: 24; color: white;">
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Status</th>
<th colspan="1">Action</th>
</tr>
</thead>
</center>
<tbody style="background-color: #F0F8FF">
<?php
foreach($users as $u)
{
?>
<tr style="font-size: 20;" id="row<?= $u->id?>">
<td width="5%;"> <?php echo $u->id; ?></td>
<td><?php echo $u->first_name; ?></td>
<td><?php echo $u->last_name; ?></td>
<td><?php echo $u->email; ?></td>
<td><?php echo ($u->approved) ? "Approved" : "Pending"; ?></td>
<!--edit button-->
<td><button type="button" data-id="<?= $u->id ?>" data-first_name="<?= $u->first_name ?>" data-last_name="<?= $u->last_name ?>" data-email="<?= $u->email ?>" data-approved="<?= $u->approved ?>" onclick="loadmodal(this)"><span class='glyphicon glyphicon-edit'></span></button></td>
<!--approve button
<td><span class="glyphicon glyphicon-ok gi-15x" style='color: green'></span></td>-->
</tr>
<?php } ?>
</tbody>
</table>
<!--modal-->
<script type="text/javascript">
function loadmodal(button){
var first_name = $(button).data("first_name");
var last_name = $(button).data("last_name");
var email = $(button).data("email");
var id = $(button).data("id");
var status = $(button).data("approved");
/* pass values to modal */
$("#m_id").val(id);
$("#m_first_name").val(first_name);
$("#m_last_name").val(last_name);
$("#m_email").val(email);
$("#m_approved").val(status);
$("input[name=r1]:checked").val()
$("input[name=r2]:checked").val()
$("#myModalLabel").text("Entry for User ID: " + id);
$("#editModal").modal("show");
$("#formdata").submit(function(e){
e.preventDefault();
var data = $(this).serialize();
$.post("/ci/index.php/myform/edituser", data, function(html){
console.log(html);
var response = $.parseJSON(html);
console.log(response);
if (response.status == 'success'){
$("#row"+id).html(response.html);
$("#editModal").modal("hide");
} else {
console.log('Error updating user');
$("#editModal").modal("hide");
}
});
});
function approveRadio(){
if (document.getElementsByID('r1').checked) {
rate_value = document.getElementsByID
}
var choice = document.getElementsByName('choice').value;
}
}
</script>
<div class='modal fade' id='editModal' tabindex='-1' role='dialog' aria-labelledby='myModalLabel'>
<div class='modal-dialog'>
<div class='modal-content'>
<div class='modal-header'>
<h3 class="modal-title" id='myModalLabel'></h3>
<button type='button' class='close' data-dismiss='modal' aria-label="Close"><span class='glyphicon glyphicon-remove'></span></button>
</div>
<!--modal body-->
<div class='modal-body'>
<form id="formdata">
<input type="hidden" id="m_id" name="id" value="">
<div class='form-group'>
<label class='control-label' for='First Name'>First Name</label>
<input type='text' id="m_first_name" name='first_name' class='form-control'
value=""><br/>
</div>
<div class='form-group'>
<label class='control-label' for='Last Name'>Last Name</label>
<input type='text' id="m_last_name" name='last_name' class='form-control' value=""/><br/>
</div>
<div class='form-group'>
<label class='control-label' for='Last Name'>Email</label>
<input type='text' id="m_email" name='email' class='form-control' value=""/><br/>
</div>
<div class='form-group'>
<label class='control-label' for='Approved'>Is user approved? Current status:</label><br>
<input type="radio" id="r1" name="approved" value="1"> Yes
<input type="radio" id="r2" name="approved" value="0"> No
<!--m<input type="text" id="m_approved" name="status" class='form-control' value="">-->
</div>
<button type='submit' class='btn btn-success'>Update Entry</button>
</form>
</div>
</div>
</div>
</div>
</body>
</html>

Ajax not working on multiple inserts - CI

I want to save multiple data in one go using codeigniter and then on success load the data on my datatable wihtout refreshing the whole page. I am able to do this successfully if I use modal and insert a single value but when I try to save multiple values, it doesn't work. I produce my input boxes on button click. Below are my codes:
CONTROLLER
public function add_multiple_orders(){
$dataset=[];
$item_name=$this->input->post('m_item_name');
$quantity=$this->input->post('m_quantity');
$amount=$this->input->post('m_amount');
$order_comment=$this->input->post('m_order_comment');
$branch_name=$this->input->post('m_branch_name');
$date_added=$this->input->post('m_date_added');
for($i=0;$i<sizeof($item_name);$i++){
$dataset[$i]=array(
'date_added'=>$date_added,
'item_name'=>$item_name[$i],
'quantity'=>$quantity[$i],
'amount'=>$amount[$i],
'ordered_by'=>$this->session->userdata['username'],
'order_status'=>'ordered',
'order_comment'=>$order_comment[$i],
'branch_name'=>$branch_name
);
}
$result=$this->sales_model->insert_mult_orders($dataset);
}
VIEW
<a name="mult_page">
<button class="btn btn-info" data-toggle="collapse" data-target="#add_multiple" style="margin-left: 20px;">Add Multiple Orders</button>
<div class="collapse" id="add_multiple" style="width: 95%; margin: 0 auto; margin-top: 10px;">
<div class="row">
<div class="col-md-12">
<div class="panel panel-primary">
<div class="panel-heading">
</div>
<div class="panel-body">
<form class="form_mult_ordrs form-inline" method="post">
<div class="form-group">
<label for="m_date_added">Date</label>
<input type="date" name="m_date_added" required>
</div>
<div class="form-group">
<label for="m_branch_name" class="control-label">Branch Name</label>
<select name="m_branch_name" class="form-control">
<option value="superdome">Superdome</option>';
<option value="seaside">Sea Side</option>
<option value="robinsons">Robinsons</option>
</select>
</div>
<div class="btn btn-warning pull-right" onclick="add_new_row()">Add more</div>
<hr>
<div style="font-weight: bold;">Total Php <input type="text" id="total_result" placeholder="0.00" class="form-control"></div>
<br>
<table id="mult_ord_tbl" class="table table-striped table-bordered table-condensed">
<thead>
<tr>
<th class="ui-help-center">Item Name</th>
<th class="ui-help-center">Quantity</th>
<th class="ui-help-center">Amount</th>
<th class="ui-help-center">Comment</th>
<th class="ui-help-center">Delete</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<select name="item_name[]" class="form-control">
<?php foreach($items as $item){
echo '<option value"='.$item->item_name.'">'.$item->item_name.'</option>';
} ?>
</select>
</td>
<td><input type="text" name="m_quantity[]" placeholder="Quantity"></td>
<td><input type="text" name="m_amount[]" id='m_amount[]' placeholder="Amount" onblur="total_values()"></td>
<td><input type="text" name="m_order_comment[]" placeholder="Commment"></td>
<td>
<button class="btn btn-danger" onclick="delete_row(this)"><i class="glyphicon glyphicon-remove"></i></button>
</td>
</tr>
</tbody>
</table>
<tr>
<td colspan="12">
<button id="btn_mult_ordrs" class="btn btn-success" onclick="save_mult_ordrs()" value="">Submit All</button>
</td>
</tr>
</form>
</div> <!-- end of panel body -->
<div class="panel-footer">
footer
</div>
</div> <!-- end of panel primary -->
</div> <!-- end of column 12 -->
</div> <!-- end of row -->
</div> <!-- end of collapse -->
<script type="text/javascript">
$(document).ready(function(){
$('#table_id').DataTable({
"order":[[0,"desc"]]
});
});
function save_mult_ordrs(){
if(confirm("Are you done?")){
var url="<?php echo site_url('sales/add_multiple_orders')?>";
add_new_row();
// $("#form_mult_ordrs").submit();
$.ajax({
url:url,
type:"POST",
data:$('#form_mult_ordrs').serialize(),
datatype:"JSON",
success:function(data)
{
alert('All data has been saved.');
location.reload();
},
error:function(jqXHR, textStatus, errorThrown){
alert('Error in saving.');
}
});
}
}
function add_new_row(){
var arrTables = document.getElementById('mult_ord_tbl');
var oRows = arrTables.rows;
var numRows = oRows.length;
var newRow = document.getElementById('mult_ord_tbl').insertRow( numRows );
var cell1=newRow.insertCell(0);
var cell2=newRow.insertCell(1);
var cell3=newRow.insertCell(2);
var cell4=newRow.insertCell(3);
var cell5=newRow.insertCell(4);
cell1.innerHTML = "<tr><td><select name='m_item_name[]' class='form-control'>" +
<?php
foreach($items as $item){
echo ('"<option value=\"'.$item->item_name.'\">'.$item->item_name.'</option>"+');
}
?>
+ "</select></td>";
cell2.innerHTML="<td height='5'><input type='text' name='m_quantity[]' placeholder='Quantity'></td>";
cell3.innerHTML="<td height='5'><input type='text' name='m_amount[]' placeholder='Amount' onblur='total_values()'></td>"
cell4.innerHTML="<td height='5'><input type='text' name='m_order_comment[]' placeholder='Comment'></td>";
cell5.innerHTML="<td><button class='btn btn-danger' onclick='delete_row(this)''><i class='glyphicon glyphicon-remove'></i></button></td></tr>";
}
</script>
MODEL
public function insert_mult_orders($data){
$this->db->insert_batch('piercapitan.sls_ordrs',$data);
return $this->db->affected_rows();
}
Your help is immensely appreciated.
Never mind guys. I found what's wrong. It's my form id! I somehow placed the name on the class and not on the id.
<form class="form_mult_ordrs form-inline" method="post">
It should have been:
<form id="form_mult_ordrs" class="form-inline" method="post">

ajax wont respond after called on dropdown in PHP

I tried to grab data from API using php through ajax on my html page, when I tried to make direct link it works successfully but when i trying to call it with ajax on my drop down, it is like failed to call ajax..
Here is my html
<head>
<link rel="stylesheet" type="text/css" href="css/normalize.css">
<link rel="stylesheet" type="text/css" href="css/skeleton.css">
<script type="text/javascript" src="js/jquery-2.1.3.min.js">
</script>
<script type="text/javascript" src="js/script.js"></script>
<title>Penggunaan API RajaOngkir | IDMore</title>
</head>
<body>
<div class="container">
<div class="row">
<br />
<div class="twelve columns">
<h1>Hitung Ongkos Kirim</h1>
</div>
</div>
<div class="row">
<div class="twelve columns">
<h5>Masukan Data</h5>
</div>
</div>
<div class="row">
<div class="two columns">Asal
<br />
<select id="oriprovince">
<option>Province</option>
</select></div>
<div class="two columns">
<br />
<select id="oricity">
<option>Kota</option>
</select>
</div>
<div class="two columns">Tujuan
<br />
<select id="desprovince">
<option>Provinsi</option>
</select></div>
<div class="two columns">
<br />
<select id="descity">
<option>Kota</option>
</select>
</div>
<div class="two columns">Layanan
<br />
<select id="service">
<option>JNE</option>
<option>POS</option>
<option>TIKI</option>
</select></div>
<div class="two columns">
<br />
<button id="btncheck">Cek Harga</button>
</div>
</div>
<div class="row">
<div class="twelve columns">
<h5>Harga</h5>
</div>
<hr />
<table class="twelve columns">
<tr>
<th>Servis</th>
<th>Deskripsi Servis</th>
<th>Lama Kirim (hari)</th>
<th>Total Biaya (Rp)</th>
</tr>
<span id="resultsbox">
<tr>
<td>...</td>
<td>...</td>
<td>...</td>
<td>...</td>
</tr>
<tr>
<td>...</td>
<td>...</td>
<td>...</td>
<td>...</td>
</tr>
</span>
</table>
</div>
</div>
</body>
Here is my javascript.
$(document).ready(function() {
loadProvinsi('#oriprovince');
loadProvinsi('#desprovince');
$('#oriprovince').change(function() {
alert('yussan');
});
$('#desprovince').change(function() {
alert('yussan');
});
});
function loadProvinsi(id) {
$('#oricity').hide();
$('#descity').hide();
$(id).html('loading...');
$.ajax({
url: 'process.php?act=showprovince',
dataType: 'json',
success: function(response) {
$(id).html('');
province = '';
$.each(response['rajaongkir']['results'], function(i, n) {
province = '<option value="n[province_id]">'+n['province']+'</option>';
<option></option>
province = province + '';
$(id).append(province);
});
},
error: function() {
$(id).html('ERROR');
}
});
}
$.each(response['rajaongkir']['results'], function(i, n) {
var option = '<option value="'+n['province_id']+'">'+n['province']+'</option>';
province += option;
});
$(id).append(province);
Please replace your each function with this code.And try again.

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');
}

Categories