how to pass multiple parameter in ajax call using jquery - javascript

Greeting of the Day!!!
I am facing problem in passing parameters with ajax URL.
i am trying to send multiple data using jquery $.ajax method to my php script but i can pass only single data when i concatenate multiple data.
when I try to update another fields but that field not update and first one is updated. only first field update. remains fields are not update. I am facing problem to update another fields. and also I try to pass multiple parameter in ajax URL but getting error. not update any fields.
Please check my code and give me solution.
I hope you all are understand.
Thank You!!!
Here is my code:
<?php
include("connect.php");
?>
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<meta charset="utf-8">
<title>Editable Tables using jQuery - jQuery AJAX PHP</title>
<link href="assets/css/bootstrap.min.css" rel="stylesheet" type="text/css">
<link href="assets/css/custom.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="container">
<div style="text-align:center;width:100%;font-size:24px;margin-bottom:20px;color: #2875BB;">Click on the underlined words to edit them</div>
<div class="row">
<table class= "table table-striped table-bordered table-hover">
<thead>
<tr>
<th colspan="1" rowspan="1" style="width: 180px;" tabindex="0">FName</th>
<th colspan="1" rowspan="1" style="width: 220px;" tabindex="0">LName</th>
<th colspan="1" rowspan="1" style="width: 288px;" tabindex="0">Email</th>
<th colspan="1" rowspan="1" style="width: 288px;" tabindex="0">Gender</th>
<th colspan="1" rowspan="1" style="width: 288px;" tabindex="0">Address</th>
<th colspan="1" rowspan="1" style="width: 288px;" tabindex="0">City</th>
<th colspan="1" rowspan="1" style="width: 288px;" tabindex="0">Course</th>
<th colspan="1" rowspan="1" style="width: 288px;" tabindex="0">Hobby</th>
</tr>
</thead>
<tbody>
<?php
$query = mysql_query("SELECT * FROM student_data");
$i=0;
while($fetch = mysql_fetch_array($query))
{
if($i%2==0) $class = 'even'; else $class = 'odd';
echo'<tr class="'.$class.'">
<td><span class= "xedit" id="'.$fetch['id'].'">'.$fetch['fname'].'</span></td>
<td><span class= "xedit" id="'.$fetch['id'].'">'.$fetch['lname'].'</span></td>
<td><span class= "xedit" id="'.$fetch['id'].'">'.$fetch['email'].'</span></td>
<td><span class= "xedit" id="'.$fetch['id'].'">'.$fetch['gender'].'</span></td>
<td><span class= "xedit" id="'.$fetch['id'].'">'.$fetch['address'].'</span></td>
<td><span class= "xedit" id="'.$fetch['id'].'">'.$fetch['city'].'</span></td>
<td><span class= "xedit" id="'.$fetch['id'].'">'.$fetch['course'].'</span></td>
<td><span class= "xedit" id="'.$fetch['id'].'">'.$fetch['hobby'].'</span></td>
</tr>';
}
?>
</tbody>
</table>
</div>
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/bootstrap.min.js"></script>
<script src="assets/js/bootstrap-editable.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery(document).ready(function() {
$.fn.editable.defaults.mode = 'popup';
$('.xedit').editable();
$(document).on('click','.editable-submit',function(){
var x = $(this).parents('td').children('span').attr('id');
var y = $('.input-sm').val();
var z = $(this).parents('td').children('span');
alert(x);
alert(y);
alert(z);
$.ajax({
url:"process.php?id="+x+"&fname="+y,
type: 'GET',
success: function(s){
if(s == 'city'){
$(z).html(y);}
if(s == 'error') {
alert('Error Processing your Request!');}
},
error: function(e){
alert('Error Processing your Request!!');
}
});
});
});
</script>
</div>
</body>
</html>
Here is my another file:
<?php
include("connect.php");
if($_GET['id'])
{
$id = $_GET['id'];
$fname = $_GET['fname'];
$lname=$_GET['lname'];
$email=$_GET['email'];
$gender=$_GET['gender'];
$address=$_GET['address'];
$city=$_GET['city'];
$course=$_GET['course'];
$hobby = explode(',', $_GET['hobby']);
if(mysql_query("UPDATE student_data SET fname='$fname', lname = '$lname', email = '$email', gender='$gender', address='$address', city='$city', course='$course', hobby='$hobby' where id='$id'"));
echo 'success';
}
?>
Here Ajax Code :
<script type="text/javascript">
jQuery(document).ready(function() {
$.fn.editable.defaults.mode = 'popup';
$('.xedit').editable();
$(document).on('click','.editable-submit',function(){
var x = $(this).parents('td').children('span').attr('id');
var y = $('.input-sm').val();
var z = $(this).parents('td').children('span');
alert(x);
alert(y);
alert(z);
$.ajax({
url:"process.php?id="+x+"&fname="+y,
type: 'GET',
success: function(s){
if(s == 'city'){
$(z).html(y);}
if(s == 'error') {
alert('Error Processing your Request!');}
},
error: function(e){
alert('Error Processing your Request!!');
}
});
});
});
</script>

