Issue regarding ajax and identifying data from a table - javascript

I'm desperately trying to gain access to the $BarcodeID by pressing the DELETE button on my site. All I want to do is retreive this 13 digit number, so that I can use it to remove that row from the item Database (Sql).
I know that as long as I get the correct row I can get the data but i'm wondering if thats even possible because I'm building the table inside a $.post().
Please note that before i started trying to make the button and get the barcodeID in the click function all of the code was working. Thanks!
$(document).ready(function(){
$.get("../php/security.php", function(response){
if(response.result == "failure"){
location.href='../user_login.html';
} else {
$("#header").load("../header_logout.html");
$.post("../php/item_database.php", {email1:response.data.authUser}, function(indata){
indata.items.forEach(function(element){
$BarcodeID = element.BarcodeID;
$UserID = element.UserID;
$ProductName = element.ProductName;
$BrandName = element.BrandName;
$Weight = element.Weight;
$row = "<tr><td id='rowbarcode'>" + $BarcodeID + "</td>" + "<td>" + $ProductName + "</td>" + "<td>" + $BrandName + "</td>" + "<td>" + $Weight + "</td>" + "<td>" + "<button class='delete'>Delete</button>" + "</td></tr>";
$("#final_row").before($row);
});
}, "json");//eo post
} //eo else
}, "json"); //eo get
$(".delete").click(function(){
// var BarcodeID = $(this).closest('tr').find('#rowbarcode').val();
var BarcodeID = $(this).parent().find("#rowbarcode").text();
var $row = $(this).closest("tr"); // Finds the closest row <tr>
var $tds = $row.find("td:nth-child(1)"); // Finds the 2nd <td> element
console.log($tds);
//all I want is $BarcodeID
});
});//eof
Image of table on site:

Just for anyone who's interested I found a pretty neat way of solving my problem. Thanks to everyone who helped #Pointy #Taplar #Andreas. What I needed was 'event binding on dynamically created elements'. It is particularly useful when linked with $.post and $.get operations as they complicate data retreival.
Sample output to console:
5000157024671 <- if i clicked the first delete button
6221033101517 <- if i clicked the second delete button
Next stage:
As this is only a reference to a barcode number which has to be removed from the DB I will now pass this onto php via a post operation.
Next part of my project (adding a row search feature) can be found here:
Dynamically created table queries
Sample solution code:
$(document).ready(function(){
$.get("../php/security.php", function(response){
if(response.result == "failure"){
location.href='../user_login.html';
} else {
$("#header").load("../header_logout.html");
//from here down is the relevant code
$.post("../php/item_database.php", {email1:response.data.authUser}, function(indata){
indata.items.forEach(function(element){
$BarcodeID = element.BarcodeID;
$UserID = element.UserID;
$ProductName = element.ProductName;
$BrandName = element.BrandName;
$Weight = element.Weight;
$row = "<tr class='row'><td class='rowbarcode'>" + $BarcodeID + "</td>" + "<td>" + $ProductName + "</td>" + "<td>" + $BrandName + "</td>" + "<td>" + $Weight + "</td>" + "<td>" + "<button class='delete'>Delete</button>" + "</td></tr>";
$("#final_row").before($row);
});
}, "json");//eo post
} //eo else
}, "json"); //eo get
$(".contenttable").on('click', '.delete', function(){
var BarcodeID = $(this).closest('tr').find('.rowbarcode').text();
console.log(BarcodeID);
});
});//eof

Related

Get return true values using if else statements in jquery

