how can i differentiate multiple rows with same class using javascript? i've searched it but it shows only jquery and i know nothing about it.
my rows always shows the amount in inventory of the last product selected like this example in this pic the example
here's what i wrote as js function:`
function showAmount(variable)
{
this.product = variable;
if(product == '')
{
document.getElementsByClassName('qte').innerHTML = " ";
}else
{
const xmlhttp = new XMLHttpRequest();
var table = document.getElementById('tbody');
//var rows = table.rows.length;
//console.log(rows);
var rows = document.getElementsByClassName('qte');
console.log(rows[1]);
xmlhttp.onload = function(){
myObj = JSON.parse(this.responseText);
for(var j = 0; j < rows.length; j++)
{
for (var i = 0; i < myObj.length; i++)
{
if(product === myObj[i]['NomArt'])
{
rows[j].innerHTML = myObj[i]['Qte'];
}
}
}
}
xmlhttp.open("GET", "templates/Client/products.json", "true");
xmlhttp.send();
}
}
this function add rows to the table
function addItem() {
items++;
// code...
var html = "<tr>";
html += "<td><input type='text' class='form-control' name='product[]' list='produit' id='pick' onchange='showAmount(this.value)' ><datalist id='produit'> <?php foreach ($productinfo as $req) { ?><option value='<?php echo $req['NomArt']; ?>'><?php echo $req['NomArt']; } ?></option></datalist></td>";
html += "<td class='text-center qte'></td>";
html += "<td><input type='number' class='form-control' name='qte[]'></td>";
html += "<td><button type='button' class='btn btn-danger' onclick='remove(this);'><i class='fa fa-close'></i></button></td>";
html += "</tr>";
var row = document.getElementById("tbody").insertRow();
row.innerHTML = html;
}
`
And i couldn't understand others exactly as they showed jquery with Ids and stuff. is there a way to do it with php cuz php approach also gave the same results showing the amount of the last product that's why i took javascript approach but couldn't get a handle of it.
It would help to see your response, but I think the problem is that you're checking one product and updating all rows. You need to identify which row to update, and if your user puts the same product name in two different rows, your system will be confused, so start by changing your function call to onChange="showAmount(this)", so you're passing a DOM element rather than text.
function ShowAmount(productInput) {
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
myObj = JSON.parse(this.responseText);
row = productInput.parentElement.closest('tr'); // find the table row
let i = myObj.map(item => item.NomArt).indexOf(productInput.value); // find matching data in response
row.getElementsByClassName('qte')[0].innerHTML = myQbj[i].Qte // update the row
}
xmlhttp.open("GET", "templates/Client/products.json", "true");
xmlhttp.send();
}
Of course, you're downloading the entire product catalogue every time the user makes a single change. If your database is large, this is very inefficient. You'd be better updating your back end to return data on a specified product.
xmlhttp.open("GET", "templates/Client/products.json?product="+productInput.value, "true");
Related
I'm trying to read a .dat file (it's a CSV with delimiter';') and convert it into a table and is done in PHP and is as follows:
<table id='sol'>
<?php
echo "<html><body>";
$f = fopen("/var/www/html/uploads/data_old.dat", "r");
$var = 0;
/* Writes the CSV to table in the page*/
while (($line = fgetcsv($f, 0, ';')) !== false) {
echo "<tr>";
foreach ($line as $cell) {
if ($var < 36) {
echo "<th>" . htmlspecialchars($cell) . "</th>";
$var = $var + 1;
}
else {
echo "<td><div contenteditable>" . htmlspecialchars($cell) . "</div></td>";
}
}
echo "</tr>";
}
fclose($f);
echo "</body></html>";
?>
</table>
Now after editing the values in the table, I need to save this table on the server. Currently, I can download the table in .dat using a script written in JS as below:
// Quick and simple export target #table_id into a csv
function download_table_as_csv(table_id, separator = ';') {
// Select rows from table_id
var rows = document.querySelectorAll('table#' + table_id + ' tr');
// Construct csv
var csv = [];
for (var i = 0; i < rows.length; i++) {
var row = [], cols = rows[i].querySelectorAll('td, th');
for (var j = 0; j < cols.length; j++) {
// Clean innertext to remove multiple spaces and jumpline (break csv)
var data = cols[j].innerText.replace(/(\r\n|\n|\r)/gm, '').replace(/(\s\s)/gm, ' ')
// Escape double-quote with double-double-quote
data = data.replace(/"/g, '""');
// Push escaped string
row.push('"' + data + '"');
}
csv.push(row.join(separator));
}
var csv_string = csv.join('\n');
// Download it
var filename = 'data_new' + '.dat';
var link = document.createElement('a');
link.style.display = 'none';
link.setAttribute('target', '_blank');
link.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv_string));
link.setAttribute('download', filename);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
I'm fairly new to this and any help is highly appreciated.
I might not understand the question here, but I think its something like "I get a csv file from a user - how to display file's fields as an HTML table, and then setup a download link for newly editted file"
If that sounds correct, this is probably what you want.
You are correctly displaying the CSV as an HTML table (as far as I can tell).
if htmlspecialchars(..) changes the characters emitted from data_old.dat then we start writing a new CVS file where we'll place the changes emitted by htmlspacechars(..) - and you write in the delimiter yourself by adding ; (as you noted).
$f_ = fopen("/var/www/html/uploads/data_new.dat", "w");
And which ever file we wish the user to download, just place it inside an <a href='...'> tag.
<?php echo "<a href='uploads/data_new.data'>download</a>" ?>
Furthermore (Getting user edits):
While the example above tells us how to setup the backend for the user downloading the file, - it doesn't outline a way for the user to commit edits, and the backend to know about it.
To do allow the server to know about user edits, as mentioned in the comments AJAX is the way to go for php.
AJAX is Javascript sending XML (body) notation to the backend as an http request. The way it works is described in the image below.
AJAX is accessed by javascript in the browser (hey the where the user is!)
var xhttp = new XMLHttpRequest(); // setup object
// hook function
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// this is ran after we get an OK from the server.
// after they've committed a change
}
};
// setup request
xhttp.open("GET", "link/to/your/website", true)
xhttp.send(); // send it
AJAX playground
So far this is pretty vague outlining of what it is, now lets see how we can use it.
So the idea being that when a user changes a field in the table, we run some javascript to send an AJAX request. Specifying what they changed.
The server gets the request, updates the changes on the backend, and then sends OK back to the client.
Hope this helps.
hello there i am trying to display the result of data request of a json feed and put it into a html table. the json data looks like this:
0->data->status:RESOLVED 1->data->status:RESOLVED
and so on . . .
[{"data":{"status":"RESOLVED"}},{"data":{"status":"RESOLVED"}}]
I am accessing the feed using this code:
<script type="text/javascript">
function livedepotrack () {
$(document).ready(function(){
$.ajax({
url: "https://www.xxxxx.org/livexxxx.php",
method: "GET",
success: function(depolivetrack) {
// console.log(depolivetrack)
// var statusdepojs = depolivetrack[key].data.status;
//console.log(key, depolivetrack[key].data.status);
//Object.keys(depolivetrack).forEach(function(key) {
// var lolo = depolivetrack[key].data.status;
//});
var mainContainer = document.getElementById("livedepostatus");
for (var i = 0; i < depolivetrack.length; i++) {
var div = document.createElement("div");
div.innerHTML = depolivetrack[i].data.status;
mainContainer.appendChild(div);
}
}
})
console.log('DEPOTRACKER');
//console.log(b);
})
}
var interval = setInterval(function () { livedepotrack(); }, 6000);
</script>
echo "<td align='center' width='200'> <span class='badge bg-info'><div id='livedepostatus'></div></span> </td>";
inside while that runs over a sql query i have the td tags for the table i am calling the result like this
echo "<td align='center' width='200'>
<span class='badge bg-info'>
<div id='livedepostatus'>
</div>
</span>
</td>";
Now i have seen the code working but not in the right way i creates a div element and it repats, this code is something i put together copy pasting from the web so i am bit stuck, what i need is to display the result of the json on each row of the html table and when interval functions runs it updates that field. hope you can help me thanks in advance
I'm having some issues submitting an HTML form. The form allows the user to add skills to the HTML page using a button. These newly created skills then need to be inserted into the database. The problem is, I can only insert one skill at a time. The skills are entered as checkboxes and all checked skills should be entered in the database. I think my issue is that each checkbox that is created dynamically shares the same $skill_name variable, but this is not an issue when I grab existing skills from the database to display. I added some ajax to try and save each skill in a post statement as they are created, but it doesn't help when I actually go to insert. The INSERT statement looks something like this:
if(!empty($_POST["backend"])){
$backend = $_POST["backend"];
$sql2 = "INSERT INTO skill (skill_cat_id, skill_name) VALUES (?,?)";
$skill_cat_id = 1;
for ($i = 0; $i < count($backend); $i++){
$skill_name = $_POST["skill_name"];
if($stmt = $mysqli->prepare($sql2)){
$stmt->bind_param("is", $skill_cat_id, $backend[$i]);
if ($stmt->execute()) {
echo "<script>
alert('Success!');
</script>";
}
else{
echo "<script>
alert('Failure!');
</script>";
}
}
}
}
And the HTML for looks like this:
<h5>Backend Technologies </h5>
<div class="container">
<div id = "backendDiv">
<?php
$backend=getbackendtech();
while($row = $backend -> fetch_assoc()) {
// echo "<input type='checkbox' value='{$data['skill_name']}'>". $data['skill_name'];
echo "<div class=\"list-group-item checkbox\" id = \"backendCheckBoxes\">
<label><input type=\"checkbox\" name=\"backend[]\" class=\"common_selector form\" value='{$row['skill_name']}'> {$row['skill_name']}</label>
</div>";
}
echo"<input type=\"button\" class='btn btn-warning btn-sm' id = \"addBackendButton\" value = \"Add\" onclick=\"addSkill('backendCheckBoxes', 'backendDiv', 'backend', 'addBackendButton')\">";
?>
</div>
</div>
And here is the addSkill event:
function addSkill(checkBoxDivId, divId, nameId, buttonId){
//Variables
//Creating new elements for new skills and
//setting their attributes
let count = 0;
console.log(checkBoxDivId);
let existingSkills = document.querySelectorAll("div[id =" + checkBoxDivId +"]");
console.log(existingSkills);
for (let i = 0; i < existingSkills.length; i++){
count++;
}
let uniqueId = count+1;
console.log(uniqueId);
let hiddenValue = document.createElement("input");
hiddenValue.setAttribute("hidden", true);
hiddenValue.setAttribute("name", "skill_name");
let checkBoxDiv = document.createElement("div");
checkBoxDiv.setAttribute("id", checkBoxDivId);
checkBoxDiv.setAttribute("class", "list-group-item checkbox");
//console.log(checkBoxDiv);
let textBoxParent = document.getElementById(divId);
//console.log(textBoxParent);
let newTextBox = document.createElement("input");
newTextBox.setAttribute("type","text");
newTextBox.setAttribute("id", "newTextBox");
let newCheckBox = document.createElement("input");
newCheckBox.setAttribute("name", nameId);
newCheckBox.setAttribute("class", "common_selector form");
newCheckBox.setAttribute("type","checkbox");
newCheckBox.setAttribute("checked", true);
newCheckBox.setAttribute("value", uniqueId);
let newLabel = document.createElement("label");
newLabel.setAttribute("for", "newCheckBox");
let addButton = document.getElementById(buttonId);
//console.log(addButton);
//adding textbox to page
textBoxParent.appendChild(newTextBox);
//When an enter key is pressed the newly created textBox
//will be removed and a new checkbox will appear
newTextBox.addEventListener("keypress", function(event) {
// Number 13 is the "Enter" key on the keyboard
if (event.keyCode === 13) {
//console.log(newTextBox.value);
//Canceling the default action, if needed
event.preventDefault();
event.stopPropagation();
//Setting Label value
newLabel.innerHTML = newTextBox.value;
let skill_name = newLabel.innerHTML;
console.log(newCheckBox.getAttribute("value"));
//posting skill name to database
hiddenValue.setAttribute("value", newLabel.innerHTML);
console.log(hiddenValue);
//Remove textbox from page
textBoxParent.removeChild(newTextBox);
//Adding new Checkbox to Div
checkBoxDiv.appendChild(newCheckBox);
checkBoxDiv.appendChild(newLabel);
//checkBoxDiv.appendChild(hiddenValue);
//Adding new Checkbox Div to page
addButton.before(checkBoxDiv);
$.ajax({
type: 'post',
data: {skill_name: skill_name},
success: function(response){
alert(skill_name);
}
});
}
});
}
Edited the codes to add in full code
<!DOCTYPE html>
<html>
<body>
<h2>Make a table based on JSON data.</h2>
<button onClick="makeAjaxQueryMarket()">
Table1
</button>
<button onClick="makeAjaxQueryMarket2()">
Table2
</button>
<script>
function makeAjaxQueryMarket(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
readyStateChangeHandler(xhttp);
};
xhttp.open("GET", "country.json", true);
xhttp.send();
}
function readyStateChangeHandler(xhttp){
if (xhttp.readyState == 4){
if(xhttp.status == 200){
handleStatusSuccess(xhttp);
}else{
handleStatusFailure(xhttp);
}
}
}
function handleStatusFailure(xhttp){
var displayDiv = document.getElementById("display");
displayDiv.innerHTML = "XMLHttpRequest failed: status " + xhttp.status;
}
function handleStatusSuccess(xhttp){
var jsonText = xhttp.responseText;
// parse the json into an object
var currencyObj = JSON.parse(jsonText);
// display the object on the page
displayCurrency(currencyObj);
}
// display the market object on the page
function displayCurrency(currencyObj){
var html = "Table1";
html += "<table border='1'>";
html += "<tr><th>Name</th><th>Alpha-2</th><th>Currency</th></tr>";
for(var i=0; i < currencyObj.CountryList.length; i++){
var recordObj = currencyObj.CountryList[i];
html += "<tr>";
html += "<td><b>" + recordObj.name + "</b></td>";
html += "<td align='right'>" + recordObj.alpha2 + "</td>";
html += "<td align='right'>" + recordObj.currency+ "</td>";
html += "</tr>";
}
html += "</table>";
// show the constructed HTML code in the display div
var displayDiv = document.getElementById("display");
displayDiv.innerHTML = html;
}
</script>
</body>
</html>
I want to insert multiple buttons to generate different tables.
<Button> Onclick ="makeAjaxQuery()" </button>
Currently, I am able to generate a table from this. But what i wanted to do is to code more buttons to generate a different table. However, when i try to use the same code, i could not produce the tables, instead it all ended up the same. I have tried to use different names for the functions.. but doesn't help.
Is possible to put words in the function bracket of my AjaxQuery? like
makeAjaxQueryMarket(tb2)
i have display data from xml file to the index.php like this
function processXML($node){
foreach($node->children() as $agent => $data){
$agent= trim($agent);
if($agent=='image')
{
echo '<div><img src="'.$data.'" ></div>';
echo '<div>';
echo '</div>';
}
elseif($agent=='id')
{
echo '<div class = "Left">';
echo '<input type = "button" name="Agent" id = "'.$data.'" class = "subs-btn" value = "Select this Agent" OnClick = Selected(this.id);>';
$_SESSION['Selected'] = $data;
echo '</div>';
echo '<br/>';
echo '<br/>';
}
else
{
echo '<div class = "inline1">';
echo $data;
echo '</div>';
echo '<br/>';
}
processXML($data);
}
}
processXML($xml);
you guys can see here i am generating a button and onclick function is call - Selected(this.id);
So here is the code of function
function Selected(elem) {
var buttons = document.getElementsByClassName('subs-btn');
var length = buttons.length;
for (var i = 0; i < buttons.length; i++) {
buttons[i].style.backgroundImage="url('images/subs-btn.png')";
buttons[i].value="Select this Agent";
}
document.getElementById(elem).style.backgroundImage="url('images/subs-btn-act.png')";
document.getElementById(elem).value="Agent Selected";
}
So due to this agent is selected. Now i had one button at the end of the page
<input type = "submit" name="Continue" class = "btn btn-primary right" value = "Continue">
now i want to display data which is related to selected agent on another page. So how can i display this data with respect to selected agent?
Please Help.
You would need to something along the lines of the following. This is more just psuedo code than an actual working example, as I don't know what you want to display about an agent
Note: I am assuming you have jQuery included.
JS
function Selected(elem) {
var buttons = document.getElementsByClassName('subs-btn');
var length = buttons.length;
for (var i = 0; i < buttons.length; i++) {
buttons[i].style.backgroundImage="url('images/subs-btn.png')";
buttons[i].value="Select this Agent";
}
document.getElementById(elem).style.backgroundImage="url('images/subs-btn-act.png')";
document.getElementById(elem).value="Agent Selected";
//Start here
var AgentData = ""//something about the agent. their id or some other identifier
//here you would make an ajax call to a php script
$.ajax({
type:"POST",
data: AgentData,
url: "someurl"
});
}
PHP
$_SESSION["AgentData"] = $_POST["AgentData"];
Now you would be able to access that data about the selected agent anywhere as long as there is a valid session.