The issue is here:
url:"process.php?id="+x+"&fname="+y,
here you are sending only id and fname and in php script you are trying to get:
$id = $_GET['id'];
$fname = $_GET['fname'];
$lname=$_GET['lname'];
ans so many parameters, which is wrong.
The correct approach to send multiple parameter is:
data: {
key1: value1,
key2: value2,
key3: value3,
and so on
}
or format the proper url by appending all the key : value in it like:
key1=value1&key2=value2&key3=value3

For Sending Single Parameter
data: "id="+id,
For Sending Multiple Parameters
data: {
id: id,
fname: fname
},

Related

Sorting icon not replace jquery ajax php

I am working on "sort tables" in ajax jquery with php,My sorting
function working properly but need to hide/show "sorting images", Right now one sided (desc)
sorting is working because unable to replace/change sorting image and status,
I just want whenever i click on "upper" icon then its status(asc) should pass and "down" image should display and if i click on "down" icon then status should pass and "up" icon should display,
Here is my code
<table border='1' width='100%' style='border-collapse: collapse;' id='postsList'>
<thead>
<tr>
<th>S.no</th>
<th class="column_sort" id="name" data-order="desc" href="#">Title
<img id="ASC" datas-order="desc" src="<?php echo base_url();?>/assets/img/UpArrow.png">
<img id="DESC" datas-order="asc" src="<?php echo base_url();?>/assets/img/DownArrow.png" style="display:none;">
</th>
<th class="column_sort" id="symbol" data-order="desc" href="#">Symbol
<img id="ASC" datas-order="desc" src="<?php echo base_url();?>/assets/img/UpArrow.png">
<img id="DESC" datas-order="asc" src="<?php echo base_url();?>/assets/img/DownArrow.png" style="display:none;">
</th>
</tr>
</thead>
<tbody></tbody>
</table>
Here is my php script code,Where i am wrong ?
<script>
$(document).ready(function(){
$(document).on('click', '.column_sort', function(){
var column_name = $(this).attr("id");
var order = $(this).data("order");
var arrow = '';
var PageNumber= $("#pagination").find("strong").html();
if(order == 'desc')
{
arrow = ' <span class="glyphicon glyphicon-arrow-down"></span>';
}
else
{
arrow = ' <span class="glyphicon glyphicon-arrow-up"></span>';
}
$.ajax({
url:'<?=base_url()?>/Main/fetch_details/',
method:"POST",
data:{column_name:column_name, order:order ,PageNumber:PageNumber},
success:function(data)
{
$("#postsList tr:not(:first)").remove();
$("#postsList2").show();
$("#postsList2").html(data);
$('#'+column_name+'').replace('<img src="<?=base_url()?>/assets/img/DownArrow.png"/>');
return false;
}
})
});
});
</script>
Toggle:
$("#postsList .column_sort").on("click", "img" ,function(e) {
$(this).sibling().toggle()
$(this).toggle()
})
or have just one image
$("#postsList").on("click","[data-order]",function(e) {
this.src = this.dataset.order === "desc" ? "/assets/img/UpArrow.png" : "/assets/img/DownArrow.png"
})

