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
2
Answers
The solution may be this…
If I understood correctly what you were asking.
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 thecontentEditable
cells.Any/All checkboxes that are ticked will appear in the POST array – any that remain unticked are ignored. The
set
method of theFormData
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.