ajax response and html not working properly - javascript

Here I am trying to get result in jsp page using ajax but i am getting improper result.
Problem: My ajax response is displayed first instead of my table headings. That means it should show table headings and then table content but not happening.
my jsp page displaying result
My Ajax code:
<script>
$(document).ready(function(){
$(function(){
$('#form1').submit(function(e){
e.preventDefault();
var form = $(this);
var post_url = form.attr('action');
var post_data = form.serialize();
$.ajax({
type: 'POST',
url: post_url,
data: post_data,
success: function(msg) {
console.log(msg);
$('#LogsReceived').append(msg);
},
error: function (error) {
console.log(error);
}
});
});
});
});
</script>
Here is my html code:
<div class="result" >
<p>
<table>
<div id="LogsReceived">
<tr>
<th>Index</th>
<th>Type</th>
<th>Severity</th>
<th>Source Host</th>
<th>Source</th>
<th>Program</th>
<th>Priority</th>
<th>Message</th>
<th>User</th>
<th>Facility</th>
<th>Event Time</th>
</tr>
</div>
</table>
</p></div>

Your HTML structure is invalid. You can't have a div as a direct child of table and as a parent of tr. What you're looking for there is thead or tbody, not div. It's being corrected by the browser, relocating the div to before the table. (Because it's invalid, the browser can do anything it wants: Put the div before, put it after, treat it as though it were a tbody, ...) Putting a table in a p is similarly invalid. You can see the rearrangement with the dev tools of your browser: Just right-click the table headers and choose "Inspect element" (or similar):
I recommend reviewing the various rules for what elements can go where in the spec.
Probably, you want both thead and tbody:
<table>
<thead>
<tr>
<th>Index</th>
<th>Type</th>
<th>Severity</th>
<th>Source Host</th>
<th>Source</th>
<th>Program</th>
<th>Priority</th>
<th>Message</th>
<th>User</th>
<th>Facility</th>
<th>Event Time</th>
</tr>
</thead>
<tbody id="LogsReceived">
</tbody>
</table>

Related

Is there any way to complete an array with values of clicked rows, after a jQuery DataTable is loaded by submitting a form?