Codeigniter ajax status code shows 200 but display error message

Just try to make it simple.
I'm trying to show data in my data table when I click a dropdown value
I'm using ajax to get the data from my controller
everything works fine except the results isn't showing in my view even the status code shows 200 ok
here's my Model
function tampil_renja(){
$this->db->distinct();
$this->db->select
(
'lkp_program.progskpd_id AS prog_id,
CONCAT(msr_mstrurusan.uru_kode, '.', lkp_program.progskpd_kode) AS prog_kode,
lkp_program.progskpd_prog_uraian as prog_uraian');
$this->db->from('msr_mstrurusan');
$this->db->join('lkp_program', 'msr_mstrurusan.uru_id = lkp_program.progskpd_ursid');
$this->db->join('lkp_kegiatan', 'lkp_program.progskpd_id = lkp_kegiatan.kegskpd_prog_id');
$this->db->join('mnv_keg_renja', 'lkp_kegiatan.kegskpd_id = mnv_keg_renja.tar_keg_id');
$this->db->where('mnv_keg_renja.tar_keg_id is NOT NULL', NULL, FALSE);
$this->db->order_by("lkp_program.progskpd_id", "asc");
return $this->db->get();
}
here's my ajax code within the view
<div class="container-fluid">
<header>
<h3 class="mb-2">Renja</h3>
</header>
<div class="card-body">
<div class="table-responsive" style="margin-bottom: 1px;">
<?php
if (count($skpd) > 0) {
?>
<label class="col-sm-1 control-label">OPD</label>
<div class="col-sm-5">
<select id="skpd" name="skpd" class="form-control input-sm">
<option value="0">-- Pilih Perangkat Daerah--</option>
<?php
foreach ($skpd as $pd) {
echo "<option value='" . $pd->uk_kowil . "#" . $pd->uk_id . "'>" . strtoupper($pd->uk_nama) . "</option>";
}
?>
</select>
</div>
<?php
}
else {
?>
<input type='hidden' name='skpd' id='skpd' value='<?php
?>' />
<?php
}
?>
<div id="listskpd" class="col-sm-1">
<i id="rldspin" style="margin-top:5px"></i>
</div>
<div id="jml_angg" class="text-right" style="padding-top: 8px;font-size: 13px;margin-right: 15px;">
</div>
</div>
<table id="list_target" class="table table-striped table-bordered table-hover" width="100%">
<thead>
<tr>
<th rowspan="3" class="text-center text-middle" style="width:1%;">No</th>
<th rowspan="3" class="text-center text-middle" style="width:4%;">Kode Rekening</th>
<th rowspan="3" class="text-center text-middle" style="width:27%;">Program/Kegiatan</th>
<th rowspan="3" class="text-center text-middle" style="width:20%;">Indikator Kinerja program (outcome)/ kegiatan (output) </th>
<th colspan="7" class="text-center text-middle" style="width:30%;">Target Renja [berdasarkan DPA] SKPD pada Tahun</th>
</tr>
<tr>
<th rowspan="2" class="text-center text-middle" style=""> Satuan</th>
<th colspan="2" class="text-center text-middle" style="">Target Triwulan 1</th>
<th colspan="2" class="text-center text-middle" style="">Target Triwulan 2</th>
<th colspan="2" class="text-center text-middle" style="">Target Triwulan 3</th>
<th colspan="2" class="text-center text-middle" style="">Target Triwulan 4</th>
<th rowspan="2" class="text-center text-middle" style="">Target Anggaran</th>
</tr>
<tr>
<th class="text-center text-middle" style="">Kin</th>
<th class="text-center text-middle" style="">Keu</th>
<th class="text-center text-middle" style="">Kin</th>
<th class="text-center text-middle" style="">Keu</th>
<th class="text-center text-middle" style="">Kin</th>
<th class="text-center text-middle" style="">Keu</th>
<th class="text-center text-middle" style="">Kin</th>
<th class="text-center text-middle" style="">Keu</th>
</tr>
</thead>
<tbody id="datatarget">
</tbody>
</table>
</div>
</div>
</article>
<script type="text/javascript" language="javascript" src="<?php echo base_url().'assets/vendor/jquery/jquery.js'?>"></script>
<script type="text/javascript" language="javascript" src="<?php echo base_url().'assets/vendor/datatables/jquery.dataTables.js'?>"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#skpd').change(function(){
var arrval = $(this).val().split("#");
var kowil = arrval[0];
var idpd = arrval[1];
if(idpd != 0){;
tampil_data_renja(kowil, idpd);
} else {
$('#datatarget').DataTable.Destroy();
$('#datatarget').DataTable.Draw();
$('#datatarget').DataTable.Destroy();
}
});
function tampil_data_renja(kowil, idpd){
$.ajax({
type : 'ajax',
url : '<?php echo base_url()?>renja/tampil_renja/',
async : false,
dataType : 'json',
success : function(data){
var html = '';
var i;
alert(data.length);
for(i=0; i<data.length; i++){
html += '<tr>'+
'<td>'+(i+1).toString()+'</td>'+
'<td>'+data[i].prog_kode+'</td>'+
'<td>'+data[i].prog_uraian+'</td>'+
'</tr>';
}
$('#datatarget').html(html);
},
error: function(){
alert('Could not load the data');
}
});
}
and this is the controller
function tampil_renja(){
echo json_encode( $this->m_data->tampil_renja()->result() );
}
JSON result in the network tab of chrome dev tools
[{"prog_id":"1","prog_kode":"6.01.0118","prog_uraian":"Program Koordinasi, pembinaan dan penyelenggaraan pemerintahan, ketentraman dan ketertiban umum, perekonomian, kesejahteraan sosial dan pembangunan"},{"prog_id":"2","prog_kode":"6.01.0118","prog_uraian":"Program Koordinasi, pembinaan dan penyelenggaraan pemerintahan, ketentraman dan ketertiban umum, perekonomian, kesejahteraan sosial dan pembangunan"}]
any help and guide would be appreciated
sorry for my bad english by the way
Please try the following code:
Changes made are:
commented datatype in the AJAX
parse response of success function as JSON.
$.ajax({
type : 'get', // edit 1
url : '<?php echo base_url()?>renja/tampil_renja/',
async : false,
//dataType : 'json', //change over here
success : function(data){
data = JSON.parse(data); //change over here
var html = '';
var i;
alert(data.length);
for(i=0; i<data.length; i++){
html += '<tr>'+
'<td>'+(i+1).toString()+'</td>'+
// '<td>'+data[i].prog_id+'</td>'+
'<td>'+data[i].prog_kode+'</td>'+
'<td>'+data[i].prog_uraian+'</td>'+
'</tr>';
}
$('#datatarget').html(html);
},
error: function(){
alert('Could not load the data');
}
})
You have to redraw the datatable after the element is updated on ajax call success :
//fungsi tampil barang
function tampil_data_renja(kowil, idpd){
// var requrl = '<?php echo base_url()?>renja/tampil_renja/'+kowil+'/'+idpd;
$.ajax({
type : 'ajax',
// url : '<?php echo base_url()?>renja/tampil_renja/'+kowil+'/'+idpd,
url : '<?php echo base_url()?>renja/tampil_renja/',
async : false,
dataType : 'json',
success : function(data){
var html = '';
var i;
// console.log(data.length);
alert(data.length);
for(i=0; i<data.length; i++){
html += '<tr>'+
'<td>'+(i+1).toString()+'</td>'+
// '<td>'+data[i].prog_id+'</td>'+
'<td>'+data[i].prog_kode+'</td>'+
'<td>'+data[i].prog_uraian+'</td>'+
'</tr>';
}
$('#datatarget').html(html);
$('#list_target').DataTable.Draw(); // redraw the datatable
},
error: function(){
alert('Could not load the data');
}
});
// return alert(kowil);
}

