how to get html table data to an Array? - javascript

I am using PHP Codeigniter.I don't have good knowledge in JavaScript. My problem is that I have a table with editable columns and when I click on the submit button I want to send the table data to the Codeigniter function using POST method.
HTML code
<div class="col-md-12 top-20 padding-0">
<div class="col-md-12">
<div class="panel">
<div class="panel-heading"><h3>Data Tables</h3></div>
<div class="panel-body">
<div class="responsive-table">
<table id="data_table" class="table table-striped table-bordered" width="100%" cellspacing="0">
<tr>
<th>Name</th>
<th>Country</th>
<th>Age</th>
<th>Action</th>
</tr>
<tr>
<td><input type="text" id="new_name"></td>
<td><input type="text" id="new_country"></td>
<td><input type="text" id="new_age"></td>
<td><input type="button" class="add" onclick="add_row();" value="Add Row"></td>
</tr>
</table>
<input type="button" name="check" onclick="clik();">
</div>
</div>
</div>
</div>
</div>
JavaScript for editable table
function edit_row(no)
{
document.getElementById("edit_button"+no).style.display="none";
document.getElementById("save_button"+no).style.display="block";
var name=document.getElementById("name_row"+no);
var country=document.getElementById("country_row"+no);
var age=document.getElementById("age_row"+no);
var name_data=name.innerHTML;
var country_data=country.innerHTML;
var age_data=age.innerHTML;
name.innerHTML="<input type='text' id='name_text"+no+"' value='"+name_data+"'>";
country.innerHTML="<input type='text' id='country_text"+no+"' value='"+country_data+"'>";
age.innerHTML="<input type='text' id='age_text"+no+"' value='"+age_data+"'>";
}
function save_row(no)
{
var name_val=document.getElementById("name_text"+no).value;
var country_val=document.getElementById("country_text"+no).value;
var age_val=document.getElementById("age_text"+no).value;
document.getElementById("name_row"+no).innerHTML=name_val;
document.getElementById("country_row"+no).innerHTML=country_val;
document.getElementById("age_row"+no).innerHTML=age_val;
document.getElementById("edit_button"+no).style.display="block";
document.getElementById("save_button"+no).style.display="none";
}
function delete_row(no)
{
document.getElementById("row"+no+"").outerHTML="";
}
function add_row()
{
var new_name=document.getElementById("new_name").value;
var new_country=document.getElementById("new_country").value;
var new_age=document.getElementById("new_age").value;
var table=document.getElementById("data_table");
var table_len=(table.rows.length)-1;
var row = table.insertRow(table_len).outerHTML="<tr id='row"+table_len+"'><td id='name_row"+table_len+"'>"+new_name+"</td><td id='country_row"+table_len+"'>"+new_country+"</td><td id='age_row"+table_len+"'>"+new_age+"</td><td><input type='button' id='edit_button"+table_len+"' value='Edit' class='edit' onclick='edit_row("+table_len+")'> <input type='button' id='save_button"+table_len+"' value='Save' class='save' onclick='save_row("+table_len+")'> <input type='button' value='Delete' class='delete' onclick='delete_row("+table_len+")'></td></tr>";
document.getElementById("new_name").value="";
document.getElementById("new_country").value="";
document.getElementById("new_age").value="";
}
So in the given editable table data I want to push to my codeigniter function.

the best way now is to use Ajax in order to post those javascript value to the Codeigniter function
example on a simple ajax call :
var newName = 'John Smith';
$.ajax('myservice/codigniter_Function?' + $.param({id: 'some-unique-id'}), {
method: 'POST',
data: {
name: newName
}
})
.then(
function success(name) {
if (name !== newName) {
alert('Something went wrong. Name is now ' + name);
}
},
function fail(data, status) {
alert('Request failed. Returned status of ' + status);
}
);
please check the source for more information on how to use ajax with javascript in details.

