I have an HTML table and I get the values from that table with JavaScript.
I put them in arrays, but I'm having troubles when I send them to PHP using AJAX.
Here is my JavaScript, because it doesn't call my PHP file. Actually it doesn't do anything:
JavaScript:
function getData(tableID) {
var qty = [];
var messureUnit = [];
var price = [];
var total = [];
var table = x(tableID);
var rowCount = table.rows.length;
for (var i = 1; i < rowCount; i++) {
messureUnit[i] = table.rows[i].cells[2].innerHTML;
price[i] = table.rows[i].cells[3].innerHTML;
price[i] = table.rows[i].cells[4].innerHTML;
qty[i] = table.rows[i].cells[1].innerHTML;
}
var array = JSON.stringify(qty);
$.ajax({
type: "POST",
data: { array1: array },
url: "DataReceiver.php",
dataType: 'json',
success: function (response) {
$('#resp').val(response);
}
});
}
PHP:
$qty=json_decode($_POST['array1']);
if($_POST['array1'])
{
$message="received";
}
echo json_encode($message);
HTML:
I call the JavaScript with a button:
<button type="button" class="btn btn-danger btn-sm" onclick="recogerDatosD('tblFactD');"></button>
<input type="text" readonly class="form-control" id="resp" name="resp">
I don't see anywhere that getData(), your javascript function, is getting called.
Your onclick method on the button is referencing another function that we do not see defined anywhere: onclick="recogerDatosD('tblFactD');"
Instead, that should be
<button type="button" class="btn btn-danger btn-sm" onclick="getData('tblFactD');"></button>
Also make sure that 'tblFactD' is the ID set on the table that you are trying to serialize and POST.
Related
I want to store the variable "clients[i]._id" and send it to another page when I click the button in the for loop.I want to later use that id to get more specific information about that client on its seperate window.
Im getting an undefined error where clients is undefined. Also the console.log in the store(function) doesnt work. Can you find whats wrong?
let thisArray = [];
//let clientId = $('#clientId').val();
$.ajax({
method: 'GET',
url: '/auth/clientsGET',
dataType: 'json',
success: function(clients) {
thisArray = clients
buildTable(thisArray);
console.log(thisArray);
}
})
function buildTable(clients) {
let table = document.getElementById('tabelaClientesAdmin')
for (let i = 0; i < clients.length; i++) {
let row = `<tr>
<td>${clients[i]._id}</td>
<td>${clients[i].name}</td>
<td>${clients[i].admin}</td>
<td><button type="button" class="btn btn-primary" onclick="store()">Ver Cliente</button></td>
</tr>`
table.innerHTML += row
}
}
function store() {
console.log("Trying to get clientId....")
let clientId = clients._id;
sessionStorage.setItem("clientId", clientId);
location.href = "./ver_cliente";
}
I'll update straight away when information is needed.
You could pass the index like that:
onclick="store(${i})"
then retrieve it like that:
function store(index) {
const clientId = thisArray[index]._id;
sessionStorage.setItem("clientId", clientId);
}
Here is a slightly modified but working example of your page:
The most important part is probably:
let clientId=+ev.target.closest("tr").children[0].textContent;
where I navigate from the clicked button (ev.target) via the parent-<tr> to the first child (a <td>). There I read the textContent, convert it into an integer with the unary +-operator and store it in variable clientId.
I also introduced the global variable clients that could be used for further reference in the page. But currently this array not really used anywhere.
var clients
$.ajax({
method: 'GET',
url: 'https://jsonplaceholder.typicode.com/users',
dataType: 'json',
success: function(d) {
clients = d
buildTable(clients);
console.log(clients);
}
})
function buildTable(clients) {
let table = document.getElementById('tabelaClientesAdmin')
for (let i = 0; i < clients.length; i++) {
let row = `<tr>
<td>${clients[i].id}</td>
<td>${clients[i].name}</td>
<td>${clients[i].username}</td>
<td><button class="btn btn-primary">Ver Cliente</button></td>
</tr>`
table.innerHTML += row
}
}
document.body.onclick=function(ev) {
if (ev.target.tagName==="BUTTON") {
let clientId=+ev.target.closest("tr").children[0].textContent;
console.log("Trying to get clientId:",clientId);
// sessionStorage.setItem("clientId", clientId); // not in SO snippets
console.log("go to ./ver_cliente");
}}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tabelaClientesAdmin"></table>
How can I pass 2 variables from ajax to function ?
I can successfully pass 1 variable, but I don't know how to write the code to pass 2 variables. I'm stuck here:
<button id ="+data[i].id+" onclick='tahu("+data[i].id+","+data[i].nama+")'>Detail</button>
Here is my function
function tahu(x, y) {
window.alert(x);
window.alert(y);
}
Here is my full ajax code
function tampilkan() {
var data_table = "";
var head_table = "";
$.ajax({
url: "showkaryawan/da",
dataType: "json",
success: function(data) {
$('#oo').empty();
head_table +="<thead><tr class='bg-info'><th width='10%'>ID Karyawan</th><th width='30%'>Nama Karyawan</th><th width='15%'>Action</th></tr></thead>";
for (var i =0; i<data.length; i++) {
data_table +="<tr><td>"+data[i].id+"</td><td>"+data[i].nama+"</td><td>"+"<button id ="+data[i].id+","+data[i].nama+" onclick='tahu("+data[i].id+")'>Detail</button>"+"</td></tr>";
}
$('#oo').append(head_table);
$('#oo').append(data_table);
}
});
}
Ok, I've tried to solve your problem but without actually doing a json request so bear with me. Firstly, You are already using jquery for your ajax call so why not leverage jquery for your DOM manipulation as well? I have written your function to store the id and nama as attributes on the button element and instead of having an inline function call, I have written a click event handler in jquery to execute any time a button (with class detailButton) is clicked. This function will grab the data-id and data-name from the button itself and should display the information you want, specific to that button.
The final button element:
<button data-id ="id" data-name="nama" class="detailButton">Detail</button>
and the jquery:
//ajax request
function tampilkan() {
var data_table = "";
var head_table = "";
$.ajax({
url: "showkaryawan/da",
dataType: "json",
success: function(data) {
$('#oo').empty();
head_table +="<thead><tr class='bg-info'><th width='10%'>ID Karyawan</th><th width='30%'>Nama Karyawan</th><th width='15%'>Action</th></tr></thead>";
for (var i =0; i<data.length; i++) {
var id = data[i].id;
var nama = data[i].nama;
data_table +="<tr>";
data_table +="<td>"+id+"</td>";
data_table += "<td>"+nama+"</td>";
data_table += "<button data-id ="+id+" data-nama="+nama+" class="detailButton">Detail</button>";
data_table += "<td></td></tr>";
}
$('#oo').append(head_table);
$('#oo').append(data_table);
}
});
}
//click event handler
$('.detailButton').click(function() {
var id = $(this).data('id')
var nama = $(this).data('nama');
alert(id);
alert(name);
});
I took the liberty of expanding your data_table concatenation into multiple lines for ease of reading. Hope this is closer to your final solution.
I'm trying to store table data to Javascript array and send the array to php.
<div>
<h5>PUT SOMETHING 1</h5>
<input type="text" id="sample1" palceholder="SOMETHING" required>
</div>
<div>
<h5>PUT SOMETHING 2</h5>
<input type="text" id="sample2" palceholder="SOMETHING" required>
</div>
<div>
<h5>PUT SOMETHING 3</h5>
<input type="text" id="sample3" palceholder="SOMETHING" required>
</div>
<div>
<button style="margin-top: 20px;" type="button" onclick="output();">OUTPUT</button>
</div>
<div style="margin-top: 10px;">
<table class="table table-striped projects" id="table">
<thead>
<tr>
<th>sample1</th>
<th>sample2</th>
<th>sample3</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<div>
<button type="button" onclick="submit();">SUBMIT</button>
</div>
Here's my script
function delete_row(r) {
var result = confirm("Are you sure? Delete row from order?");
if (result) {
var i = r.parentNode.parentNode.rowIndex;
document.getElementById("table").deleteRow(i);
}//if(result)
}//delete_row();
function output() {
var sample1 = document.getElementById("sample1").value;
var sample2 = document.getElementById("sample2").value;
var sample3 = document.getElementById("sample3").value;
var table = document.getElementById("table");
var row = table.insertRow(table).outerHTML = "<tr id='row'><td>" + sample1
+ "</td><td>" + sample2 + "</td><td>" + sample3 +
"</td><td> <a href='#' onclick='delete_row(this)'>Remove </a></td></tr>";
}//output();
function submit() {
//Store HTML Table Values into Multidimensional Javascript Array Object
var TableData = new Array();
$('#table tr').each(function(row, tr) {
TableData[row] = {
"sample1": $(tr).find('td:eq(0)').text(),
"sample2": $(tr).find('td:eq(1)').text(),
"sample3": $(tr).find('td:eq(2)').text()
}//tableData[row]
});
TableData.shift(); // first row will be empty - so remove
alert(TableData);
var Data;
Data = $.toJSON(TableData);
$.ajax({
type: "POST",
url: "getInfo.php",
data: "pTableData=" + TableData,
success: function(msg) {
//return value stored in msg variable "success";
}//success
});
}//submit();
my php
<?php
// Unescape the string values in the JSON array
$tableData = stripcslashes($_POST['pTableData']);
// Decode the JSON array
$tableData = json_decode($tableData,TRUE);
// now $tableData can be accessed like a PHP array
echo $tableData[1]['sample1'];
?>
The submit function isn't working for me, even if i remove the $.ajax, the alert(TableData) isn't showing. thus I cant verify if my php code and storing html table data is correct, could you please take a look at my submit function and php code to see where did I go wrong?
Thank You in Advance.
function submit() {
//Store HTML Table Values into Multidimensional Javascript Array Object
var TableData = new Array();
$('#table tr').each(function(row, tr) {
TableData[row] = {
"sample1": $(tr).find('td:eq(0)').text(),
"sample2": $(tr).find('td:eq(1)').text(),
"sample3": $(tr).find('td:eq(2)').text()
}//tableData[row]
});
TableData.shift(); // first row will be empty - so remove
alert(TableData);
var Data;
Data = JSON.stringify(TableData);
alert(Data);
$.ajax({
type: "POST",
url: "getInfo.php",
data: "pTableData=" + Data,
success: function(msg) {
return value stored in msg variable "success";
}//success
});
};//submit();`enter code here`
try to change how you send post data to this:
data: { pTableData: TableData},
There are several buttons (they creates dynamically)
<button class="common" id="1.1" status="sale" oncontextmenu="rightButton('1.1'); return false" onclick="addOptions('1.1')" number="1">1</button>
I need to get attributes (class, id, status, number) and insert them into object array. Then input to database.
function saveScheme()
{
var table = document.getElementById('schemeTable');
var elements = table.getElementsByTagName('button');
var arrayIdButtons = {};
for(var i = 0; i<elements.length; i++)
{
arrayIdButtons[i] = {};
for(var j = 0; j<4; j++)
{
arrayIdButtons[i]["coord"] = elements.item([i]).id;
arrayIdButtons[i]["status"] = elements.item([i]).status;
arrayIdButtons[i]["type"] = elements.item([i]).class;
arrayIdButtons[i]["number"] = elements.item([i]).number;
}
}
console.log(arrayIdButtons);
var data='data=' + JSON.stringify(arrayIdButtons,"", 2);
$.ajax({
type: 'POST',
url: "handler.php",
data: data,
cache: false,
data: data,
success: function(data) {
alert(data)
}
});
}
result of this code(console.log(arrayIdButtons);):
Since you're already using jQuery, you can access the attributes of an element using .attr(). For example:
$('.common').attr('number');
Or, without jQuery,
elements[i].getAttribute('number');
Use HTML5 API data
<button class="common" id="1.1" data-status="sale" oncontextmenu="rightButton('1.1'); .....</button>
So,
elements.item([i]).data('status'); //if jquery enabled
You can try this html. then,
<button class="common" data-id="1.1" data-status="sale" data-number="1">1</button>
If DOM is not loaded, then you can get this by
$(document).ready(function(){
$(".common").on("click",function(){
var data_id = $(this).attr('data-id');
var data_status = $(this).attr('data-status');
var data_number = $(this).attr('data-number');
console.log(data_id);
console.log(data_id);
console.log(data_id);
});
});
And if DOM is already loaded you can get them by
$(document).on("click",".common",function(){
var data_id = $(this).attr('data-id');
var data_status = $(this).attr('data-status');
var data_number = $(this).attr('data-number');
console.log(data_id);
console.log(data_id);
console.log(data_id);
});
Then you can push this is an array. Note - this will give you the attributes of only the button was clicked
I have an editable table in my view.. At first, there's no data in the table but the user can add data in the table since it is editable. And there's no exact number of rows in the table since I have also a button that can add new row. I want to get the data that the user have added and save it in the database.
I have this code:
VIEW:
<table class="table " id="memberTB">
<thead><tr><th >First Name</th><th >Middle Name</th><th>Last Name</th></tr></thead>
<tbody>
<tr id="first"><td><span class="edit"></span></td>
<td><span class="edit"></span></td>
<td><span class="edit"></span></td></tr>
</tbody>
<button type="button" class="btn btn-link" id="addrow"><span class="fa fa-plus"> Add new row</span></button>
</table>
<br><button type="button" class="btn" id="savebtn">Save</button> Reset
JS:
$.fn.editable.defaults.mode = 'inline';
$.fn.editable.defaults.showbuttons = false;
$.fn.editable.defaults.url = '/post';
$.fn.editable.defaults.type = 'text';
// make all items having class 'edit' editable
$('.edit').editable();
// this is to automatically make the next item in the table editable
$('.edit').on('save', function(e, params){
var that = this;
// persist the old value in the element to be restored when clicking reset
var oldItemValue = $(that)[0].innerHTML;
if (!$(that).attr('oldValue')) {
console.log('persisting original value: ' + oldItemValue)
$(that).attr('oldValue', oldItemValue);
}
setTimeout(function() {
// first search the row
var item = $(that).closest('td').next().find('.edit');
console.log(item);
if (item.length == 0) {
// check the next row
item = $(that).closest('tr').next().find('.edit');
}
item.editable('show');
}, 200);
});
$('#resetbtn').click(function() {
$('.edit').each(function() {
var o = $(this);
o.editable('setValue', o.attr('oldValue')) //clear values
.editable('option', 'pk', o.attr('pk')) //clear pk
.removeClass('editable-unsaved')
.removeAttr('oldValue');
});
});
$('#savebtn').click(function() {
var person = [];
var x=1;
$('tbody tr',$('#memberTB')).each(function(){
for(var i = 0 ; i < cells ; i++)
{
person[x][i]=$(this).find('td').eq(i).text();
}
x++;
});
$.ajax({
url: '<?php echo base_url("index.php/test/Savedata");?>',
type: "post",
data: { values: arraylng },
cache: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
}
});
});
$('#addrow').click(function() {
$('#memberTB > tbody:last').append(' <tr><td><span class="edit"></span></td><td><span class="edit"></span></td><td><span class="edit"></span></td></tr>');
$('.edit').editable();
});
Controller: [inside the test.php]
public function saveData(){
$this->load->model('test_model');
$myArray = $_REQUEST['values'];
echo sizeof($myArray);
}
Whenever I click the save button, there's no response at all.. Where did I go wrong? please help me..
ADDED INFO:
I didn't include my SQL insert statement here because I want to test first if there's data in $myArray if I added data in the table.
Better use this ajax
var arraylng = [3,4,7];
$.ajax({
url: '<?php echo base_url("index.php/test/Savedata");?>',
type: "post",
data: {values: JSON.stringify(arraylng)},
cache: false,
success: function (response) {
alert(response);
}
});
arraylng is an array, which doesn't exist in the code. I added it here for debugging.
Suppose you want to send person[] array, you write, data: {values: JSON.stringify(person)}.
Now, the person array may not exist, because of the "i < cells" in for. What is cells?
The word response is just a name, any name, but better avoid 'data'.
In test.php, what is sizeof($myArray)? Just, echo $myArray;
When you click save you must get the $myArray content in an alert.