Reputation: 9
Below is my code and what I have done so far.
How to insert all data in table to database using ajax after click #orderSave button??
<table class="table table-sm table-striped table-hover" id="tbltrs">
<thead>
<tr>
<th>Name</th>
<th>Price</th>
<th>Qty</th>
</tr>
</thead>
<tbody id="tbodydata"></tbody>
</table>
<button type="button" id="orderSave" class="btn btn-sm btn-secondary">Process</button>
$("#code").bind('blur keypress',function(event){ event.preventDefault(); if (event.keyCode === 13 || event.type == 'blur') { var vals = $('#code').val(); $.ajax({ type: 'POST', url: 'check.php', cache: false, dataType:"json", data:{code: vals}, success: function(data) { if(data['ok'] > 0){ var qty = 1; var elems = $('#tbltrs td').filter(function(){ return $.trim($(this).text()) === data['name']; }); if (elems.length) { var qty = parseInt(elems.parent('tr').find('#qty').val()) + 1; elems.parent('tr').find('#qty').val(qty); } else { var html = ''; html += ''; html += ''+data['product']+''; html += ''+data['price']+''; html += ''; $('#tbodydata').prepend(html); } } else {alert('none');} $('#code').val('').focus(); }, error:function(err){alert("error"+JSON.stringify(err)); } }); } });
$('#orderSave').click(function() {
$.ajax({
type: 'POST',
url: 'orders.php',
cache: false,
data:............,
success: function(data) {
printWindow = window.open("", "", "height=1, width=1");
printWindow.document.write(data);
printWindow.focus();
printWindow.print();
printWindow.close();
},
error:function(err){alert("error"+JSON.stringify(err)); }
});
});
Upvotes: 0
Views: 1140
Reputation: 178385
You need to serialize the form and use the submit event
We use e.preventDefault()
to not submit
You do need NAME attributes
Also I suggest not to use ID when you append/prepend data
You forget a document.close where you use document.write
Lastly is the html more readable when you use template literals
$('#tbodydata').prepend(`<tr>
<td class="d-none"><input type="text" name="id" id="id" value="${data['id']}"></td>
<td class="col" name="product">${data(product)}</td>
<td class="col" name="price">${data(price)}</td>
<td class="col"><input type="text" name="qty" id="qty" value="${qty}"></td></tr>`);
$("#yourForm").on("submit",function(e) {
e.preventDefault()
const data = $(this).serialize();
$.ajax({
type: 'POST',
url: 'orders.php',
cache: false,
data: data,
success: function(data) {
printWindow = window.open("", "", "height=1, width=1");
printWindow.document.write(data);
printWindow.document.close();
printWindow.focus();
printWindow.print();
printWindow.close();
},
error: function(err) {
alert("error" + JSON.stringify(err));
}
});
});
Upvotes: 0