PHP / AJAX checkbox values

I'm trying to get all checked checkbox values and parse them to my php functin using AJAX.
I use foreach to try and get each id of the checked checkbox's.
My problem is that when I try and update the database, it doesn't return '1' which I echo upon success.
When I take my foreach code out, it works.
My delete button is :
<form class="form -dark" id="form-inline" method="POST">
<div class="btn-group">
<button type="button" onclick="deleteSelectedTokens()" class="btn -dark" style="margin-left: 5px;" title="Delete all selected tokens"><i class="fa fa-trash"> </i></a>
</div>
</form>
My checkbox html/php code is :
<table class="table -dark -striped">
<thead>
<tr>
<th style="text-align: center;"><input type="checkbox" id="selectall"/></th>
<th style="text-align: center;">Token</th>
<th style="text-align: center;">Date/Time Generated</th>
<th style="text-align: center;">Status</th>
<th style="text-align: center;">Durbaility</th>
</tr>
</thead>
<tbody>
<tr>
<?php
$username = $_SESSION['username'];
$token_result = mysqli_query($con, "SELECT id, token, used, time_generated, durability FROM tokens WHERE user_id = '$username' ORDER BY used");
if(mysqli_num_rows($token_result) > 0) {
while($token_row = mysqli_fetch_array($token_result)) {
$result = array($token_row['durability']); $sub_struct_month = ($result[0] / 30) ; $sub_struct_month = floor($sub_struct_month); $sub_struct_days = ($result[0] % 30); $sub_struct = "<i>".$sub_struct_month."</i> month(s) <i>".$sub_struct_days."</i> day(s)";
echo '
<tr style="text-align: center;">
<td>
<center><input type="checkbox" id="checkedTokens" class="checkbox" value='.($token_row['id']).'></center>
</td>
<td>
'.$token_row['token'].'
</td>
<td>
'.($token_row['time_generated']).'
</td>
<td>
'.($token_row['used'] == "0" ? "<span class='label label-primary'><i class='fa fa-check'></i> Valid </span>" : "<span class='label label-primary'><i class='fa fa-fa fa-times'></i> Used </span>").'
</td>
<td>
'.$sub_struct.'
</td>
';
} }else{ ?>
<tr>
<td colspan="12" style="padding: 30px;">
<div class="alert -dark">
<div class="alert-icon _text-danger">
<i class="fa fa-exclamation-circle"></i>
</div>
No tokens in your account
</div>
</td>
</tr>
<?php } ?>
</tr>
</tbody>
Notice I need to use foreach to get each check checkbox value so I can remove the selected ones when I press the delete button.
My AJAX send to PHP function is :
<script>
function deleteSelectedTokens() {
var selectedTokens = document.getElementById("checkedTokens").value;
$.ajax({
type: "POST",
url: "includes/form_submit.php",
data: {
deleteSelectedTkns: true,
checked_id: selectedTokens
},
success: function(msg){
if(msg == 1) {
update_myDays_success();
} else {
general_error_forms();
}
},
});
return false;
}
</script>
I think the problem is the Javascript... when I get the value of the checkboxes and post them, i think it's only getting 1 value inside the checkedTokens id.
My php receive code (this is not the problem) :
$username = $_SESSION['username'];
$selectedTokens = mysqli_real_escape_string($con, $_POST['checked_id']);
foreach($selectedTokens as $id) {
$doUpdateDelete = 'DELETE FROM tokens WHERE id = "'.$id.'" AND user_id = "'.$username.'"';
$result = $con->query($doUpdateDelete) or die("Error");
if($result)
{
echo '1';
}
else
{
echo 'Failed';
}
}
My console.log has not errors. Like I said, i think it's the javascript code for getting the value of my checkbox's not getting all the values.
You can send json of checked items:
<script>
var selectedTokens = [];
$('#checkedTokens:checked').each(function(key, value){
selectedTokens.push($(value).val());
});
$.ajax({
type: "POST",
url: "includes/form_submit.php",
data: {
deleteSelectedTkns: true,
checked_id: JSON.stringify(selectedTokens)
},
success: function(msg){
if(msg == 1) {
update_myDays_success();
} else {
general_error_forms();
}
},
});
</script>
And your php code mysqli_real_escape_string give only string we should convert json to get array:
$selectedTokens = json_decode($_POST['checked_id']);
foreach($selectedTokens as $id) {
$doUpdateDelete = 'DELETE FROM tokens WHERE id = "'.$id.'" AND user_id = "'.$username.'"';
$result = $con->query($doUpdateDelete) or die("Error");
if($result)
{
echo '1';
}
else
{
echo 'Failed';
}
}
In html it is not allowed to assign the same id to multiple tags. (As already mentioned in the comments.)
If you place your checkboxes on a <form id="some_id">, and give every checkbox a unique name and id, you can use the function $('#some_id').serialize() to get the data of the form and post it to the server.

