send checkbox data along with table data using jQuery and AJAX - javascript

The following is an inline insert using HTML5 table data to a database table using jQuery and AJAX. I would like to also send a checkbox data along with this table data, how can I achieve that ?
<div id="add-product">
<div class="txt-heading">Add Product</div>
<table cellpadding="10" cellspacing="1">
<tbody>
<tr>
<th><strong>Name</strong></th>
<th><strong>Code</strong></th>
<th><strong>Description</strong></th>
<th style="text-align:right;"><strong>Price</strong></th>
</tr>
<tr><form name="myform"><input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue2" /></form>
<td contentEditable="true" data-id="product_name"></td>
<td contentEditable="true" data-id="product_code"></td>
<td contentEditable="true" data-id="product_desc"></td>
<td contentEditable="true" data-id="product_price" style="text-align:right;"></td>
</tr>
</tbody>
</table>
<div id="btnSaveAction">Save to Database</div>
</div>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script>
$("#btnSaveAction").on("click",function(){
params = ""
$("td[contentEditable='true']").each(function(){
if($(this).text() != "") {
if(params != "") {
params += "&";
}
params += $(this).data('id')+"="+$(this).text();
}
});
if(params!="") {
$.ajax({
url: "insert-row.html",
type: "POST",
data:params,
success: function(response){
$("#ajax-response").append(response);
$("td[contentEditable='true']").text("");
}
});
}
});
</script>
code is from here

I mentioned using a FormData object to gather together all the data that you want to send so the following is an example using vanilla Javasript that does just that.
The form must be either entirely within a single table-cell or the entire table must be wholly contained within the form for the markup to be valid - hence the form below, with several checkboxes to illustrate the point, contains the table with the contentEditable cells.
Any/All checkboxes that are ticked will appear in the POST array - any that remain unticked are ignored. The set method of the FormData api takes two parameters - a name and value pair. ( a third value is possible if you wish to supply a filename, for an upload for instance )
I appreciate that the question says jQuery but my efforts with that resulted in errors that I knew not how to resolve - hence vanilla JS. The FormData object can be used with jQuery quite happily though I believe.
const d=document;
d.querySelector('button[name="save"]').addEventListener('click', e=>{
// create the FormData object bound to the `form`
let fd = new FormData( document.forms.myform );
let col=d.querySelectorAll('td[contentEditable="true"]');
// add all the contentEditable text to the FormData object
col.forEach(n=>fd.set(n.dataset.id, n.textContent));
// send the http request
fetch('insert-row.html', { method:'post', body:fd })
.then( r=>r.text() )
.then( text=>{
d.getElementById('ajax-response').insertAdjacentHTML('beforeend',text);
col.forEach(n=>n.textContent='')
})
.catch(e=>console.log(e))
});
body,body *{
font-family:monospace;
font-size:1rem
}
table{
width:90%;
border:1px solid grey;
margin:1rem;
}
tr th:nth-of-type(4),
tr td[contentEditable='true']:nth-of-type(4){
text-align:right;
}
tr,td{margin:0.1rem;}
td,th{
padding:0.25rem;
border:1px solid grey
}
[contentEditable]:focus{background:rgba(0,255,0,0.25)}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="add-product">
<div class="txt-heading">Add Product</div>
<form name="myform">
<input type="checkbox" name="myCheckboxes[]" value="someValue - 1" />1
<input type="checkbox" name="myCheckboxes[]" value="someValue - 2" />2
<input type="checkbox" name="myCheckboxes[]" value="someValue - 3" />3
<input type="checkbox" name="myCheckboxes[]" value="someValue - 4" />4
<input type="checkbox" name="myCheckboxes[]" value="someValue - 5" />5
<input type="checkbox" name="myCheckboxes[]" value="someValue - 6" />6
<table cellpadding="10" cellspacing="1">
<tbody>
<tr>
<th><strong>Name</strong></th>
<th><strong>Code</strong></th>
<th><strong>Description</strong></th>
<th><strong>Price</strong></th>
</tr>
<tr>
<td contentEditable="true" data-id="product_name"></td>
<td contentEditable="true" data-id="product_code"></td>
<td contentEditable="true" data-id="product_desc"></td>
<td contentEditable="true" data-id="product_price"></td>
</tr>
</tbody>
</table>
</form>
<button name='save' type='button'>Save to Database</button>
</div>
<div id='ajax-response'></div>