Since your question includes vanilla Javascript, my answer will use XMLHttpRequest(). I have created the following function to send post data to the back end.
function ajax_req(url, params) {
var http = new XMLHttpRequest();
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function () {
if (http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
}
In your save_row() function, create parameters to send to the back end, like name=billy&age=21&country=us
function save_row(no) {
var name_val = document.getElementById("name_text" + no).value;
var country_val = document.getElementById("country_text" + no).value;
var age_val = document.getElementById("age_text" + no).value;
document.getElementById("name_row" + no).innerHTML = name_val;
document.getElementById("country_row" + no).innerHTML = country_val;
document.getElementById("age_row" + no).innerHTML = age_val;
document.getElementById("edit_button" + no).style.display = "block";
document.getElementById("save_button" + no).style.display = "none";
// send values to back end
var params = "name=" + name_val + "&country=" + country_val + "&age=" + age_val;
ajax_req('/savedata', params);
}

<form action="<php echo base_url('controller_name/ method_name')?>
method="POST">
<div class="col-md-12 top-20 padding-0">
<div class="col-md-12">
<div class="panel">
<div class="panel-heading"><h3>Data Tables</h3></div>
<div class="panel-body">
<div class="responsive-table">
<table id="data_table" class="table table-striped table-bordered" width="100%" cellspacing="0">
<tr>
<th>Name</th>
<th>Country</th>
<th>Age</th>
<th>Action</th>
</tr>
<tr>
<td><input type="text" id="new_name" name="newname"></td>
<td><input type="text" id="new_country" name="country"></td>
<td><input type="text" id="new_age" name="age"></td>
</tr>
</table>
<input type="submit" name="check" class="btn btn-primary">
</div>
</div>
</div>
</div>
In Your Controller
public function function_name()
{
$post = $this>input->post();
$data = array(
'name' =>$post['newname'],
'country' =>$post['country'],
'age' =>$post['age'],
);
$this->load->model('model_name');
$this->model_name->function_name($data);
}
In your model
public function function_name($data)
{
return $this->db->insert('table_name', $data);
}

Related

My validation does not work on added rows and autonumbering

I have a function where i can add rows and autonumbering. The add rows works when you click the "add row" button, and auto numbering works when you press Ctrl+Enter key when there's 2 or more rows. My problem is, my validation does not work on my autonumbering.
For example: when I type manually the "1" on the textbox, it works.
But when I do my auto numbering, "Not good" does not appear on my 2nd
textbox.
Is there anything I missed? Any help will be appreciated.
//this is for adding rows
$("#addrow").on('click', function() {
let rowIndex = $('.auto_num').length + 1;
let rowIndexx = $('.auto_num').length + 1;
var newRow = '<tr><td><input class="auto_num" type="text" name="entryCount" value="' + rowIndexx + '" /></td>"' +
'<td><input name="lightBand' + rowIndex + '" value="" class="form" type="number" /> <span class="email_result"></span></td>"' +
'<td><input type="button" class="removerow" id="removerow' + rowIndex + '" name="removerow' + rowIndex + '" value="Remove"/></td>';
$("#applicanttable > tbody > tr:last").after(newRow);
});
//this is for my validation
$(document).on('change', 'input[name*=lightBand]', function() {
var lightBand1 = $(this).val(); //get value
var selector = $(this) //save slector
selector.next('.email_result').html("") //empty previous error
if (lightBand1 != '') {
/*$.ajax({
url: "<?php echo base_url(); ?>participant/check_number_avalibility",
method: "POST",
data: {
lightBand1: lightBand1
},
success: function(data) {*/
selector.next('.email_result').html("NOT GOOD"); //use next here ..
/* }
});*/
}
});
// this is for autonumbering when ctrl+enter is pressed.
const inputs = document.querySelectorAll(".form");
document.querySelectorAll(".form")[0].addEventListener("keyup", e => {
const inputs = document.querySelectorAll(".form");
let value = parseInt(e.target.value);
if ((e.ctrlKey || e.metaKey) && (e.keyCode == 13 || e.keyCode == 10)) {
inputs.forEach((inp, i) => {
if (i !== 0) {
inp.value = ++value;
}
})
}
});
Add a row and type any number at number textbox column and press ctrl+enter. You'll see the "Not good" is not working on added rows. It'll only work if you enter the number manually per row.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<table class="table table-bordered" border="1" id="applicanttable">
<thead>
<tr>
</tr>
</thead>
<tbody>
<div class="row">
<tr>
<th>#</th>
<th>Number</th>
<th>Action</th>
</tr>
<tr id="row_0">
<td>
<input id="#" name="#" class="auto_num" type="text" value="1" readonly />
</td>
<td class="labelcell">
<input value="" class="form" name="lightBand1" placeholder="" id="lightBand1" />
<span class="email_result"></span>
</td>
<td class="labelcell">
<input type="button" class="removerow" id="removerow0" name="removerow0" value="Remove">
</td>
</tr>
</div>
</tbody>
<tfoot>
<tr>
</tr>
<tr>
<button type="button" id="addrow" style="margin-bottom: 1%;">Add Row</button>
</tr>
</tfoot>
</table>
You can call your event handler i.e : change whenever you change your input values by auto numbering . So , use $(this).trigger("change") where this refer to input where value is changed .
Demo Code :
$("#addrow").on('click', function() {
let rowIndex = $('.auto_num').length + 1;
let rowIndexx = $('.auto_num').length + 1;
var newRow = '<tr><td><input class="auto_num" type="text" name="entryCount" value="' + rowIndexx + '" /></td>"' +
'<td><input name="lightBand' + rowIndex + '" value="" class="form" type="number" /> <span class="email_result"></span></td>"' +
'<td><input type="button" class="removerow" id="removerow' + rowIndex + '" name="removerow' + rowIndex + '" value="Remove"/></td>';
$("#applicanttable > tbody > tr:last").after(newRow);
});
//this is for my validation
$(document).on('change', 'input[name*=lightBand]', function() {
var lightBand1 = $(this).val(); //get value
var selector = $(this) //save slector
selector.next('.email_result').html("") //empty previous error
if (lightBand1 != '') {
/*$.ajax({
url: "<?php echo base_url(); ?>participant/check_number_avalibility",
method: "POST",
data: {
lightBand1: lightBand1
},
success: function(data) {*/
selector.next('.email_result').html("NOT GOOD"); //use next here ..
/* }
});*/
}
});
// this is for autonumbering when ctrl+enter is pressed.
$(document).on('keyup', '.form', function(e) {
let value = parseInt(e.target.value);
if ((e.ctrlKey || e.metaKey) && (e.keyCode == 13 || e.keyCode == 10)) {
//loop through all values...
$(".form").each(function(i) {
if (i !== 0) {
$(this).val(++value); //assign new value..
$(this).trigger("change") //call your change event to handle further...
}
})
}
})
Add a row and type any number at number textbox column and press ctrl+enter. You'll see the "Not good" is not working on added rows. It'll only work if you enter the number manually per row.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<table class="table table-bordered" border="1" id="applicanttable">
<thead>
<tr>
</tr>
</thead>
<tbody>
<div class="row">
<tr>
<th>#</th>
<th>Number</th>
<th>Action</th>
</tr>
<tr id="row_0">
<td>
<input id="#" name="#" class="auto_num" type="text" value="1" readonly />
</td>
<td class="labelcell">
<input value="" class="form" name="lightBand1" placeholder="" id="lightBand1" />
<span class="email_result"></span>
</td>
<td class="labelcell">
<input type="button" class="removerow" id="removerow0" name="removerow0" value="Remove">
</td>
</tr>
</div>
</tbody>
<tfoot>
<tr>
</tr>
<tr>
<button type="button" id="addrow" style="margin-bottom: 1%;">Add Row</button>
</tr>
</tfoot>
</table>

I want to add new data from second table to main table

I want to add new data to the main table using the checkbox option, but the data added is not the same as the selected data. this is my code ...
<table border="1" id="table2">
<tr>
<td>Raka</td>
<input type="hidden" id="fname" value="Raka">
<td>Gilbert</td>
<input type="hidden" id="lname" value="Gilbert">
<td><input type="checkbox" name="chk"></td>
</tr>
<tr>
<td>Achyar</td>
<input type="hidden" id="fname" value="Achyar">
<td>Lucas</td>
<input type="hidden" id="lname" value="Lucas">
<td><input type="checkbox" name="chk"></td>
</tr>
</table>
<script>
$(document).on('click', '#Add', function() {
$("table").find('input[name="chk"]').each(function(){
if($(this).is(":checked")){
var fname = $('#fname').val();
var lname = $('#lname').val();
var newData = '<tr>'+
'<td>'+fname+'</td>'+
'<td>'+lname+'</td>'+
'<tr>';
$('table').append(newData);
}
});
})
</script>
You need to change your id="fname" to class="fname" and get the input value closest to checkbox. Currently you are getting data from the first inputs as they have the same id's.
function valueExists(value) {
if (!value) {
return true;
}
let exists = false;
$("#main-table").find('tr').each(function() {
let fname = $(this).find("td:nth-child(1)").text(),
lname = $(this).find("td:nth-child(2)").text();
const fullName = `${fname}${lname}`;
if (value.toLowerCase() === fullName.toLowerCase()) {
exists = true;
}
});
return exists;
}
$(document).on('click', '#add', function() {
$("table").find('input[name="chk"]').each(function(e) {
if ($(this).is(":checked")) {
var fname = $(this).parents('tr').find('.fname').val();
var lname = $(this).parents('tr').find('.lname').val();
if (valueExists(`${fname}${lname}`)) return;
var newData = '<tr>' +
'<td>' + fname + '</td>' +
'<td>' + lname + '</td>' +
'<tr>';
$('#main-table').append(newData);
}
});
})
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Main Table</h1>
<table class="table table-dark" border="1" id="main-table">
</table>
<hr>
<h1>Second table</h1>
<table border="1" id="table2">
<tr>
<td class="name">Raka</td>
<input type="hidden" class="fname" value="Raka">
<td class="last">Gilbert</td>
<input type="hidden" class="lname" value="Gilbert">
<td><input class="check" type="checkbox" name="chk"></td>
</tr>
<tr>
<td class="name">Achyar</td>
<input type="hidden" class="fname" value="Achyar">
<td class="last">Lucas</td>
<input type="hidden" class="lname" value="Lucas">
<td><input class="check" type="checkbox" name="chk"></td>
</tr>
</table>
<button type="button" id="add" name="button">Add</button>
Try this. I have used plain javascript
document.addEventListener("click", function() {
[...document.querySelectorAll("input[name='chk']")].forEach(data => {
console.log(data);
if (data.checked) {
const fname = document.getElementById("fname").value;
const lname = document.getElementById("lname").value;
const newData = `<tr><td>${ fname }</td><td>${ lname }</td</tr>`;
// "<tr>" + "<td>" + fname + "</td>" + "<td>" + lname + "</td>" + "<tr>";
document.getElementById("table2").innerHTML += newData;
}
});
});
Hope was useful. If any flaws please update
Here is a neater solution, using 2 tables as requested, without hidden inputs and a better use of 'tables' and 'trs' in jquery
$(function(){
$("#btnAdd").click(function(){
let table1 = $("#table1");
table2 = $("#table2");
$.each(table2.find('tr'), function(i, tr){
tr = $(tr);
let new_tr = $('<tr>');
if (tr.find("td input").is(":checked")) {
let fname = tr.find("td:nth-child(1)").html(),
lname = tr.find("td:nth-child(2)").html();
new_tr.append(
'<td>' + fname + '</td>' +
'<td>' + lname + '</td>' +
'<td><input type="checkbox" name="chk"></td>'
);
table1.append(new_tr)
}
})
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
TABLE 1
<table border="1" id="table1">
</table>
<hr/>
TABLE 2
<table border="1" id="table2">
<tr>
<td>Raka</td>
<td>Gilbert</td>
<td><input type="checkbox" name="chk"></td>
</tr>
<tr>
<td>Achyar</td>
<td>Lucas</td>
<td><input type="checkbox" name="chk"></td>
</tr>
</table>
<button type="button" id="btnAdd">Add</button>

How to find the closest table row using jQuery?

I have problem getting the value of the replace new table row, I will let you show the codes for the replacing new table row.
The is the Table B, Where this code use for replacing new table row to the Table A
$('#edit_chainingBuild').on('click','tr.clickable-row',function(e){
$('table#edit_chainingBuild tr').removeClass('selected');
$(this).addClass('selected');
var find_each_id_will_update = $(this).find('.data-attribute-chain-id').attr('data-attribute-chain-id');
$('.id_to_update_chain').val(find_each_id_will_update);
var find_each_id_condiments = $(this).find('.data-attribute-chain-id').attr('data-attribute-condiments-section-id');
$.ajax({
url:'/get_each_id_section_condiments',
type:'get',
data:{find_each_id_condiments:find_each_id_condiments},
success:function(response){
var get_each_section = response[0].condiments_table;
$.each(get_each_section, function (index, el) {
var stringify = jQuery.parseJSON(JSON.stringify(el));
var cat_condi_screen_name = stringify['cat_condi_screen_name'];
var cat_condi_price = stringify['cat_condi_price'];
var cat_condi_image = stringify['cat_condi_image'];
var condiment_section_name = stringify['condiment_section_name'];
var image = '<img src=/storage/' + cat_condi_image + ' class="responsive-img" style="width:100px;">';
// $('#edit_chainingBuild').append("<tr class='clickable-row'><td>" + Qty + "</td><td class='clickable-row-condiments'>" + Condiments + "</td><td>" + Price + "</td><td style='display:none;' data-attribute-chain-id="+menu_builder_details_id +" class='data-attribute-chain-id'>"+menu_builder_details_id+"</td></tr>");
$('table#edit_table_chaining_condiments').append("<tr class='edit_condimentsClicked' style='font-size:14px; border:none;'><td>"+condiment_section_name +"</td><td class='edit_condimentsScreenNameClicked'>" + cat_condi_screen_name + "</td><td class='edit_condimentsScreenPriced'>" + cat_condi_price + "</td><td>"+image+"</td></tr>");
});
$("table#edit_table_chaining_condiments tr").click(function(e){
var tableBhtml = $(this).closest('tr').html();
var condiments_name = $(this).closest("tr").find(".edit_condimentsScreenNameClicked").text();
var condimentsScreenPriced = $(this).closest("tr").find(".edit_condimentsScreenPriced").text();
// var input = '<input type="number" id="qty" name="qty" class="form-control changeQuantity" value="1" min="1">';
var id_to_edit_build = $('.id_to_update_chain').val();
$("#edit_chainingBuild tr.selected").html('');
var id_to_edit_builders = $('.id_to_update_chain').val();
$("#edit_chainingBuild tr.selected").replaceWith("<tr data-attribute-chain-id=" + id_to_edit_build + " class='clickable-row'><td class='new_condiments_name'>"+condiments_name+"</td><td>"+condimentsScreenPriced+"</td><td style='display:none;' data-attribute-chain-id="+id_to_edit_builders +" class='data-attribute-chain-id'>"+id_to_edit_builders+"</td></tr>");
$('#EditcondimentsBuilderModal').modal('hide');
});
},
error:function(response){
console.log(response);
}
});
$('#EditcondimentsBuilderModal').modal('show');
});
Looking forward if the table row already replace, I want to get the value of the class of new_condiments_name. So I create a variable to find the class of new_condiments_name. It look like this.
var new_condiments_name = $(this).closest("tr").find(".new_condiments_name").text();
So now when I try alert the variable new_condiments_name using the click function it shows null only.
$('.edit_build_success_insert').click(function(){
var new_condiments_name = $(this).closest("tr").find(".new_condiments_name").text();
alert(new_condiments_name);
});
My Html Table:
<div class="modal-body">
<div class="container">
<div class="header" style="text-align: center;">
<br>
<h3 style="color:#007BFF;">Build Your Chain Button</h3>
<label>This button will be served as customers menu.</label><br>
<i class="fab fa-creative-commons-remix" style="font-size:70px;"></i>
<br><br>
<input type="hidden" value="" class="edit_hidden_noun_id" name="">
<table class="table table-hover" id="edit_chainingBuild">
<thead>
<tr style="font-size: 15px;">
<!-- <th scope="col">Qty</th> -->
<th scope="col">Condiments</th>
<th scope="col">Price</th>
</tr>
</thead>
<tbody style="font-size:14px;">
</tbody>
</table>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="edit_build_success_insert btn btn-primary">Build Done</button>
</div>
I have here the image to proof that the value that i get always null.
$('table .edit_build_success_insert').click(function(){
var new_condiments_name = $(this).closest("tr").find(".new_condiments_name").text();
alert(new_condiments_name);
});

Javascript CRUD

My problem is that the edit function will display undefined in input field but in my console it displays the img url..
Can you please correct my script why it displays undefined
This is my js code, where I created 3 function,the , and
my.js
function delete_row(no)
{
document.getElementById("row"+no+"").outerHTML="";
}
function add_row(){
var new_image=document.getElementById("new_image").value;
var new_title=document.getElementById("new_title").value;
var new_description=document.getElementById("new_description").value;
if (new_image&&new_title&&new_description != "") {
var table=document.getElementById("data_table");
var table_len=(table.rows.length)-1;
var row = table.insertRow(table_len).outerHTML=
"<div id='row"+table_len+"'><img id='image_row"+table_len+"' src = "+new_image+"><div id='title_row"+table_len+"'>"+new_title+
"</div><div id='description_row"+table_len+"'>"+new_description+"</div><div><input type='button' value='Delete' class='delete' onclick='delete_row("+table_len+")'><input type='button' value='Edit' class='edit' onclick='edit_row("+table_len+")'></div></div>";
document.getElementById("new_image").value="";
document.getElementById("new_title").value="";
document.getElementById("new_description").value="";
}
}
function edit_row(no){
var image=document.getElementById("image_row"+no).getAttribute("src");
console.log(image);
var title=document.getElementById("title_row"+no);
console.log(title);
var description=document.getElementById("description_row"+no);
console.log(description);
var image_data = image.innerHTML;
var title_data = title.innerHTML;
var description_data =description.innerHTML;
document.getElementById("new_image").value=image_data;
document.getElementById("new_title").value=title_data;
document.getElementById("new_description").value=description_data;
}
This part is my html code, why I only have div and tables
index.html
<div id="wrapper">
<h1 align="center">My Todo App</h1>
<div id="container">
<form id="myForm">
<table align='center' cellspacing=2 cellpadding=5>
<tr>
<th>Image Link</th>
<th>Title</th>
<th>Description</th>
</tr>
<tr>
<td><input type="text" id="new_image"></td>
<td><input type="text" id="new_title"></td>
<td><input type="text" id="new_description"></td>
<td><input type="button" class="add" onclick="add_row();" value="SAVE"></td>
</tr>
</table>
</form>
</div>
<div id="content_container">
<div>
<table align='center' cellspacing=2 cellpadding=5 id="data_table">
</table>
</div>
</div>
</div>
and also how to append the new edited data when clicking the save button, in my case it will add another row.
Remove image.innerHTML inside function edit_row(no)
Added new function as per your question
function delete_row(no)
{
document.getElementById("row"+no+"").outerHTML="";
}
function add_row(){
var new_image=document.getElementById("new_image").value;
var new_title=document.getElementById("new_title").value;
var new_description=document.getElementById("new_description").value;
if (new_image&&new_title&&new_description != "") {
var table=document.getElementById("data_table");
var table_len=(table.rows.length)-1;
var row = table.insertRow(table_len).outerHTML=
"<div class='myrow'><div id='row"+table_len+"'><img id='image_row"+table_len+"' src = "+new_image+"><div id='title_row"+table_len+"' class='titleData'>"+new_title+
"</div><div class='descData' id='description_row"+table_len+"'>"+new_description+"</div><div><input type='button' value='Delete' class='delete' onclick='delete_row("+table_len+")'><input type='button' value='Edit' class='edit' onclick='edit_row("+table_len+",this)'></div></div></div>";
document.getElementById("new_image").value="";
document.getElementById("new_title").value="";
document.getElementById("new_description").value="";
}
}
function edit_row(no,ref){
ref.value="Save";
ref.removeAttribute("onclick");
var image=document.getElementById("image_row"+no).getAttribute("src");
console.log(image);
var title=document.getElementById("title_row"+no);
console.log(title);
var description=document.getElementById("description_row"+no);
console.log(description);
var image_data = image; // remove image.innerHTML
var title_data = title.innerHTML;
var description_data =description.innerHTML;
document.getElementById("new_image").value=image_data;
document.getElementById("new_title").value=title_data;
document.getElementById("new_description").value=description_data;
ref.setAttribute("onclick","saveEdit(this,'"+no+"')");
}
function saveEdit(ref,no)
{
var new_image=document.getElementById("new_image").value;
var new_title=document.getElementById("new_title").value;
var new_description=document.getElementById("new_description").value;
var parent= (ref.parentElement).parentElement;
var img=parent.firstChild.setAttribute("src",new_image);
var list = document.getElementById(parent.id);
var title=list.getElementsByClassName("titleData")[0];
var desc=list.getElementsByClassName("descData")[0];
title.innerHTML=new_title;
desc.innerHTML=new_description;
ref.value="Edit";
ref.removeAttribute("onclick");
ref.setAttribute("onclick","edit_row("+no+",this)");
document.getElementById("new_image").value="";
document.getElementById("new_title").value="";
document.getElementById("new_description").value="";
}
<div id="wrapper">
<h1 align="center">My Todo App</h1>
<div id="container">
<form id="myForm">
<table align='center' cellspacing=2 cellpadding=5>
<tr>
<th>Image Link</th>
<th>Title</th>
<th>Description</th>
</tr>
<tr>
<td><input type="text" id="new_image"></td>
<td><input type="text" id="new_title"></td>
<td><input type="text" id="new_description"></td>
<td><input type="button" class="add" onclick="add_row();" value="SAVE"></td>
</tr>
</table>
</form>
</div>
<div id="content_container">
<div>
<table align='center' cellspacing=2 cellpadding=5 id="data_table">
</table>
</div>
</div>
</div>

ajax, php how to save correctly data

I tried to send information via ajax about user_question and language input fields, but how to write correctly this element inside ajax javascript to save the table element value in database.
thank you.
the script element.
<table id="myTable" class="table table-sm table-hover order-list">
<thead>
<tr>
<td>User Question</td>
<td>Language</td>
</tr>
</thead>
<tbody>
<tr>
<td class="col-md-9">' . HTML::inputField('user_question', null, 'placeholder="Write a short answer"'). '</td>
<td class="col-md-2">' . HTML::inputField('language', null, 'placeholder="Language"') . '</td>
<td class="col-sm-1"><a id="delete_row" class="deleteRow"></a></td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="5">
<input type="button" class="btn btn-lg btn-block " id="addrow" value="Add Row" />
</td>
</tr>
<tr></tr>
</tfoot>
</table>
<script>
$(document).ready(function () {
var counter = 0;
$("#addrow").on("click", function () {
var newRow = $("<tr>");
var cols = "";
cols += '<td><input type="text" class="form-control" name="user_question' + counter + '"/></td>';
cols += '<td><input type="text" class="form-control" name="language' + counter + '"/></td>';
cols += '<td><input type="button" class="ibtnDel btn btn-md btn-danger " value="Delete"></td>';
newRow.append(cols);
$("table.order-list").append(newRow);
counter++;
// element pb
// var data = $("#new_product").serialize(); // form id or table id ?
var dataString = 'user_question='+user_question+'language='+language;
$.ajax({
type: 'POST',
url: '{$ajax_url}',
data : dataString,
success: function(data) {
alert(data);
$("p").text(data);
}
});
$("table.order-list").on("click", ".ibtnDel", function (event) {
$(this).closest("tr").remove();
counter -= 1
});
});
</script>
Use like this to get php variables value inside javascript in .php page
url: "<?php echo $ajax_url; ?>",
Also use & and symbol to add two or more param in your dataString

Categories

Resources