I have a form that includes a checkbox that when clicked performs an AJAX request to update a backend database. I would like to then remove the checkbox input and replace it with a a simple table cell showing the current date.
Here's my form:
$(document).ready(function() {
$("input[name='dateReceived']").change(function() {
var recid = $(this).closest('td').attr('id');
// Create a reference to $(this) here:
$this = $(this);
$.post('updateAsset.php', {
type: 'updateAsset',
recid: recid,
dateReceived: dateReceived
}, function(data) {
data = JSON.parse(data);
//console.log( data );
if (data.error) {
var ajaxError = (data.text);
var errorAlert = 'There was an error updating the Date Received - ' + ajaxError + '. Please contact the Help Desk';
$this.closest('td').addClass("error");
//display AJAX error details
$("#dateReceivedErrorMessage").html(errorAlert);
$("#dateReceivedError").show();
return; // stop executing this function any further
} else {
$this.closest('td').addClass("success")
$this.closest('td').removeClass("error");
// if you want to show a success alert enable the following
// $("#ajaxAlert").addClass("alert alert-success").html(data.text);
}
}).fail(function(xhr) {
var httpStatus = (xhr.status);
var ajaxError = 'There was an error updating the Date Received - AJAX request error. HTTP Status: ' + httpStatus + '. Please contact the Help Desk';
// console.log( 'ajaxError: '+ajaxError );
$this.closest('td').addClass("error");
//display AJAX error details
$("#dateReceivedErrorMessage").html(ajaxError);
$("#dateReceivedError").show();
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<table class="table table-condensed table-striped table-bordered">
<thead>
<th class="text-center" scope="col">ID</th>
<th class="text-center" scope="col">Code</th>
<th class="text-center" scope="col">Description</th>
<th class="text-center" scope="col">Received</th>
<th></th>
</thead>
<tbody>
<tr class="" id="111202">
<td>GRP423423</td>
<td>BWEQRQEW/A</td>
<td>Standard Containers</td>
<td id="111202"><input type="checkbox" id="111202" value="1" class="form-control" name="dateReceived"></td>
</tr>
<tr class="" id="111216">
<td>GRP424213412</td>
<td>PPUPJHL/A</td>
<td>Packaging Boxes</td>
<td id="111202"><input type="checkbox" id="111202" value="1" class="form-control" name="dateReceived"></td>
</tr>
</tbody>
</table>
which is currently working fine and adding the success/danger class accordingly. If it is successful I would like to extend this to replace the checkbox input with a simple table cell showing the current date, e.g.
DD/MM/YYYY
I think you can achieve it by adding this into your success function:
$(this).hide();
var dd = new Date();
$(this).closest('td').append(dd.getDate() + '/'+ ('0' + (dd.getMonth() + 1)).slice(-2) + '/'+ dd.getFullYear());
I Think you can change your td's html instead of appending to achieve it
$(this).hide();
var dd = new Date();
$(this).closest('td').html(dd.getDate() + '/'+ ('0' + (dd.getMonth() + 1)).slice(-2) + '/'+ dd.getFullYear());
Related
I am working in Modern SharePoint and have a web-part installed that allows me to inject code directly into the page. I have built this code to allow me to use a DataTable to pull information from a List I have on that site.
I am having trouble with the filters for the columns as they appear to not be pulling in any values at all. I believe this is due to me calling the data for the table after the DataTable has been created. But I also reference the table in the code to get the data for the table after it is declared. Can someone please take a look at my code and see if there is a way for this to be done?
Any help would be appreciated!
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Image</th>
<th>Title</th>
<th>Industry</th>
<th>Market</th>
<th>Description</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Image</th>
<th>Title</th>
<th>Industry</th>
<th>Market</th>
<th>Description</th>
</tr>
</tfoot>
</table>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
<link
rel="stylesheet"
type="text/css"
href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css"
/>
<script>
var dataTable;
$(document).ready(function () {
dataTable = $('#example').DataTable({
initComplete: function () {
this.api()
.columns([2, 3])
.every(function () {
var column = this;
var select = $('<select><option value=""></option></select>')
.appendTo($(column.header()).empty())
.on('change', function () {
var val = $.fn.dataTable.util.escapeRegex($(this).val());
column.search(val ? '^' + val + '$' : '', true, false).draw();
});
column
.data()
.unique()
.sort()
.each(function (d, j) {
select.append('<option value="' + d + '">' + d + '</option>');
});
});
}
});
$.ajax({
url:
"https://ewscripps.sharepoint.com/sites/lighthouseideas/_api/web/lists/getbytitle('Site%20Pages')/items?$select=FileLeafRef,Title,Industry,Market,Description,PageType&$filter=TaxCatchAll/Term eq 'Station Initiatives'",
headers: {
accept: 'application/json;odata=verbose',
'content-type': 'application/json;odata=verbose',
'X-RequestDigest': jQuery('#__REQUESTDIGEST').val()
},
success: function (data) {
console.log('issued URL Request');
//Get Success Stories
for (var i = 0; i < data.d.results.length; i++) {
console.log('Found: ' + data.d.results[i].Title);
dataTable.row
.add([
"<img src='https://ewscripps.sharepoint.com/sites/lighthouseideas/_layouts/15/getpreview.ashx?path=SitePages/" +
data.d.results[i].FileLeafRef +
"'>",
data.d.results[i].Title,
data.d.results[i].Industry.results,
data.d.results[i].Market.results,
data.d.results[i].Description
])
.draw(false);
}
console.log(data.d.results[4]);
console.log(data.d.results[9]);
dataTable.draw(true);
}
});
});
</script>
This should be related to databind after DataTable init, try to update the init with data, in your case, it's success function.
You could check my previous tested thread here.
I was trying to create a dynamic table with contents from jQuery. Also I have enabled a setTimeout in order for the data to be refreshed and updated in the html page.`
$(document).ready(function update_data() {
$.ajax({
dataType: "json",
url: "/wirelessSensor/dag",
success: updateForData,
error: errorOnAjax
});
setTimeout(function() {
update_data();
}, 5000);
});
function updateForData(data) {
// Updates DAG
console.log("Wirless nodes details");
var hasData = true;
if (data.result && data.result && data.result == "none") {
console.log('No data in result');
hasData = false;
} else if (!data.devices || !data.status) {
console.log('Devices not found in result');
hasData = false;
}
if (hasData) {
console.log('Creating Table');
var trHTML = '';
$.each(data.devices, function(index) {
trHTML += "<tr><td>" + data.devices[index] + "</td><td>" + data.lifetime[index] + "</td><td>" + data.status[index] + "</td></tr>";
});
$("#location").append(trHTML);
}
}
function errorOnAjax(jqxhr, status, errorstr) {
var errText = (errorstr == null) ?
'' : ', error: ' + errorstr;
console.log('Ajax error: ' + status + errText);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="location" border='1' width='100%'>
<tr>
<th align='center'> Devices </th>
<th align='center'> Lifetime </th>
<th align='center'> Status </th>
</tr>
</table>
Here since am using setTimeout my dynamic table is getting duplicated. The entries already existing are been repeated. How can I avoid this?
You can restructure your HTML to include <thead> and <tbody> elements, and the set the contents of the <tbody> to the results (rather than appending results to entries that might already be present).
<table id="location" border='1' width='100%'>
<thead>
<tr>
<th align='center'> Devices </th>
<th align='center'> Lifetime </th>
<th align='center'> Status </th>
</tr>
</thead>
<tbody id="location-content"></tbody>
</table>
Then do $("#location-content").html(trHTML); (note: html instead of append, to destroy old results instead of keeping them)
I am trying to add a dynamic row to the existing table on click of button, whose rows are dynamically created using output from PHP script.
I doing an ajax call to the script insert_tr.php which returns me a TR element in the same format as the existing table with the data.Data is returned appropriately
But unfortunately, the <tr> row is not being added to the table dynamically but adds only after a page refresh.
PHP file code :
<div id="v_div">
<table class="table table-bordered table-striped" >
<thead>
<th class='col-md-2'>name</th>
<th class='col-md-2'>number</th>
</thead>
<tbody>
<?php
while ($data = pg_fetch_assoc($ret)) {
echo
"<tr id=tr_".$data['sr_number'].">
<td class='td_topic' id=title:".$data['number']." >".trim($data['name'])."</td>
<td class='td_topic' id=title:".$data['number']." >".trim($data['number'])."</td>
<td class='td_topic' id=title:".$data['number']." ><button class='btn btn-info check1' type=button title='Add Entry'>Add Entry</button></td>
</tr>";
?>
</tbody>
</table>
</div>
Javascript :
$(document).ready(function() {
$("#v_div").on('click', '.check1', function() {
var field_userid = $(this).parent().attr("id");
var value = $(this).text();
$.post('insert_tr.php', field_userid + "=" + value, function(data) {
if (data != '') {
$(this).closest("tr").after(data);
}
});
});
});
All I want to do is add the row immediately after the current TR am on ,dynamically without a page refresh, which serves the ultimate use of an ajax call.
The reference to this is not the button that was clicked.
$(this).closest("tr").after(data);
Store a reference to the row outside the Ajax call.
$(document).ready(function() {
$("#v_div").on('click', '.check1', function() {
var field_userid = $(this).parent().attr("id");
var value = $(this).text();
var row = $(this).closest("tr");
$.post('insert_tr.php', field_userid + "=" + value, function(data) {
if (data != '') {
row.after(data);
}
});
});
});
I asked a question yesterday and that got me going on the right path, but I'm absolutely stuck again.
Outline:
I have 3 tables;
table 1 - expected data (#expected)
table 2 - expected confirmed data (#scannedExp)
table 3 - unexpected confirmed data (#scannedUnExp)
So for a example..
if I was to enter "6666" in the input box
it would reduce qty in the "#expected" table by 1 but create a column in the "#scannedExp" table with qty of 1 (with the i.e desc, cage grabbed from the #expected table).
if we was to enter '6666' this time it would delete the "#expected" row, but increase the table "#scannedExp"
if again we was to enter '6666' this time it would add a row to "#scannedUnExp" with just the code and qty (dont need the desc or cage)
and if we was to enter say "1234" it would add a row in "#scannedUnExp"
for some reason my codes not working in Jsfiddle as it works to some extent in my browser.
http://jsfiddle.net/j3psmmo3/
<body>
<input type="text" style="width: 200px" id="code" name="code" />
<input id = "btnSubmit" type="submit" value="Submit"/>
<P>Scanned Expected</P>
<table id = "scannedExp" > <thead>
<tr>
<th>Code</th>
<th>Desc</th>
<th>Qty</th>
<th>Cage</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<P>Scanned Un Expected</P>
<table id = "scannedUnExp" > <thead>
<tr>
<th>Code</th>
<th>Qty</th>
<th>Cage</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<P>Data Expected</P>
<table id = "expected"> <thead>
<tr>
<th>Code</th>
<th>Desc</th>
<th>Qty</th>
<th>Cage</th>
</tr>
</thead>
<tbody>
<tr id="4444" >
<td>4444</td>
<th>Car Door</th>
<td>3</td>
<th>S2222</th>
</tr>
<tr id="5555" >
<td>5555</td>
<th>door handel</th>
<td>1</td>
<th>S2222</th>
</tr>
<tr id="6666" >
<td>6666</td>
<th>headlight</th>
<td>2</td>
<th>S2222</th>
</tr>
<tr id="7777">
<td>7777</td>
<th>seat</th>
<td>5</td>
<th>S2222</th>
</tr>
</tbody>
</table>
</body>
my javascript
$(window).load(function(){
$("#btnSubmit").on("click", function(){
numRows = $("#expected tr").length; //loop thought expected data
for(var i=1 ; i<numRows ; i++){
var code = $("#expected tr:nth-child(" + i + ") td:nth-child(1)").html();
var desc = $("#expected tr:nth-child(" + i + ") td:nth-child(2)").html();
var qty = $("#expected tr:nth-child(" + i + ") td:nth-child(3)").html();
var cage = $("#expected tr:nth-child(" + i + ") td:nth-child(4)").html();
// if code is in expected data -1 from qty col
if(code == $("#code").val()){
$("#expected tr:nth-child(" + i + ") td:nth-child(3)").html(parseInt(qty) - 1);
//delete if last one in expected table
if(qty ==1 ){$("#" + code).remove();}
// loop thought scanned expected table
numRowsB = $("#scannedExp tr").length;
for(var ib=1 ; ib<numRows ; ib++){
var codeExp = $("#scannedExp tr:nth-child(" + ib + ") td:nth-child(1)").html();
var qtyExp = $("#scannedExp tr:nth-child(" + ib + ") td:nth-child(3)").html();
// if in scannedExp add qty by one
if(codeExp == $("#code").val()){
$("#scannedExp tr:nth-child(" + ib + ") td:nth-child(3)").html(parseInt(qtyExp) + 1);
return true;
}
else{ //if not found in expected table add row to scannedExp
$("#scannedExp tbody").append("<tr><td>" + $("#code").val() + "</td><td>" + desc + "</td><td>1</td><td>" + cage + "</td></tr>");
return true;
}
}
return true;
}
else{
alert("not in expected");
}
}})
});
I noticed from your fiddle that the button does not trigger the click event.
Your code had 3 problems that I have fixed and then the code worked fine.
First
I think you meant to use $(document).ready() instead of $(window).load().
Since you want to listen to events, it is better to wait until all DOM elements are loaded and the document is ready before attempting to do anything else.
But since the event trigger I am about to tell you about in my second point does not depend on the document being ready or not, it is not necessary. So I removed it.
Second:
I modified the code to use $(document).on('click','selector',function(){}); instead of $(element).on('click',function(){});
//Use this event
$(document).on('click','#btnSubmit',function(){
...
...
});
//Instead of using this
$("#btnSubmit").on("click", function(){
...
...
});
the .on() I used will work for DOM controls that have been loaded from the page, or ones that you added dynamically. That's why I rely on it all the time.
Third
You forgot a semi-colon at the last line of your code...
...
...
else{
alert("not in expected");
}
}}) // <-- This line has no semi-colon
});
You may check the modified code on this fiddle
The code works fine after the modification.
i just buil a data APIT trough Kimono -> https://www.kimonolabs.com/api/2ewmh21u?apikey=lvafgzGqR6fOqrI0mXAbiPEmQGh7rR4m.
i would like to include it in a simple and nice bootstrap table, like this: http://wenzhixin.net.cn/p/bootstrap-table/docs/examples.html.
i just tried to insert the jquery code given by kimono
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
function kimonoCallback(data) {
// do something with the data
// please make sure the scope of this function is global
}
$.ajax({
"url":"https://www.kimonolabs.com/api/2ewmh21u?apikey=lvafgzGqR6fOqrI0mXAbiPEmQGh7rR4m&callback=kimonoCallback",
"crossDomain":true,
"dataType":"jsonp"
});
</script>
but i didn't manage to create the table.
any advice?
you can active bootstrap table via javascript:
<table id="table">
<thead>
<tr>
<th data-field="nome" data-formatter="linkFormatter">Nome</th>
<th data-field="descrizione" data-formatter="linkFormatter">Descrizione</th>
</tr>
</thead>
</table>
<script>
function linkFormatter(value) {
return '' + value.text + '';
}
function kimonoCallback(data) {
$('#table').bootstrapTable({
data: data.results.collection1
});
}
$.ajax({
"url":"https://www.kimonolabs.com/api/2ewmh21u?apikey=lvafgzGqR6fOqrI0mXAbiPEmQGh7rR4m&callback=kimonoCallback",
"crossDomain":true,
"dataType":"jsonp"
});
</script>
jsFiddle: http://jsfiddle.net/wenyi/8svjf80g/33/
I have no idea what you want to display from your JSONP feed, but generally you can handle the display like so:
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Href</th>
<th>Text</th>
</tr>
</thead>
<tbody id="loadHere">
</tbody>
</table>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
function kimonoCallback(data) {
// this will help you see data structure while you develop the table
console.log(data);
// then create your table
var results = data.results.collection1,
i;
for (i = 0; i < results.length; i += 1) {
$('#loadHere').append(
'<tr>' +
'<td>' + results[i].nome.href + '</td>' +
'<td>' + results[i].nome.text + '</td>' +
'<td>' +
'</table>');
}
}
$.ajax({
"url":"https://www.kimonolabs.com/api/2ewmh21u?apikey=lvafgzGqR6fOqrI0mXAbiPEmQGh7rR4m&callback=kimonoCallback",
"crossDomain":true,
"dataType":"jsonp"
});
</script>
Be sure to look at the console to see how the data is structured so you can determine which fields to populate the table with.
Well.. You need to actually make the table when kimonoCallback gets called.
See?
// do something with the data
// please make sure the scope of this function is global