The solution may be this...
If I understood correctly what you were asking.
<div id="add-product">
<div class="txt-heading">Add Product</div>
<table cellpadding="10" cellspacing="1">
<tbody>
<tr>
<th><strong>Name</strong></th>
<th><strong>Code</strong></th>
<th><strong>Description</strong></th>
<th style="text-align:right;"><strong>Price</strong></th>
</tr>
<tr><form name="myform"><input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue2" /></form>
<td contentEditable="true" data-id="product_name"></td>
<td contentEditable="true" data-id="product_code"></td>
<td contentEditable="true" data-id="product_desc"></td>
<td contentEditable="true" data-id="product_price" style="text-align:right;"></td>
<td><input type="checkbox" id="product_xxxx" name="product_xxxx" value="yes"></td>
</tr>
</tbody>
</table>
<div id="btnSaveAction">Save to Database</div>
</div>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script>
$("#btnSaveAction").on("click",function(){
params = ""
$("td[contentEditable='true']").each(function(){
if($(this).text() != "") {
if(params != "") {
params += "&";
}
params += $(this).data('id')+"="+$(this).text();
}
});
// For each checkbox whose name begins with 'product_'
$("[type=checkbox][name^='product_']").each(function(){
// If Checkbox Checked
if($(this).prop('checked')) params += $(this).attr('id')+"="+$(this).val();
});
// End - For each checkbox whose name begins with 'product_'
if(params!="") {
$.ajax({
url: "insert-row.html",
type: "POST",
data:params,
success: function(response){
$("#ajax-response").append(response);
$("td[contentEditable='true']").text("");
}
});
}
});
</script>

Related

How do I display data back from a javascript calling a php function?

I'm using a MVC framework and in my view I have my javascript code
this is in my view:
<script>
$(document).ready(function(){
$(document).on('click','#filtr',function(){
var id_val = $('#id_val').val();
var key_val= $('#key_val').val();
console.log(id_val);
console.log(key_val);
$.ajax({
url:"<?php echo base_url()?>filter/filtr",
method:"POST",
data:{
id_val:id_val,
key_val:key_val
},
/*beforeSend:function(){
$("container_tab").html("Searching...");
},*/
success:function(data){
$("container_tab").html(data);
}
})
});
});
</script>
<div class="table-responsive">
<table class="table table-striped table-hover" id="dataTables-example">
<tr>
<td>
Filter by...
</td>
<td>
ID: <input type="text" id="id_val" name="id_val" value="3" />
</td>
<td>
KEY: <input type="text" id="key_val" name="key_val" value="asdf12" />
</td>
<td>
<button type="button" class="btn btn-info btn-sm" id="filtr">FILTER</button>
</td>
</tr>
<br />
<div id="container_tab"></div>
</table>
</div>
I want the table that comes back from my controller to fill <div id="container_tab"></div>
in my filter controller I have my filtr function, but this function for now does not return $filter_list even though I'm still not doing the actual query.
public function filtr(){
$filter_list = '';
$filter_list .= '
<tr>
<td style="vertical-align: middle;" class="text-center">this should be sent to view as a table row</td>
</tr>
';
echo $filter_list;
}
when I do a console.log within my javascript function the values '3' and 'asdf12' are display but I'm not getting anything back on screen from my controller function calling filtr.
There is a minor error in your success function, your containor has a id called container_tab so use a # in front of its name like this
success:function(data){
$("#container_tab").html(data);
}

Create textbox dynamically in td next to specified td in html table using jquery