I want to get true values from the if/else statement using jQuery. I apply this code but I can't get the required output. It displays both true and false values.
$.each(response, function(index, value) {
var user = (user_id == value.User_id);
if (user_roll == 'Customer' && user) {
if (user === true) {
//alert(user === true);
html += "<tr data-id='" + value.ticket_id + "'>";
html += "<td>" + value.ticket_id + "</td>";
html += "<td>" + value.User_id + "</td>";
html += "<td>" + value.User_name + "</td>";
html += "<td>" + value.Customer_name + "</td>";
html += "<td>" + value.subject + "</td>";
html += "<td>" + value.priority + "</td>";
}
}
The response is this : [The response I got][1]
[1]: https://i.stack.imgur.com/oePac.png . I want to get only User_id = 1 records
try comparing the string values together. Sometimes what happens is one of the id that you pass is read as String.
So ,
user_id.toString() == value.User_id.toString()
this is what I do in Javascript to compare id, please check how to convert into String in jquery.

Javascript Append Function, Need to build a loop

I have a .php file where I am using both HTML and JavaScript to display items from my database. I have a JavaScript append function that is creating cards where each item is display. On my cards, I have a button that will expand the card to show product history. Some products have more history than others so the expansion needs to be dynamic. The historical data is being pulled from database and is initially in a php array. I originally was going to institute php into the javascript append function but I could not figure out how to set the JavaScript index variable 'I' to my php index. So I want to just stay with JavaScript. But I don't know how to write a loop in the middle of this append function that will loop through the historical array and populate the expansion. Below is what I am attempting. I took out a lot of the lines in the append function but you can see what I am trying to do.
function get_products() {
clear_cards();
$.each(productNumbers,
function(i, value) {
$('.main_card_shell').append(
"<div class='card_content card_style' id='card" + i + "'>" +
"<div id='card_tab2" + i + "' class='tabcontent' data-tab='tab-name2'>" +
"<div class='details_tables'>" +
"<table>" +
"<tr>" +
"<th>Item Type</th>" +
"<th>Painted</th>" +
"<th>Last Sold" +
"<a id='_close_tab" + i + "' class='tablinks tab_override' onclick=\"openCity(event,'card_tab4" + i + "')\">" +
"<i class='large angle up icon'></i>" +
"</a>" +
"</th>" +
"</tr>" +
"<tr>" +
var itemdatesplit = itemdate[i].split("$$");
var itemtypesplit = itermtype[i].split("$$");
var itemsplit = item[i].split("$$");
var arraylength = itemsplit.length;
var counter = 0;
while(counter < arraylength)
{
+ "<td>" + itemtypesplit[counter] + "</td>" +
+ "<td>" + itemdatesplit[counter] + "</td>" +
counter = counter + 1;
}
+
"</tr>" +
"</table>" +
"</div>" +
"</div>" +
Please help. I had it working with PHP inserted in, but I just couldn't figure out how to set it to a PHP variable.
Place this code into a function:
function getSomething(i) {
var html = '';
var itemdatesplit = itemdate[i].split("$$");
var itemtypesplit = itermtype[i].split("$$");
var itemsplit = item[i].split("$$");
var arraylength = itemsplit.length;
var counter = 0;
while(counter < arraylength) {
html += "<td>" + itemtypesplit[counter] + "</td>";
html += "<td>" + itemdatesplit[counter] + "</td>";
counter = counter + 1;
}
return html;
}
And then use it in your HTML building block:
'<some html>' + getSomething(i) + '<some other html>'

Bootstrap Datatable is no longer functioning after loading content via Ajax

Before some one says its a duplicate question, i know it is. I've just not been able to find anyone's script that looks similar to mine and as i'm completely new to JavaScript and JQuery (used to php) i don't really know what I'm doing.
My datatable worked perfectly having the data loaded using php (before the page had loaded) but now its loaded after the page load, the table has lost all of it's filtering and pagination.
Here is how my table is loaded.
<div class="table-responsive">
<table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
<thead>
<tr>
<?php echo $tableheader;?>
</tr>
</thead>
<tfoot>
<tr>
<?php echo $tableheader;?>
</tr>
</tfoot>
<tbody id="data"> <!--data will be inputed here-->
</tbody>
</table>
</div>
This is the script that gets the data and puts it into the table.
<script>
//call ajax
var ajax = new XMLHttpRequest ();
var method = "GET";
var url = "data_assets.php";
var asynchronous = true;
setInterval(function(){
ajax.open(method, url, asynchronous);
//sending ajax request
ajax.send();
}, 250)
//receiving response from data_assets.php
ajax.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
//convert JSON back to array
var data = JSON.parse(this.responseText);
//console.log(data); //for debugging
//html value for <tbody>
var html ="";
//looping through the data
for (var a = 0; a < data.length; a++) {
var asset_number = data[a].asset_number;
var id = data[a].id;
var room = data[a].room;
var _location = data[a]._location;
var sku = data[a].sku;
var qty = data[a].qty;
var _value = data[a]._value;
var date = data[a].date;
var po_number = data[a].po_number;
var purchaced_from = data[a].purchaced_from;
var notes = data[a].notes;
var total = data[a].total;
//storing in html
html += "<tr>";
html += "<td style='vertical-align: middle;'>" + asset_number + "</td>";
html += "<td style='vertical-align: middle;'>" + id + "</td>";
html += "<td style='vertical-align: middle;'>" + room + "</td>";
html += "<td style='vertical-align: middle;'>" + _location + "</td>";
html += "<td style='vertical-align: middle;'>" + sku + "</td>";
html += "<td style='vertical-align: middle;'>" + qty + "</td>";
html += "<td style='vertical-align: middle;'>" + _value + "</td>";
html += "<td style='vertical-align: middle;'>" + total + "</td>";
html += "<td style='text-align: center; vertical-align: middle;'>" + date + "</td>";
html += "<td style='vertical-align: middle;'>" + po_number + "</td>";
html += "<td style='vertical-align: middle;'>" + purchaced_from + "</td>";
html += "<td style='vertical-align: middle;'>" + notes + "</td>";
html += "<td style='text-align: center; vertical-align: middle;'>";
html += "<a href='?id=" + id + "&room=" + room + "&asset=" + asset_number + "&location=" + _location + "&sku=" + sku + "&qty=" + qty + "&value=" + _value + "&date=" + date + "&po=" + po_number + "&where=" + purchaced_from + "&notes=" + notes + "#editModal' class=''><i class='far fa-edit fa-lg'></i></a>";
html += "</td>";
html += "<td style='text-align: center; vertical-align: middle;'>";
html += "<a href='?id=" + id + "&room=" + room + "&asset=" + asset_number + "&location=" + _location + "&sku=" + sku + "&qty=" + qty + "&value=" + _value + "&date=" + date + "&po=" + po_number + "&where=" + purchaced_from + "&notes=" + notes + "#duplicateModal' class=''><i class='far fa-clone fa-lg'></i></a>";
html += "</td>";
html += "</tr>";
}
//replacing the <tbody>
document.getElementById("data").innerHTML = html;
}
}
</script>
If anyone could show me how to get this working in my example it would be greatly appreciated, I really want to load all of my tables on this site like this so i dont need to have a refresh on saving data (This refreshes every 250ms so the data in the table is always up to date with the database).
Update:
Right i took out my 250ms refresh and now the table works perfectly! is anyone now able to help me with my next issue. How do i get the table to refresh when new data is entered into the database, without refreshing the whole page
I suggest creating the table structure in HTML or PHP (not Javascript). Then load the data into the table with ajax. Those DOM elements are not readily available to javascript unless the event to create the elements is bound to an element that already exists like body or document or some other parent element of the table.
UPDATE:
I personally don't have much experience with DataTables plugin. So the plugin will automatically create your DOM elements (table structure) based on either the data object returned from ajax or by properties you specify. DataTables does use jQuery's ajax() method to make ajax calls however you should not override the success callback. There is a proper way to use their API when making ajax calls as specified in the documentation. There is also a proper way to reload data on an interval to refresh your tables.
Please check out this fiddle.
The ajax url, method, data properties must of course be updated to fit your application (this was the only way to simulate ajax call on jsFiddle. Please note you will have to have properly formatted JSON.
Did you tried to explicitly set pagelength property on Datatables?
$('#datatable').dataTable( {
"pageLength": 50
} );

Add HTML code inside of a JS var that contains an HTML element

I need to add a list of task after to click one row in a html table I'm using knockout js. the problem is that I'm just adding de last task from my data in a row and I need to add a new TR inside my element "$taskSelected" for each task. Here is my code
self.retrieveTask = function(data, event) {
if (event.type=="click") {
var id = data.Id;
var $taskSelected = event.currentTarget.parentElement.nextElementSibling;
$.get("#Url.Action("Method", "Controller")", { id: id })
.done(function(data) {
$.each(data, function(key, value) {
var html = "<tr><td>" +
"</td>" +
"<td>" +
" <div >" +
+ value.Type +
"</div> " +
"</td>" +
"<td>" +
" <div >" +
value.Id +
"</div> " +
"</td>" +
"</tr>";
$taskSelected.innerHTML=html;
});
}).fail(function() {
alert("error");
});
};
}
the var $taskSelected contains another row "<tr> </tr>" basically Ii want to nested rows. Some advises please
Try this:
self.retrieveTask = function(data, event) {
if (event.type=="click") {
var id = data.Id;
var $taskSelected = event.currentTarget.parentElement.nextElementSibling;
$.get("#Url.Action("Method", "Controller")", { id: id })
.done(function(data) {
var html = "";
$.each(data, function(key, value) {
html += "<tr><td>" +
"</td>" +
"<td>" +
" <div >" +
+ value.Type +
"</div> " +
"</td>" +
"<td>" +
" <div >" +
value.Id +
"</div> " +
"</td>" +
"</tr>";
});
$taskSelected.innerHTML=html;
}).fail(function() {
alert("error");
});
};
}
All I did was move var html outside of your each loop. This makes sure that all your previous HTML stays inside the variable, otherwise you are overwriting html each time you run through the loop (This is why you're only outputting the last one ;) ).

How to pass id of dynamic drop downlist?

I have dynamic table, in that table every row has a dynamic dropdown list. So every dynamic dropdown list have a unique id, I have to pass this id to the onChange function. Please tell me how to do this. Please see this question for more info.
<select id=carpender"+obj[i].b_id +"onChange='update(this.id)
The data in the table is dynamically generated. I have to pass an id like carpenter12, if the value of obj[i].b_id is 12.
Working code I modified this code
JavaScript:
<script>
function fetchData1(){
$(".data-contacts1-js tbody").empty();
$.get("http://localhost/service/services.php", function(data) {
var obj=JSON.parse(data);
// convert it into obj otherwise it will give
//alert(obj.length);
for(var i in data){
var tr=$("<tr></tr>");
tr.append(
"<td>" + obj[i].b_id + "</td>" +
"<td>" + obj[i].cust_name + "</td>" +
"<td>" + obj[i].cust_mobile + "</td>" +
"<td>" + obj[i].cust_email + "</td>");
tr.append("<select id="+obj[i].b_id+" onChange='update(this.id)' class='input-small'><option value='New Job'>New Job</option><option value='WIP Job'>WIP Job</option><option value='Close Job'>Close Job</option></select>");
$(".data-contacts1-js tbody").append(tr);
i++;
}
});
}
$(document).ready(function(){
$(".data-contacts1-js tbody").empty();
$('#fetchContacts1').click(function() {
fetchData1();
});
});
</script>
<script>
function update(id){
alert(id);
}
</script>

Categories