I'm new to javascript.
I need to fetch JSON response from 2 different AJAX request and create a 2 different table.
I have achieved it for 1 JSON response and 1 Table.
HTML :
<div style="width:700px;padding:20px;S">
<table id="host_table" class="table">
<tr>
<th>Server Name</th>
<th>Availability %</th>
</tr>
</table>
</div>
JavaScript :
$(function() {
// kick off with fetchdata
fetchData();
// fetchServiceData();
});
function make_base_auth(user, password) {
var tok = user + ':' + password;
var hash = btoa(tok);
return 'Basic ' + hash;
}
function fetchData() {
var time = new Date();
var end = Math.floor((new Date).getTime()/1000);
//var end = ~~(Date.now() /1000) ;
var start = Math.floor(time.setDate(time.getDate() - 1)/1000);
Availreport = "http://xx.xx.xx.xx/nagios/cgi-bin/archivejson.cgi?query=availability&availabilityobjecttype=hostgroups&hostgroup=ALM&assumedinitialhoststate=up&assumedinitialservicestate=ok&starttime=" + start + "&endtime=" + end;
$.ajax({
type: "GET",
url: Availreport,
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization',
make_base_auth("nagiosadmin", "nagiosadmin"));
},
dataType: 'json', //data format
//async: false,
//success: onOutboundReceived //on receive of reply
timeout: 0,
success: availshow
});
function availshow(series) {
// 1. remove all existing rows
$("tr:has(td)").remove();
$.each(series.data.hostgroup.hosts, function (index, test) {
$('<tr>').append(
$('<td>').text(test.name),
$('<td>').text(parseInt(((test.time_up - test.time_down)/test.time_up)*100)),
).appendTo('#host_table');
});
$('#host_table tr').each(function() {
var $td = $(this).find('td:eq(1)');
var value = $td.text();
if (parseInt(value) < 100) {
$td.css('background-color', 'red');
}
});
}
This works perfect for 1 table creation.
But I'm unable to proceed for 2 table creation for 2 JSON response.
I can able to create 2 tables in HTML.
But unable to feed the JSON response to specific table.
HTML for 2 table Creation :
<table id="host_table" class="inlinetable" style="display: inline-block;">
<tr>
<th>Server Name</th>
<th>Availability %</th>
</tr>
</table>
<table id="service_table" class="inlinetable" style="display: inline-block;">
<tr>
<th>Service Name</th>
<th>Availability %</th>
</tr>
</table>
How to achieve my task?
make tables side by side like this
its another question but
use for first table
style="display: inline-block;"
and for second table
style="float: left;">
<table id="host_table" class="inlinetable" style="display: inline-block;">
<thead>
<tr>
<th>Server Name</th>
<th>Availability %</th>
</tr>
</thead>
<tbody></tbody>
</table>
<table id="service_table" class="inlinetable" style="float: left;">
<thead>
<tr>
<th>Service Name</th>
<th>Availability %</th>
</tr>
</thead>
<tbody></tbody>
</table>
JS
$(function() {
// kick off with fetchdata
// service_table();
service_table();
// host table();
fetchData2();
});
function service_table() {
$.ajax({
type: "GET",
url: Availreport,
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization',
make_base_auth("nagiosadmin", "nagiosadmin"));
},
dataType: 'json',
timeout: 0,
success:function(series) {
$('#service_table tbody').empty();
// your row loop code
}
});
function service_table() {
$.ajax({
type: "GET",
url: Availreport,
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization',
make_base_auth("nagiosadmin", "nagiosadmin"));
},
dataType: 'json',
timeout: 0,
success:function(series) {
$('#host_table tbody').empty();
// your row loop code
}
});
}
its just how it can work for your understanding, more dynamic solution can be made
Related
I want to display data in table on inserting data as well as when the page is loaded. Storing data successfully works with the code but the issue is;
When I use POST, the form data is completely visible in the URL.
How do i display all data passed in json format in html table.
HTML:
<table class="table table-striped table-bordered" id="myTable">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Match</th>
<th scope="col">Match Date</th>
<th scope="col">Winner</th>
<th scope="col">Loser</th>
<th scope="col">Man of the Match</th>
<th scope="col">Bowler of Match</th>
<th scope="col">Best Fielder</th>
</tr>
</thead>
</table>
JAVASCRIPT:
<script>
$(function() {
$("#submit").on("click", function(e) {
var team_one = $('#team_one').val();
var team_two = $('#team_two').val();
var match_summary = $('#match_summary').val();
var match_date = $('#match_date').val();
var winner = $('#winner').val();
var loser = $('#loser').val();
var man_of_the_match = $('#man_of_the_match').val();
var bowler_of_the_match = $('#bowler_of_the_match').val();
var best_fielder = $('#best_fielder').val();
$.ajax(
{
type: "POST", //HTTP POST Method
url: '<?php echo base_url(); ?>/MatchController/storeMatch',
data: { //Passing data
'team_one': team_one,
'team_two': team_two,
'match_summary' : match_summary,
'match_date' : match_date,
'winner' : winner,
'loser' : loser,
'man_of_the_match' : man_of_the_match,
'bowler_of_the_match' : bowler_of_the_match,
'best_fielder' : best_fielder
},
success: function (response) {
console.log("Response: " + response);
alert("Data stored successfully");
},
});
});
});
//FETCH ALL MATCH DATA USING PASSED API IN CONTROLLER
$(document).ready(function (){
getData();
function getData(){
$.ajax({
url : "<?php echo base_url(); ?>/MatchController/fetchMatchData",
method : 'get',
dataType: "json",
success: function(data){
}
});
}
});
CONTROLLER:
public function storeMatch()
{
$team_one = $_POST['team_one'];
$team_two = $_POST['team_two'];
$match_date = $_POST['match_date'];
$match_summary = $_POST['match_summary'];
$winner = $_POST['winner'];
$loser = $_POST['loser'];
$man_of_the_match = $_POST['man_of_the_match'];
$bowler_of_the_match = $_POST['bowler_of_the_match'];
$best_fielder = $_POST['best_fielder'];
$data = array(
'team_one' => $team_one,
'team_two' => $team_two,
'match_date' => $match_date,
'match_summary' => $match_summary,
'winner' => $winner,
'loser' => $loser,
'man_of_the_match' => $man_of_the_match,
'bowler_of_the_match' => $bowler_of_the_match,
'best_fielder' => $best_fielder
);
$this->MatchModel->saveMatchData($data);
}
public function fetchMatchData()
{
$match_data = $this->MatchModel->fetchMatchList();
return $match_data;
}
Try to pass the result to <tbody> use JQuery
success: function(data){
//delete old tbody block
$('#myTable tbody').remove()
//add tbody block
$('#myTable').append('<tbody><tr><td>'+data.someValue+'</td></tr></tbody>')
}
And when you want add new data just call your getData().
success: function (response) {
getData()
console.log("Response: " + response);
alert("Data stored successfully");
},
Also look at e.preventDefault for your ajax call. If you use ajax needlessly reload page
I have a table filled with data from my database. This table is sortable and saves the order with ajax. Now I made the option to delete the selected row. When the row is deleted the table is refreshed with ajax.
My only problem now is when I delete a row and my table is refreshed, the table can't be sorted any more (until I refresh).
Is there a way to fix this?
This is my jquery/ajax code:
$(document).ready(function () {
$('#sortable').sortable({
axis: 'y',
update: function (event, ui) {
var data = $(this).sortable('serialize');
$.ajax({
data: data,
type: 'POST',
url: 'includes/saveorder.php'
});
}
});
});
function deleteFromDatabase(id) {
if (confirm("Weet u zeker dat u deze pagina wilt verwijderen?")) {
$.ajax({
url: "includes/paginas_del.php",
type: "POST",
data:'id='+id,
success: function(data){
document.getElementById("alert").style.display = "block";
$("#myTable").load("paginas.php #myTable");
}
});
} else {
document.getElementById("alert").style.display = "none";
}
}
This is my table:
<table class="table table-hover table-cust" id="myTable">
<thead>
<tr>
<th scope="col" width="80%">Pagina</th>
<th width="10%"></th>
<th width="10%"></th>
</tr>
</thead>
<tbody id="sortable">
<?php $result = mysql_query("SELECT * FROM pagina WHERE active = '1' ORDER BY sort");
while ($data = mysql_fetch_assoc($result)) { ?>
<tr id="item-<?php echo $data['id'] ?>">
<td><?php echo $data['titel'] ?></td>
<td><i class="fas fa-edit"></i></td>
<td><i class="fas fa-trash-alt"></i></td>
</tr>
<?php } ?>
</tbody>
</table>
This issue is caused by the fact that what the call to jquery's load method does is "load data from the server and place the returned HTML into the matched element".
This means that the whole table is replaced with a new table. So the old <tbody id="sortable"> element is replaced with a new one which doesn't have the sortable behavior you attached to the old one.
Try rerunning the sortable method after the table is rebuilt:
function deleteFromDatabase(id) {
if (confirm("Weet u zeker dat u deze pagina wilt verwijderen?")) {
$.ajax({
url: "includes/paginas_del.php",
type: "POST",
data:'id='+id,
success: function(data){
document.getElementById("alert").style.display = "block";
$("#myTable").load("paginas.php #myTable");
$('#sortable').sortable({
axis: 'y',
update: function (event, ui) {
var data = $(this).sortable('serialize');
$.ajax({
data: data,
type: 'POST',
url: 'includes/saveorder.php'
});
}
});
}
});
} else {
document.getElementById("alert").style.display = "none";
}
}
I am having a big list which I am grouping into a size of 500 and then rendering them one at a time to client on demand. I am using the following Java script code to render the list into table.
var counter;
$(document).ready(function() {
var table = $('#example').DataTable();
$('#example tbody').on('click', 'tr', function() {
$(this).toggleClass('selected');
});
$('#button').click(function() {
alert(table.rows('.selected').data().length + ' row(s) selected');
});
});
function getData(submit) {
var pointer;
var msg = "";
var company = "";
if (submit == 1) {
//On click of get more
counter += 500;
pointer = counter;
} else {
//On load
counter = 500;
pointer = 500;
}
$.ajax({
type: "GET",
url: "/biz/getListOfFreeMembers",
data: {
limit: pointer
},
success: function(data) {
$.each(data, function(i, obj) {
var t = $('#example').DataTable();
t.row.add([
obj.companyName,
obj.mobileNo,
obj.companyWebsite,
obj.firstName,
obj.address,
obj.createDate
]).draw();
});
},
error: function(e) {
alert("error" + e.Message);
}
});
}
<link href="//cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<div id="demo" class="col-sm-12">
<div class="table-responsive">
<table id="example" class="table">
<thead>
<tr>
<th>Company Name</th>
<th>Mobile Number</th>
<th>Website</th>
<th>Person Name</th>
<th>Address</th>
<th>Date of Creation</th>
</tr>
</thead>
<tbody id="list_of_users">
</tbody>
</table>
</div>
</div>
Get more data
The table is rendering correctly for the first time, but when I click the Get more data link, the new set of data is not appending to the existing set, instead the new set is getting displayed first and then the old set and so on for each click of get more data. Please suggest a way for appending the new data set to the old one in the table. Thank you.
Your code is working fine. (check this codePen)
May be you are missing, that Page Numbers are increasing (meaning new data is going on the next pages)
Or May be your service is not responding the data (Check the Network Console)
var counter=0;
var t=null;
var url = 'tableData';
$(document).ready(function() {
t = $('#example').DataTable();
t
.column( '0:visible' )
.order( '' )
.draw();
$('#example tbody').on('click', 'tr', function() {
$(this).toggleClass('selected');
});
$('#button').click(function() {
alert(t.rows('.selected').data().length + ' row(s) selected');
});
getData();
});
function getData(submit) {
$('#loading').show();
var pointer=0;
var msg = "";
var company = "";
if (submit == 1) {
//On click of get more
counter += 500;
pointer = counter;
url = 'tableData2';
} else {
//On load
counter = 500;
pointer = 500;
url = 'tableData';
}
$.ajax({
contentType: "application/json",
type: "GET",
url: "http://demo2315600.mockable.io/" + url,
success: function(data) {
$('#loading').hide();
//alert('asd');
$.each(data, function(i, obj) {
t.row.add([
obj.companyName,
obj.mobileNo,
obj.companyWebsite,
obj.firstName,
obj.address,
obj.createDate
]).draw();
});
},
error: function(e) {
alert("error" + e.Message);
}
});
}
<link href="//cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<div id="demo" class="col-sm-12">
<div class="table-responsive">
<table id="example" class="table">
<thead>
<tr>
<th>Company Name</th>
<th>Mobile Number</th>
<th>Website</th>
<th>Person Name</th>
<th>Address</th>
<th>Date of Creation</th>
</tr>
</thead>
<tbody id="list_of_users">
</tbody>
</table>
</div>
</div>
Get more data
<span id="loading" style="display:none;">pleas wait Load Data</span>
I'm loading data dynamically to html table as below. I'm using Datatable for ssearch.
Technology stack used is:
Spring MVC
Hibernate
Ajax
JQuery
function getdata()
{
$.ajax({
type: "GET",
url: "/controllerURL.html", //controller URL
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (results) {
console.log(results)
var success = results.success;
if(success){
var finaldata = "<tbody><thead><tr><th>ID</th><th>data1</th><th>data2</th><th>Update</th></tr></thead>"; //data
var data = results.message;
data = jQuery.parseJSON(data);
alert(data);
for(var i = 0; i < data.length; i++){
var value = data[i];
finaldata = finaldata+ "<tr><th>"+value.ID+"</th><th>"+value.variable1+"</th><th>"+value.variable2+"</th></tr>";
}
finaldata = finaldata + "</tbody>";
$("#tableID").html(finaldata);
}
},
error: function (data) {
alert("fail");
console.log('ajax call error');
}
});
}
I'm now be able to load data into table. but can someone explain how to add search option to it.
You can use datatables click here
It will provide you various inbuilt functionality that you may want to integrate
<!--dependencies for data table -->
<script src="https://cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js" type="text/javascript"></script>
Your html should look like this
<table id="stable" class="display table-responsive table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>Id</th>
<th>Data1</th>
<th>Data2</th>
<th>Data3</th>
<th>Data4</th>
</tr>
</thead>
finally write this script
$(document).ready(function () {
$('#table').DataTable();
});
I'm deleting row from datatable , and then after deleting record , I'm binding table row again then calling dataTable function again but it is not updating the total number of record showing at bottom .
from server side I'm getting updated number of record , and also in my table updated number of row. but total number shown by dataTable is not updated.
this is my ajax code
$(document).delegate('.Delete', 'click', function () {
var getDeleteID = parseInt($(this).closest('tr').find('td:eq(0)').find('span').text());
BootstrapDialog.confirm('Are you sure you want to delete person?', function (result) {
if (result) {
$.ajax({
type: 'GET',
contentType: 'application/json; charset=utf-8',
url: '/Home/DeleteData',
data: { Id: getDeleteID },
dataType: "json",
success: function (data) {
BindTable(data);
},
error: function (data) {
alert("Error In Deleting Person ");
}
});
}
});
});
});
this is my BindTable Function
function BindTable(data) {
var tabHtml = '';
$.each(data, function (i, d) {
tabHtml += "<tr><td><span class='hide'>" + d.ID + "</span>" + d.Name + "</td><td>" + d.Position + "</td><td>" + d.Age + "</td><td>" + d.Salary + "</td><td><span class='Edit ML10'>Edit</span><span class='Delete ML10'>Delete</span> </tr>";
});
$('#dbTable').find('tbody').html(tabHtml);
$('#dbTable').dataTable();
}
HTML :
<table id="dbTable" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>
Name
</th>
<th>
Position
</th>
<th>
Age
</th>
<th>
Salary
</th>
<th>
Action
</th>
</tr>
</thead>
<tbody>
</tbody>
</table>