Hello all,
I need to create textbox dynamically(depending on condition), when user clicks on employee it should get added next to employee, if user clicks on another element, it should get added next to another element
I have tried following, but I am not able to get exact td and function by which i can append textbox to it.
$("#emlpyeetd").after('<s:textfield id="employeeVal" name="employeeView.policyOrQuoteNumber" maxlength="15" style="width: 200px;" class="hideForAnotherField" theme="simple"></s:textfield>');
<td width="25%">
employee
</td>
<td id="policytd" class= "anotherfield" width="25%"></td>
Try something like this, it will remove 1st textbox when you click on 2nd option.
Jquery code
<script>
$(document).ready(function(){
$(".radio_action").click(function(){
if($(this).val() == "E" ){
$("#other_text").html("");
$("#emp_text").html("<input type='text' >");
}
else if($(this).val() == "A" ) {
$("#emp_text").html("");
$("#other_text").html("<input type='text' >");
}
})
});
</script>
HTML code
<table>
<tr>
<td><input type="radio" name="radio_type" value="E" class="radio_action" /> Employee</td>
<td id="emp_text"></td>
</tr>
<tr>
<td><input type="radio" name="radio_type" value="A" class="radio_action" /> Another Element</td>
<td id="other_text"></td>
</tr>
</table>
Html
<div>
<div class="container">
<div><input type="radio"/ name="somename" value="1">Val1</div>
<div class="editor-wrapper"></div>
</div>
<div class="container">
<div><input type="radio"/ name="somename" value="1">Val2</div>
<div class="editor-wrapper"></div>
</div>
</div>
JS
$(document).ready(function() {
$('input[name="somename"]').click(function() {
$(this.closest('.container')).find('.editor-wrapper').html($('<input>'))
});
});
jsfiddle

Traversing through a html table