how to reload javascript function without reloading the whole page

Previously i found the solution for div here Stackoverflow link
this page talks about reloading a div but my problem is different
here is my index page
<?php
$message = "";
$minutes = "";
$limit = 2;
$effect = "";
$start = "";
$end = "";
require_once('db.php');
$query = mysql_query("SELECT message FROM kioskmessage where recNo = 1");
$row = mysql_fetch_assoc($query);
$message = $row['message'];
?>
<?php
$query = mysql_query("SELECT effect FROM kioskmessage where recNo = 1");
$row = mysql_fetch_assoc($query);
$effect = $row['effect'];
if($effect == "blink")
{
$start = '<p class="blink_text">';
$end = "</p>";
}
elseif($effect == "scrolling")
{
$start = "<marquee>";
$end = "</marquee>";
}
else
{
$start = '<p class="normalmessage">';
$end = "</p>";
}
?>
<?php
$query = mysql_query("select minutes from getminutes where id = 1");
$row = mysql_fetch_assoc($query);
$minutes = $row['minutes'];
?>
<html>
<header>
<div class="img"> <img src="images/logo.png">
</div>
<div class="container" id="nav">
<p id="time"></p>
</div>
</header>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>TT</title>
<link href="css/bootstrap.css" rel="stylesheet">
<link href="style/style.css" rel="stylesheet" type="text/css">
<script>
document.body.style.zoom="95%"
</script>
<script>
function ins()
{
nextDepartures(<?=$minutes?>, <?=$limit?>);
nextDeparturesTrains(120);
nextDeparturesTrams(60);
startTime();
}
</script>
<script>
$(document).ready(
function() {
setInterval(ins(), 5000);
});
</script>
<script src="data.js"></script>
<script src="sprintf.js"></script>
<script type="text/javascript" src="2.0.0-crypto-sha1.js"></script>
<script type="text/javascript" src="2.0.0-hmac-min.js"></script>
</head>
<body onload="ins()">
<table class="table table-bordered table-stripped table-hover" id="depart" style="float:left; border: 1px solid black; width:30%;">
<thead>
<tr>
<td colspan="4" class="danger" style="text-align: center; font-weight: bold;">Buses Departing from this Stop</td>
<tr>
<tr>
<th>Bus No. & Name</th>
<th>Time</th>
<th>Remaining Mins</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<!-- This table for train information-->
<table class="table table-bordered table-stripped table-hover" id="departTrains" style="float:left; border: 1px solid black; width:30%;">
<thead>
<tr>
<td colspan="4" class="danger" style="text-align: center; font-weight: bold;">Trains Departing from varios stations</td>
<tr>
<tr>
<th>Station</th>
<th>Destination</th>
<th>Time</th>
<th>Remaining Mins</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<!-- This table for tram information-->
<table class="table table-bordered table-stripped table-hover" id="departTrams" style="float:left; border: 1px solid black; width:30%;">
<thead>
<tr>
<td colspan="4" class="danger" style="text-align: center; font-weight: bold;">Tram Departing from plenty road</td>
<tr>
<tr>
<th>Tram Name</th>
<th>Time</th>
<th>Remaining Mins</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<footer id="footer">
<?=$start?><?=$message?><?$end?>
</footer>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.js"></script>
</body>
</html>
Now i have a javascript function ins() which further have stored functions in it which sends data to the tables defined in the page with relevant information.
Also, i have a script defined in the page which i think could be the possible solution, but its not working
here is that script
<script>
$(document).ready(
function() {
setInterval(ins(), 5000);
});
</script>
this is the sample data which function ins() is pushing into tables on load the page
If you want to load the JavaScript function without reloading the Entire page you can follow up the AJAX structure and you can make the changes as per the requirement you need.
Since loading up of the JavaScript without reloading the page will perform good only if it is done in AJAX. If the process is done in AJAX it will load the particular div where you want to display the JS output as required.
You can use the ins() function in Ajax and you can reload the page as the success function so that it will load the content under the DIV what you have provided as the success div.

