Store HTML Table Data into Javascript Array - javascript

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},

Related

GetJSON jquery returns undefined

I am trying to get my search box to work and do a getJSON on text search and title. but in the console log, I get text=undefined?title=undefined. so it is not displaying any JSON. Not sure if my click is working correctly or if I have to make my JSON objects?
Script
<script>
var searchstring = $('input[type="text"]', this).val();
var url = "https://data.edu/api/v1/metadata";
url += "?text=" + searchstring;
url += "?title=" + searchstring;
$(document).ready(function() {
$('button[type="button"]').click(function(event){
$.ajax({
type: "GET",
url: url,
success: function(res){
console.log(res);
var items = res.data.metadata;
var ins = "";
for (var i = 0; i < items.length; i++){
ins += "<div>";
ins += "Title" + items[i].title;
ins += "Title" + items[i].title;
ins += "Title" + items[i].title;
ins += "</div><br />";
};
$('#results').html(ins);
}
});
});
});
</script>
html
<form class="destinations-form" role="search" >
<div class="input-line">
<input id="searchForm" type="text" class="form-input check-value" placeholder="Search Documents" />
<button type="button" class="form-submit btn btn-special" "</button>
</div>
</form>
<div class="container">
<div class="hero-text align-center">
<div id="results"></div>
</div>
</div>
json
data: [
{
collection_id: "ADGM-1552427432270-483",
metadata:{
year: "2019",
files: text ,
title: text,
},
The problem is because you only read the values from the field when the page first loads and it is empty. To fix this, move that logic inside the click handler.
The next issue is that you should remove this from $('input[type="text"]', this). You don't need a contextual selector here, and this one is incorrect regardless.
Also note that a valid querystring starts with ? and separates each value with &, so your url concatenation needs to be amended slightly. In addition you shouldn't update the url value on every click. If you do it this way your AJAX request will only work once.
Lastly the metadata in your response is an object, not an array. data is the array so you need to loop over that instead. The loop can also be simplified by using map(). Try this:
$(document).ready(function() {
const url = "https://data.edu/api/v1/metadata";
$('button[type="button"]').on('click', function(e) {
let searchstring = $('input[type="text"]').val();
let requestUrl = url + `?text=${searchstring}&title=${searchstring}`;
$.ajax({
type: 'GET',
url: requestUrl,
success: function(res) {
let html = res.data.map(item => `<div>Title ${item.metadata.title}</div><br />`);
$('#results').html(html);
}
});
});
});

JQuery find and closest Can't find closest input fields

I loop through some data dynamically via Ajax and than display them in table. As you see I have multiple row or <tr> , HeaderLine and Customerinfo. which I'm interesting in is CustomerInfo and the thing I'm trying do is when button is clicked, check which input fields is Empty or has no value than give an alert and for finding input fields or elements I used jQuery find() and closest() Method, but for some reason it can't find any elements.
Can anyone please help me to solve the issue?
JavaScript for checking Empty input fields before sending to server:
<script>
function AnmodomRMA(e) {
var tr = $(e).closest("table").find(".CustomerInfo");
var email = tr.find('input.Email').val();
var telefon = tr.find('input.Telefonnummer').val();
if (email === "") {
alert("Input is Empty:" + email);
return false;
}
if (telefon === "") {
alert("Input is Empty:" + telefon);
return false;
}
var formdata = $("select, textarea,input").serializeArray();
$.ajax({
"url": '#Url.Action("AutoRMAAnmoding", "User")',
"method": "POST",
"data": formdata,
"dataType": "json",
success: function (data) {
console.log(data);
},
error: function () {
console.log('something went wrong - debug it!');
}
});
}
</script>
JavaScript for Load Data (dynamically into table):
<div class="card-body">
<table class="table">
<tbody id="ResultProduct"></tbody>
</table>
<div id="AppendBtnRMA">
</div>
</div>
<script>
$.ajax({
type: "GET",
url: "/User/serializeItemLineByID" + 1,
dataType: 'json',
success: function (result) {
$.each(result.findclosedorders, function (ii, e) {
var guid = uuidv4();
rows += '<tr class="HeaderLine">';
rows += '<td>some data</td>';
rows += '</tr>';
rows += '<tr class="CustomerInfo">'
rows += '<input type="hidden" name="model.InsertRMALists.Index" value="' + guid + '" />';
rows += '<td><label>Telefonnummer</label><input name="model.InsertRMALists[' + guid + '].Telefonnummer" id="Telefonnummer" type="tel"></td>';
rows += '<td><label>E-mail</label><input name="model.InsertRMALists[' + guid + '].Email" id="Email" type="text"></td>';
rows += '</tr>';
});
var btnAppend = "";
btnAppend += '<button onclick="AnmodomRMA(this);">Create RMA</button>';
$("#AppendBtnRMA").append(btnAppend);
$("#ResultProduct").append(rows);
},
})
</script>
Thanks for all help :)
Here is how did i solve the problems:
- Add a class to input fields.
- beacuse button it was out side the table, i have to select closest element around table and than find <tr> like:
var tr = $(e).closest(".card-body").find("tr.section");
and than loop through that element i want to check if it is Empty:
$(tr).each(function (i, el) {
var t = $(el).find('input.Telefonnummer').val();
if (t ==="") {
alert("empty");
}
});
In the function AnmodomRMA(e) e refers to the event itself and not the clicked button, try to use e.target:
var tr = $(e.target).closest("tr");

After Ajax call succeed, DataTables search box doesn't work

I'm working on a project that php, js, jquery, datatables are included.
I'm sending post call to a PHP page to change my table data, it's running successfully as you see. After this call, I can't use my DataTable search feature strangely. May be the error is about $(".gunlukgelir").load(" .gunlukgelir"); when Ajax call is succeed, I reflesh the tables with the .gunlukgelir class name.
Libraries:
https://cdn.datatables.net/1.10.16/css/dataTables.bootstrap.min.css
https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js
https://cdn.datatables.net/1.10.16/js/dataTables.bootstrap.min.js
https://code.jquery.com/jquery-3.3.1.min.js
my Ajax call:
$(function() {
$("#gelirgetir").click(function() {
var gelirtablosecimi = $("#select1").val();
if (gelirtablosecimi) {
$.ajax({
type: "POST",
url: "tabloyenile.php",
data: {
"gelirtablosecimi": gelirtablosecimi
},
success: function(result) {
$(".gunlukgelir").load(" .gunlukgelir");
//$(".gunlukgelir").load(window.location + " .gunlukgelir");
notifyUser('success', 'Başarılı!', 'Tablo başarıyla güncellendi');
},
error: function(result) {
notifyUser('error', 'Hata', 'error');
}
});
} else {
notifyUser('info', 'Dikkat', 'Tablo seçimi yapmadınız!');
}
});
HTML part:
<div class="form-group col-xs-6">
<select id="select1" class="selectpicker" data-live-search="true" title="Gelirler">
<?php echo $geliroptions;?>
</select>
<input type="submit" id="gelirgetir" value="Getir" class="btn btn-success" />
<h1>Aylık Gelir Raporları</h1>
<table id="" class="display table table-stripe table-hover table-row-border table-order-column table-nowrap gunlukgelir">
<thead>
<tr>
<th>Tarih</th>
<th>Günlük Toplam</th>
</tr>
</thead>
<?php
$gelirtabloadi = $_SESSION["gelirtabloadi"];
$gelirgunluktoplam = $db->prepare("select tarih, hasilat + visa + butce_ici + hisse_satis + sosyal_konut + elektrik + haberlesme + iller_bank + diger AS Toplam from $gelirtabloadi");
$gelirgunluktoplam->execute();
while($row = $gelirgunluktoplam->fetch()){
echo '
<tr>
<td>'.$row["tarih"].'</td>
<td>'.$row["Toplam"].'</td>
</tr>
';
}
?>
</table>
</div>
and PHP that Ajax calls:
<?php
session_start();
if($_POST['gelirtablosecimi'] && $_POST['gidertablosecimi']){
$gidertabloadi = $_POST["gidertablosecimi"];
$gelirtabloadi = $_POST["gelirtablosecimi"];
$_SESSION["gelirtabloadi"] = $gelirtabloadi;
$_SESSION["gidertabloadi"] = $gidertabloadi;
}
if($_POST["gelirtablosecimi"]){
$gelirtabloadi = $_POST["gelirtablosecimi"];
$_SESSION["gelirtabloadi"] = $gelirtabloadi;
}
if($_POST['gidertablosecimi']){
$gidertabloadi = $_POST["gidertablosecimi"];
$_SESSION["gidertabloadi"] = $gidertabloadi;
}
?>
Any suggestion? Thanks in advance!
I also had such a problem. Just add .DataTable() in success function of ajax after assigning the data to data table.
It has been working for me.
Just write it as follows:
function TaxLoad() {
$.ajax({
url:"myCode.php",
type:"POST",
data:{functionName:"showTax"},
success:function(data) {
$("#tblTaxBody").html(data);
var table= $("#dtTable").DataTable();
}
});
}`
Probably this issue related with my problem in the Docs. If It reinitialised, it would be searching: false Anyway, If one day anybody sees this problem, just change your table choice to Bootstrap-Table. It's much more stable.

Send Array from HTML table to Php Array with javascript?

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.

How to get the data from ajax in controller codeigniter

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.

Categories

Resources