I have a table with this structure:
<table>
<tr>
<td>link1</td>
<td>link2</td>
<td>link3</td>
<td><input type = "checkbox" onclick = "func()"></td>
</tr>
</table>
function func(){
//I have to alert link1 here.
}
Can anybody tell me how to do this?
Thanks in advance.
EDIT 1: There are multiple rows of the same type and clicking on a particular check-box should alert the corresponding <a> text.
you can do like this with jquery. Just change the number of the eq. And all table with input with class of checkbox it will run. you can play with it.
$('.checkbox').on('click',function(){
var e = $(this).closest('table').find('td a');
alert(e.eq(0).text());
});
table{
border: 1px solid red;
margin-bottom: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table class="table1">
<tr>
<td>link1</td>
<td>link2</td>
<td>link3</td>
<td><input type = "checkbox" class="checkbox"></td>
</tr>
</table>
<table class="table2">
<tr>
<td>link4</td>
<td>link5</td>
<td>link6</td>
<td><input type = "checkbox" class="checkbox"></td>
</tr>
</table>
Since you are using jQuery, use a jQuery handler in which you can find the a value in the same row
jQuery(function($) {
$('#my-table input[type="checkbox"]').change(function() {
alert($(this).closest('tr').find('td:first-child a').text())
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="my-table">
<tr>
<td>link-1-1</td>
<td>link-1-2</td>
<td>link-1-3</td>
<td>
<input type="checkbox">
</td>
</tr>
<tr>
<td>link-2-1</td>
<td>link-2-2</td>
<td>link-2-3</td>
<td>
<input type="checkbox">
</td>
</tr>
</table>

Trying to serialize a form with dynamically created input elements, but values of elements aren't posted

I am dynamically adding elements. However when I try and serialize the form, none of the dynamically generated elements are serialized.
This is the function I'm using to add elements to the page :
function addObjects(IDname,classname)
{
//to add more objects
var number;
switch(classname)
{
case "name":
number = no_Name++;
break;
case "part":
number = no_part++;
break;
}
var id = classname + number;
$("#"+IDname).append('<tr class="'+id+'"><td><input id="'+id+'" class="'+id+'" type="text"> <button class="'+id+'" onclick=removeAdditions("'+id+'")>x</button></td></tr>');
}
The page looks like this:
<html>
<head>
<script src="Controller.js" type="text/javascript"></script>
<script type="text/javascript" src="https://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
//in order to prevent form reload when button click occurs
$(document).ready(function(){
document.getElementById("ReportForm").onsubmit = function (event) { event.preventDefault(); }
});
</script>
</head>
<body>
<div class="detailsPane" id="detailsPane1" >
<form id="ReportForm" name="ReportForm" >
<table style="width: 100%;">
<tbody>
<tr>
<td>
1. Describe the Status briefly-
</td>
<td>
<textarea id="StatDescp" name="StatDescp"></textarea>
</td>
</tr>
</tbody>
</table>
<br>
<table style="width: 100%;">
<thead>
<tr>
<th colspan="4" align="top">
Part Status
</th>
</tr>
</thead>
<tbody>
<tr>
<td style="vertical-align:top;">
Part Name:
</td>
<td style="vertical-align:top;">
<table >
<tbody id="PartName">
<tr class="partname0">
<td><input class="part_name" type="text"> <button onclick='addObjects("PartName","part_name");'>+</button></td>
</tr>
</tbody>
</table>
</td>
<tbody>
</table>
</form>
</div>
<div id="buttonDiv" >
<a class="bottomLeftResultDiv" id="messageBox"></a>
<input type="button" id="saveButton" value="Save" style="width:85px" onclick="save();" />
</div>
</body>
</html>
And finally here is the save Button.
function save() {
var select = document.getElementById('newReportPane');
var contents = $('#ReportForm').serialize();
contents = contents.replace(/=on/g, "=checked");
contents = contents.replace(/\+/g, " ");
$("#messageBox").html("Saving report...");
console.log(contents);
$.post("/Report/Report1", { action: "save", content: contents }, function (data) {
if (data != "ACK")
$("#messageBox").html("Unable to save.");
else
$("#messageBox").html("Report saved successfully");
});
}
When I click on the save button, it only posts this StatDescp= without any of the dynamically generated elements.
I really can't figure out why.
Any help would be appreciated.
Give a name= attribute to each of your added inputs.
From http://api.jquery.com/serialize/
For a form element's value to be included in the serialized string,
the element must have a name attribute.

Update form using Ajax, PHP, MYSQL

I found a tutorial that auto submits the form data but all I want to do is add a submit button to pass the data to ajax.
My goal is to have a form with multiple inputs and when the user clicks the submit button it sends it through ajax and updates the page without reloading the page. Also, another key piece is the way it post all the inputs into an array so that when the update script is ran the name attributes from the input fields match the columns in the database.
I think I'm close. I've searched and haven't found my exact solution. Thanks in advance.
<script type="text/javascript" src="/js/update.js"></script>
<form method="POST" action="#" id="myform">
<!-- start id-form -->
<table border="0" cellpadding="0" cellspacing="0" id="id-form">
<tr>
<th valign="top">Business Name:</th>
<td><input type="text" name="company_name" class="inp-form" /></td>
<td></td>
</tr>
<tr>
<th valign="top">Address 1:</th>
<td><input type="text" name="address_1" class="inp-form" /></td>
<td></td>
</tr>
<tr>
<th valign="top">Address 2:</th>
<td><input type="text" name="address_2" class="inp-form" /></td>
<td></td>
</tr>
<tr>
<th> </th>
<td valign="top">
<input id="where" type="hidden" name="customer_id" value="1" />
<button id="myBtn">Save</button>
<div id="alert">
</td>
<td></td>
</tr>
</table>
<!-- end id-form -->
</form>
update.js
var myBtn = document.getElementById('myBtn');
myBtn.addEventListener('click', function(event) {
updateform('form1'); });
function updateform(id){
var data = $('#'+id).serialize();
// alert(data);
$.ajax({
type: 'POST',
url: "/ajax/update_company_info.php",
data: data,
success: function(data) {
$('#id').html(data);
$('#alert').text('Updated');
$('#alert').fadeOut().fadeIn();
},
error: function(data) { // if error occured
alert("Error occured, please try again");
},
}); }
update_customer_info.php
<?php
include($_SERVER['DOCUMENT_ROOT'] . '/load.php');
// FORM: Variables were posted
if (count($_POST))
{
$data=unserialize($_POST['data']);
// Prepare form variables for database
foreach($data as $column => $value)
${$column} = clean($value);
// Perform MySQL UPDATE
$result = mysql_query("UPDATE customers SET ".$column."='".$value."'
WHERE ".$w_col."='".$w_val."'")
or die ('Error: Unable to update.');
}
?>
Ended up figuring it out. Thanks for everyones help.
<p id="alert"></p>
<form id="form" method="post" action="/ajax/update_company_info.php">
<!-- start id-form -->
<table border="0" cellpadding="0" cellspacing="0" id="id-form">
<tr>
<th valign="top">Business Name:</th>
<td><input type="text" name="company_name" class="inp-form" /></td>
<td></td>
</tr>
<tr>
<th valign="top">Address 1:</th>
<td><input type="text" name="address_1" class="inp-form" /></td>
<td></td>
</tr>
<tr>
<th valign="top">Address 2:</th>
<td><input type="text" name="address_2" class="inp-form" /></td>
<td></td>
</tr>
<tr>
<th> </th>
<td valign="top">
<input id="where" type="hidden" name="customer_id" value="1" />
<input type="submit" value="Save" id="submit">
</td>
<td></td>
</tr>
</table>
<!-- end id-form -->
</form>
update.js
$(document).ready(function() {
$('form').submit(function(evt) {
evt.preventDefault();
$.each(this, function() {
// VARIABLES: Input-specific
var input = $(this);
var value = input.val();
var column = input.attr('name');
// VARIABLES: Form-specific
var form = input.parents('form');
//var method = form.attr('method');
//var action = form.attr('action');
// VARIABLES: Where to update in database
var where_val = form.find('#where').val();
var where_col = form.find('#where').attr('name');
$.ajax({
url: "/ajax/update_company_info.php",
data: {
val: value,
col: column,
w_col: where_col,
w_val: where_val
},
type: "POST",
success: function(data) {
$('#alert').html("<p>Sent Successfully!</p>");
}
}); // end post
});// end each input value
}); // end submit
}); // end ready
update_customer_info.php
<?php
include($_SERVER['DOCUMENT_ROOT'] . '/load.php');
function clean($value)
{
return mysql_real_escape_string($value);
}
// FORM: Variables were posted
if (count($_POST))
{
// Prepare form variables for database
foreach($_POST as $column => $value)
${$column} = clean($value);
// Perform MySQL UPDATE
$result = mysql_query("UPDATE customers SET ".$col."='".$val."'
WHERE ".$w_col."='".$w_val."'")
or die ('Error: Unable to update.');
}
?>
I think that you want to update form when submit.so you should
remove submit with a button given below.
<button id="myBtn">Save</button>.
You should add the given below code in ur js file.
var myBtn = document.getElementById('myBtn');
myBtn.addEventListener('click', function(event){
Updateform('give id of the form');
});
function updateform(id){
var data = $('#'+id).serialize();
// alert(data);
$.ajax({
type: 'POST',
url: "/ajax/update_company_info.php",
data: data,
success: function(data) {
$('#id').html(data);
// alert(data);
//alert(data);
},
error: function(data) { // if error occured
alert("Error occured, please try again");
},
});
You can retrieve input value in your php code by using unserialize()
as an array.So you can save data to
database and whatever you want to.i hope you get the answer.Hence,your code will become
<form method="POST" action="#" id="form1">
<!-- start id-form -->
<table border="0" cellpadding="0" cellspacing="0" id="id-form">
<tr>
<th valign="top">Business Name:</th>
<td><input type="text" name="company_name" class="inp-form" /></td>
<td></td>
</tr>
<tr>
<th valign="top">Address 1:</th>
<td><input type="text" name="address_1" class="inp-form" /></td>
<td></td>
</tr>
<tr>
<th valign="top">Address 2:</th>
<td><input type="text" name="address_2" class="inp-form" /></td>
<td></td>
</tr>
<tr>
<th> </th>
<td valign="top">
<input id="where" type="hidden" name="customer_id" value="1" />
<button id="myBtn">Save</button>
</td>
<td></td> </tr> </table> <!-- end id-form --> </form>
Your js code become
var myBtn = document.getElementById('myBtn');
myBtn.addEventListener('click', function(event)
{ Updateform('form1'); });
function updateform(id){
var data = $('#'+id).serialize();
// alert(data);
$.ajax({
type: 'POST',
url: "/ajax/update_company_info.php",
data: data,
success: function(data) {
$('#id').html(data);
// alert(data);
//alert(data);
},
error: function(data) { // if error occured
alert("Error occured, please try again");
},
}); }
update_company_info.php will become
$data=unserialize($_POST['data']);
// you can retrieve all values from data array and save all .
?>
Instead of:
$(".submit").click(function() {
Give your form a id like 'myform': <form method="POST" action="#" id="myform">
And use this for preventing default submission of form:
$("#myform").submit(function(e) {
e.preventDefault();
//your code
}

Categories

Resources