Hi guys I have a problem when I'm using jQuery datatable. After Datatable is loaded by submitting an ID to the server, and then server response with the data that I render then into DataTable. In that DataTable I want to make multiple row selection and the values that I want to push into array are for example all the values of first column. My code below is everything that I have created now.
The HTML Code:
<form name="search_form_order" id="search_form_order" novalidate="">
<input type="text" name='login_id' id="login_id" class='form-control'>
<button type="submit" name="search" id="search">Search</button>
</form>
<table id="orders_table" width='100%'>
<thead>
<tr>
<th>Login ID</th>
<th>Order ID</th>
<th>Comment</th>
<th class="disabled-sorting">Actions</th>
</tr>
</thead>
<tfoot>
<th>Login ID</th>
<th>Order ID</th>
<th>Comment</th>
<th class="disabled-sorting">Actions</th>
</tfoot>
</table>
jQuery Code:
//This is the part where user submit the id parameter
$('#search_form_order').on('submit', function(event) {
event.preventDefault();
var id = $('#login_id').val();
$('#orders_table').DataTable().destroy();
loadOrdersTable(id);
});
//This is the function
function loadOrdersTable (id) {
table=$('#orders_table').DataTable({
responsive: true,
processing: true,
serverSide: false,
lengthMenu: [[100, -1], [100, "All"]],
"ajax": {
url: "/list_orders.php",
type:"POST",
dataSrc: "",
data: {login_id:id}
},
columns: [
{data: 'login_id', name: 'login_id'},
{data: 'order_id', name: 'order_id'},
{data: 'comment', name: 'comment'},
{data: 'actions', name: 'actions'}
]
});
}
Until here everything works perfectly, but when I want to select the the order_id-s of each row, the below jQuery code do not work:
var dataArr = [];
$('#orders_table tbody').on('click', 'tr', function () {
$(this).toggleClass('selected');
var id= $(this).find('td').eq(1).text();
dataArr.push(id);
});
console.log(dataArr);
This I'm using because I want to populate this array, to make bulk edit or bulk delete of all selected rows. On console it is displayed only this '[]', as output since onlcick event do not get the value from table rows.
Thank you!
your mistake is that you have your console.log outside of the event handler. That means that it's executed when the page is loaded and thus the array is empty.
If you move that inside your event handler (1 before) you'll se that everytime you click, the ID is pushed to the array and then shown at console.
Here is a working snippet:
PD: Note that everytime you click on one row the ID will be added to the array causing possible duplications, meanwhile the toggle will.. toggle, probably causing unexpected behaviours. You should need to add extra logic to avoid that
var dataArr = [];
$('#orders_table tbody').on('click', 'tr', function () {
$(this).toggleClass('selected');
var id= $(this).find('td').eq(1).text();
dataArr.push(id);
console.log(dataArr);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="orders_table" width='100%'>
<thead>
<tr>
<th>Login ID</th>
<th>Order ID</th>
<th>Comment</th>
<th class="disabled-sorting">Actions</th>
</tr>
</thead>
<tbody>
<tr>
<td>login_id</td>
<td>order_id</td>
<td>comment</td>
<td>actions</td>
</tr>
</tbody>
<tfoot>
<th>Login ID</th>
<th>Order ID</th>
<th>Comment</th>
<th class="disabled-sorting">Actions</th>
</tfoot>
</table>

bootstrap-table: how to dynamically pull params required for ajaxRequest(params) call

I have used bootstrap-table successfully to load AJAX data into a single table using the following call:
function ajaxRequest(params) {
$.getJSON( 'ajax.php?action=doSomething' + $.param(params.data), {format: 'json'}).then(function (res) {
params.success(res)
});
}
But now I'd like to work with multiple tables, each with their own ID, which will be populated by an onClick event bound to a button. Can anyone tell me how I can get the params for any given table required by the function?
The HTML for each table is in the format:
<table id="table-{$id}" class="my-table" data-toggle="table"
data-search="false"
data-ajax="ajaxRequest"
data-side-pagination="server"
data-pagination="true">
<thead>
<tr>
<th data-field="field1" data-sortable="true">Field 1</th>
...
</tr>
</thead>
</table>
Thanks!

How to use buttons with different Values but same ID for jQuery?

I have a table which generated by PHP and MySql. One of the column will have buttons which will have values which will be used for sending a data to another PHP file using AJAX. But I am now facing a problem that id(s) can have only unique value.
Will it be possible to use same ID for buttons with different values.
Here is a dummy data of HTML (Output given by PHP).
<table>
<tr>
<th>Serial No.</th><th>File Name</th><th>Action</th>
</tr>
<tr>
<td>1</td><td>Physics Notes</td><td><button id="request" value="1">Download</button></td>
<tr>
<tr>
<td>2</td><td>Chemistry Notes</td><td><button id="request" value="2">Download</button></td>
<tr>
<tr>
<td>3</td><td>Mathematics Notes</td><td><button id="request" value="3">Download</button></td>
<tr>
</table>
Now I want when any of the buttons in the 3rd columns are clicked, their values to be receive in the jQuery variable "file".
And then the values will be sent to a PHP file via AJAX.
Here is my jQuery and AJAX code.
<script src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#request").on("click",function(e){
e.preventDefault();
var file = $(this).val();
$.ajax({
url : "downloadfile.php",
type : "POST",
data : {file:file},
success : function(data){
alert("Thank you for using our service");
}
});
})
});
</script>
As said in Comment, an ID shall always be unique. So use class in your case.
<td><button class="request" value="2">Download</button></td>
and
$(".request").on("click", function(e) {
Note Please note that you haven't closed your tr they are missing /
Demo
$(document).ready(function() {
$(".request").on("click", function(e) {
e.preventDefault();
var file = $(this).val();
$.ajax({
url: "downloadfile.php",
type: "POST",
data: {
file: file
},
success: function(data) {
alert("Thank you for using our service");
}
});
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<th>Serial No.</th>
<th>File Name</th>
<th>Action</th>
</tr>
<tr>
<td>1</td>
<td>Physics Notes</td>
<td><button class="request" value="1">Download</button></td>
</tr>
<tr>
<td>2</td>
<td>Chemistry Notes</td>
<td><button class="request" value="2">Download</button></td>
</tr>
<tr>
<td>3</td>
<td>Mathematics Notes</td>
<td><button class="request" value="3">Download</button></td>
</tr>
</table>

Data Table hangs sporadically (No data available in table) when data sorted or loaded with Knockout binding

I am binding data to a table using Knockout JS and the JQuery/Bootstrap based; Data Table API. The table becomes unresponsive sporadically when sorted or loaded. There are no errors in the log.
It also shows 0 of 0 data as illustrated in the screenshot below:
I have seen similar errors/issues but could not get a solutions for them, E.g. This post:
Code:
function viewModel(){
var self = this;
self.Data = ko.observableArray([]);
$.getJSON('https://restcountries.eu/rest/v1/all', function(data){
self.Data(data);
});
}
ko.applyBindings(viewModel());
$(document).ready(function() {
$('#example').dataTable();
});
HTML:
<div class="table-responsive">
<table id="example" cellspacing="0"
class="table table-striped table-bordered table-condensed">
<thead>
<tr>
<th scope="col">Country</th>
<th scope="col">Capital</th>
<th scope="col">Population</th>
<th scope="col">Region</th>
</tr>
</thead>
<tfoot>
<tr>
<th scope="col">Country</th>
<th scope="col">Capital</th>
<th scope="col">Population</th>
<th scope="col">Region</th>
</tr>
</tfoot>
<tbody data-bind="foreach: Data">
<tr>
<td data-bind="text: name"></td>
<td data-bind="text: capital"></td>
<td data-bind="text: population"></td>
<td data-bind="text: region"></td>
</tr>
</tbody>
</table>
</div>
Here is a full working example (JSFiddle) utilizing a REST API so that the exact problem is accurately replicated:
I think the problem with your example may be with how you're dealing with your data when you get it back from the API call.
I've put together a quick example that achieves what I think you're trying to achieve and the sorting and searching work quickly for me.
When I get the JSON data back from the API, I use the Knockout arrayMap utility function to create an array of "Country" objects that have observable properties that I have mapped the JSON data to. I've bound the table to my observableArray of Country objects.
Initialising the data table in the same way you have works fine for me in this case.
The full working solution is here: http://plnkr.co/edit/eroIox6zqBFOVnf86Mdk?p=preview
script.js
var ViewModel = function(jsonData) {
var countries = ko.utils.arrayMap(jsonData, function(item) {
return new Country(item)
});
this.Countries = ko.observableArray(countries);
};
var Country = function(jsonItem) {
this.Name = ko.observable(jsonItem.name);
this.Capital = ko.observable(jsonItem.capital);
this.Population = ko.observable(jsonItem.population);
this.Region = ko.observable(jsonItem.region);
};
window.onload = function() {
$.getJSON('https://restcountries.eu/rest/v1/all', function(data) {
ko.applyBindings(new ViewModel(data));
$("#example").dataTable();
});
}
index.html
<table id="example" cellspacing="0" class="table table-striped table-bordered table-condensed">
<thead>
<tr>
<th scope="col">Country</th>
<th scope="col">Capital</th>
<th scope="col">Population</th>
<th scope="col">Region</th>
</tr>
</thead>
<tfoot>
<tr>
<th scope="col">Country</th>
<th scope="col">Capital</th>
<th scope="col">Population</th>
<th scope="col">Region</th>
</tr>
</tfoot>
<tbody data-bind="foreach: Countries">
<tr>
<td data-bind="text: Name"></td>
<td data-bind="text: Capital"></td>
<td data-bind="text: Population"></td>
<td data-bind="text: Region"></td>
</tr>
</tbody>
</table>
Tables are fairly slow to render within Knockout, and if your table is based on a computed, I could see how you could have some issues with redrawing time. But that's not happening here.
Apart from loading the data and binding it to the table rows, there's no data manipulation going on in your viewmodel. All the data manipulation is done by the dataTable plug-in, which you initialize with a single jQuery call. Properly, that should be done within a binding handler. You also need to know what is going on within the plug-in when it sorts, filters, or whatever it does, because you may need to mediate those changes back to your observableArray within your binding handler.
Bottom line: you need a binding handler for the dataTable. There may be one already written; I haven't Googled for it. Give that a try.

After adding, resetting/removing table rows in jQuery

<table id="myTable" style="width: 650px;">
<tbody>
<tr style="font-weight: bold;">
<td>Name</td>
<td>Price</td>
<td>Supplier</td>
<td>Amount</td>
<td>Basket</td>
</tr>
</tbody>
</table>
is my HTML.
This is my current jQuery JS:
$.post('/ajax/products', { method: 'search', string: searchstring, category: $('#search_category').val() }, function(data) {
data = $.parseJSON(data);
$('#myTable > tbody:last').append('<tr><td>'+b.name+'</td><td>'+b.price+'</td><td></td><td></td></tr>');
});
});
Each time you key up, the above js executes. Now when you are looking for Cookies, and you starts to write, it sends a ajax post with "C" then "Co" then "Coo" etc.
Already at the first ajax call it has found results that are starting with C. Therefore it appends to the table. Now it also found results for "Co" (same results as "C", because theres only Cookies in the db at the moment).
And the same with Coo, Cook, Cooki, Cookie, Cookies... yeah you get the point. And the results of this is alot of tables appending under eachother.
So what i wish to do is like cleaning/removing the <tr>'s thats inside #myTables tbody, before it appends (actually just before the $.post()).
But it should not remove the first <tr>, which is the column headers as you can see in my above html.
How can i do this?
Without changing your html you could write:
var rows = $('#myTable').find('tr');
rows.each(function(index, value) {
if (index > 0) {
$(value).remove();
}
});
$('#myTable > tbody:last').append('<tr><td>'+b.name+'</td><td>'+b.price+'</td><td></td><td></td></tr>');
My recommendation however, would be to use a th for your table header:
<table id="myTable" style="width: 650px;">
<thead>
<tr style="font-weight: bold;">
<td>Name</td>
<td>Price</td>
<td>Supplier</td>
<td>Amount</td>
<td>Basket</td>
</tr>
</thead>
<tbody>
</tbody>
</table>
Then your javascript can be:
$('#myTable > tbody').empty().append('<tr><td>'+b.name+'</td><td>'+b.price+'</td><td></td><td></td></tr>');

Categories