Display ajax response in Table

display.html :
<div id="display_result" style="display: none"><table class="table">
<p style="float: right;" >Select All<input type="checkbox" class="allcb" data-child="chk" checked/> </p>
<thead>
<tr>
<th>Die No</th>
<th> Status </th>
<th> Location </th>
<th>Select</th>
</tr>
</thead>
<tbody>
</table>
<div id ="issue_button">
<input type="submit" id="submit" class="btn btn-success " value="Recieve" style="width: 150px;"></div>
</div>
Ajax:
var data = JSON.stringify($("#form").serializeArray());
// alert(data);
$.ajax({ // Send the credential values to another checker.php using Ajax in POST menthod
type: 'POST',
data: {
list: data
},
url: 'die_recieving_process.php',
success: function(data) ){
$('#display_result').html(data);
}
});
die_recieving_process.php
while($fetch = mysql_fetch_array($query))
{
if($fetch[1] == "Table Rack" )
{
echo '<tr class="success"><td>'.$fetch[0].'</td><td>'.$fetch[1].'</td><td>'.$fetch[3] . '</td> <td><input type=checkbox class="chk" id=check_box value= '.$fetch[2].' name= check_list[] </td> </tr>';
}
else
{
echo '<tr class="warning"><td>'.$fetch[0].'</td><td>'.$fetch[1].'</td><td>'.$fetch[3] . '</td> <td><input type=checkbox class="chk" id=check_box value= '.$fetch[2].' name= check_list[] checked </td> </tr>';
}
}
Hi friends in display.html I have to display the result processed in die_recieving_process.php . In ajax i've sent all the value to die_recieving_process.php and after fetching the result i've to display the result in display.html
First in you Javascript, you have 2 errors:
Your code overrides existing contents of div, which is the whole table...
And you have one unnecessary bracket in success function declaration
So change this:
success: function(data) ){
$('#display_result').html(data);
}
To this:
success: function(data) {//remove unnecessary bracket
$('#display_result tbody').html(data);//add data - to tbody, and not to the div
}
By the way, using $.post() you can write your javascript code shorter, like this:
var data = JSON.stringify($("#form").serializeArray());
$.post('die_recieving_process.php',{list:data},function(responseData){
$('#display_result tbody').html(responseData); //added to tbody which is inside #display_result
$('#display_result').show();
});
Second you need to close your tbody tag inside the table
Create html table with empty body tags and body id = tBody for example:
<table>
<caption>Smaple Data Table</caption>
<thead>
<tr>
<th>Field 1</th>
<th>Field 2</th>
</tr>
</thead>
<tbody id="tBody"></tbody>
</table>
Use the jquery ajax to load json data in the created table after load button is clicked assuming that my json file is storing userData like userName, age, city:
$('#btnLoadAll').click(function () {
$.ajax({
url: "url/data.json",
dataType: 'json',
success: function (resp) {
var trHTML = '';
$.each(resp, function (i, userData) {
trHTML +=
'<tr><td>'
+ userData.userName
+ '</td><td>'
+ userData.age
+ '</td><td>'
+ userData.city
+ '</td></tr>';
});
$('#tBody').append(trHTML);
},
error: function (err) {
let error = `Ajax error: ${err.status} - ${err.statusText}`;
console.log(error);
}
})
});
If you do not see result, try to remove style="display: none" in display.html

Categories