Updating table rows in datatables with jquery - javascript

How can I use jQuery ajax to handle checked checkboxes? How do I then send each checked checkbox in the html table, to ajax.php?
This is what I've tried so far:
ajax.php
session_start();
if (isset($_POST['id']) && isset($_POST['to']) && isset($_SESSION['user']['id'])) {
if (is_numeric($_POST['id']) && is_numeric($_POST['to'])) {
include("mysql_connector.php");
$user = $_SESSION['user']['id'];
$sendTo = mysql_real_escape_string(trim($_POST['to']));
foreach ($_POST['id'] as $id) {
$id = mysql_real_escape_string(trim($id));
mysql_query("UPDATE `email` SET status = '$sendTo' WHERE `email_id` = '$id' AND `userid` = '$user'");
}
}
}
Javascript:
$(".submit").click(function() {
var id = $("#id").val();
var to = $("#bins").val();
var dataString = 'id=' + id + '&to=' + to;
$.ajax({
type: "POST",
url: "ajax.php",
data: dataString,
});
});
html:
<form method="POST">
<table id="inventory" class="table">
<thead>
<tr>
<th style="text-align: center;">Check All</th>
<th>Time Received</th>
<th>Email</th>
<th>Subject</th>
<th>ID</th>
</tr>
</thead>
<tbody>
<tr class="email">
<td style="text-align: center;"><input type="checkbox" name='msg[]' class="id" value="2" /></td>
<td>1231231</td>
<td>test</td>
<td>test</td>
<td>0</td>
</tr>
<tr class="email">
<td style="text-align: center;"><input type="checkbox" name='msg[]' class="id" value="3" /></td>
<td>1231231</td>
<td>test</td>
<td>test</td>
<td>1</td>
</tr>
</tbody>
</table>
</br>
<select name="bins" class="bins">
<option value="1">Archive</option>
<option value="2">Read</option>
<option value="3">Unread</option>
<option value="4">Save</option>
</select>
<input type="submit" name="move" value="Move" class="submit" style="width:auto;"/>
</form>
Thank you for reading.

First, it is invalid to have multiple dom elements with duplicate ids. If those checkboxes need ids, make them unique. If they don't need ids, then just drop them completely.
To get a list of the values of all checked checkboxes, do:
var checkedVals = [];
$("input[type='checkbox']:checked").each(function() {
checkedVals.push($(this).val());
});
Or you can fetch different groups of checkboxes by name:
var checkedMsgVals = [];
$("input[name='msg[]']:checked").each(function() {
checkedMsgVals.push($(this).val());
});
To send these to php, just include them in your data packet when you make the call. To do this you'll want to send an object over, not a querystring.
var dataObj = {'id': id, 'to': to, 'checkedValues': checkedMsgVals };
$.ajax({
type: "POST",
url: "ajax.php",
data: dataObj,
});

Related

Why when referring to the second field, the value is taken from the first?

I recently work with jquery. And I have such a question. I add elements to the page via forEach and I need to access the field of a specific product in jquery.
My JQuery:
jQuery(document).ready(function() {
$('.count').on('blur', function getTotalPrice(){
var name = $('#name').html();
var count = $('.count').val();
$.ajax({
type: "GET",
url: "cart",
data: "name=" + name + "&count=" + count,
success: function(data){
$("#totalPrice").text("Total price: " + data['totalPrice'].toFixed(2)).wrap("<h4></h4>");
$("#productCount").text("(" + data['productCount'] + ")");
$.each([data['cartItems']], function(key, value) {
});
},
dataType: "json"
});
});
});
My Page:
<table>
<tr>
<th>Item</th>
<th>Name</th>
<th>Category</th>
<th>Company Manufacturer</th>
<th>QTY</th>
<th>Prices</th>
<th>Total Prices</th>
</tr>
<c:forEach items="${cartItems}" var="items">
<tr>
<td><a href="images/product/${items.key.imageName}"><img src="images/product/${items.key.imageName}" width=100></td>
<td><span id="name">${items.key.name}</span></td>
<td>${items.key.category.name}</td>
<td>${items.key.manufacturer.name}</td>
<td><input type="text" class="count" value="${items.value}"></td>
<td>${items.key.price}</td>
<td><span id="totalPriceForOne">${items.key.price * items.value}</span></td>
<td>Remove item</td>
</tr>
</c:forEach>
</table>
</div>
<div align="right" style="color: #0087ff">
<span id="totalPrice"><h4>Total price: ${totalPrice}</h4></span>
</div>
<div align="right">Make order</div>
My Page when i fill it:
<table>
<tr>
<th>Item</th>
<th>Name</th>
<th>Category</th>
<th>Company Manufacturer</th>
<th>QTY</th>
<th>Prices</th>
<th>Total Prices</th>
</tr>
<tr>
<td><a href="images/product/3.png"><img src="images/product/3.png" width=100></td>
<td><span class="name">ALLIANCE_SUNGLASSES</span></td>
<td>accessories</td>
<td>Luis Vuitton</td>
<td><input type="text" class="count" value="1"></td> //сюда обращается
<td>810.00</td>
<td><span id="totalPriceForOne">810.00</span></td>
<td>Remove item</td>
</tr>
<tr>
<td><a href="images/product/2.png"><img src="images/product/2.png" width=100></td>
<td><span class="name">45DAVID</span></td>
<td>jeans</td>
<td>Collins</td>
<td><input type="text" class="count" value="12"></td> //сюда обратиться не выходит
<td>100.00</td>
<td><span id="totalPriceForOne">1200.00</span></td>
<td>Remove item</td>
</tr>
</table>
So I have a problem, I want that when I change the values ​​of the count field, they change for that product opposite which this field is located. Now when I try to change the count in the second product, it refers to the field of the first product, and the values ​​do not change. If I turn to the first field, then everything is fine there, I indicate the quantity of goods I need, and it recounts the price for me. But why do I fail when I try to do this for the second product? How to fix it?
You need to change this line; var count = $('.count').val(); to var count = $(this).val();
Since there seems to be many instances of .count, you have to refer to the currently selected element with $(this).
For the name, it's a bit tricky, you have to find the nearest .name. Since the .count is inside a td, you have to use .parent() to navigate to the td. Once you're in the td, you have to use .parent() again to navigate to the tr. Once in the tr, you need to use .find(".name") to find the child with class name.
jQuery(document).ready(function() {
$('.count').on('blur', function getTotalPrice(){
// updated
var name = $(this).parent().parent().find('.name').html();
// updated
var count = $(this).val();
$.ajax({
type: "GET",
url: "cart",
data: "name=" + name + "&count=" + count,
success: function(data){
$("#totalPrice").text("Total price: " + data['totalPrice'].toFixed(2)).wrap("<h4></h4>");
$("#productCount").text("(" + data['productCount'] + ")");
$.each([data['cartItems']], function(key, value) {
});
},
dataType: "json"
});
});
});

jQuery- Not able to select the right td

I can't seem to identify what went wrong with my jquery such that it keeps sending null data. Basically, after clicking a button I get a bunch of results and I want to be able to press edit and then edit that row which I can do but the values don't go into my ajax post to my api. I think that it would be my variable not selecting the correct td thus resulting in nothing being sent to the ajax post.
HTML:
<table id="results" class="hidden" cellspacing=10px>
<thead>
<tr class = "spacing">
<th id= "samIdTable">SAM ID</th>
<th id= "itemDescrip">Item Description</th>
<th id= "issuedQty">Issued QTY</th>
<th id= "openingQty">Opening QTY</th>
<th id= "closingQty">Closing QTY</th>
<th id= "corruptedQty">Corrupted QTY</th>
<th id="Remarks">Remarks</th>
</tr>
</thead>
<tbody id="bResults">
<tr class="rowdata">
<td>hi</td>
<td>hi</td>
<td>hi</td>
<td>hi</td>
<td>hi</td>
<td>hi</td>
<td>hi</td>
<td><input class="button-edit" type="submit" id="edit" value="Edit" onclick="edit(this)"></td>
</tr>
<tr class="rowdata">
<td>hi</td>
<td>hi</td>
<td>hi</td>
<td>hi</td>
<td>hi</td>
<td>hi</td>
<td>hi</td>
<td><input class="button-edit" type="submit" id="edit" value="Edit" onclick="edit(this)"></td>
</tr>
</tbody>
</table>
JS CODE
function edit(el){
var currentTD = $(el).closest('tr').find('td'); // tds except the td which closest to the edit button
var samId = currentTD.find("td:nth-child(1)").val();
var itemDescrip= currentTD.find("td:nth-child(2)").val();
var issueQty = currentTD.find("td:nth-child(3)").val();
var openingQty =currentTD.find("td:nth-child(4)").val();
var closingQty = currentTD.find("td:nth-child(5)").val();
var corruptedQty = currentTD.find("td:nth-child(6)").val();
var Remarks = currentTD.find("td:nth-child(7)").val();
var postData = { "samId": samId, "itemDescrip": itemDescrip, "issueQty" : issueQty,
"openQty" : openingQty, "closeQty" :closingQty,
"corrupQty": corruptedQty, "remarks": Remarks};
var postJSON = JSON.stringify(postData);
if ($(el).val() == 'Edit') {
$.each(currentTD, function () {
$(this).prop('contenteditable', true);
});
} else {
$.each(currentTD, function () {
$(this).prop('contenteditable', false);
});
}
$(el).val($(el).val() == 'Edit' ? 'Save' : 'Edit');
if($(el).val() == 'Edit' ){
$.ajax({
url: "http://localhost:3000/api/updateRecord", // server url
type: "POST", //POST or GET
contentType: "application/json", // data to send in ajax format or querystring format
data: postJSON,
dataType : "JSON", //dataType is you telling jQuery what kind of response to expect
success: function(response) {
alert('success');
if(response){
var txt = "";
txt += "<tr class='rowdata'><td>"+response.samID+"</td>"
+"<td>"+response.itemDescription+"</td>"
+"<td>"+response.issuedQTY + "</td>"
+"<td>"+response.openingQTY + "</td>"
+"<td>"+response.closingQTY+"</td>"
+"<td>"+response.corruptedQTY+"</td>"
+"<td>"+response.Remarks+"</td>"
+"</td>"+"</tr>";
}
if(txt != ""){
$("#results").removeClass("hidden");
$("#bResults").append(txt);
}
},
error: function(response) {
alert('error');
}
});
}
}
Do tell me if additional information is needed. Thank you in advance. Don't understand what is with the downvotes but I did state if additional information is needed, I will provide. If not, at least state reasons as to why it is downvoted and I could improve on it next time.
In your code var currentTD = $(el).closest('tr').find('td'); you have already selected the nearest <td> with query which does not have child <td> .Also you cannot get the value of td using .val().Use .html() instead.
I have modified some of your code like below.
Your html
<table id="results" class="hidden" cellspacing=10px>
<thead>
<tr class = "spacing">
<th id= "samIdTable">SAM ID</th>
<th id= "itemDescrip">Item Description</th>
<th id= "issuedQty">Issued QTY</th>
<th id= "openingQty">Opening QTY</th>
<th id= "closingQty">Closing QTY</th>
<th id= "corruptedQty">Corrupted QTY</th>
<th id="Remarks">Remarks</th>
</tr>
</thead>
<tbody id="bResults">
<tr class="rowdata">
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
<td><input class="button-edit" type="submit" id="edit" value="Edit" onclick="edit(this)"></td>
<tr class="rowdata">
<td>8</td>
<td>9</td>
<td>10</td>
<td>11</td>
<td>12</td>
<td>13</td>
<td>14</td>
<td><input class="button-edit" type="submit" id="edit" value="Edit" onclick="edit(this)"></td>
</tbody>
</table>
And your javascript
function edit(el){
var currentTD = $(el).closest('tr').find('td'); // tds except the td which closest to the edit button
var current_id = $(el).closest('tr');
var samId = current_id.find("td:nth-child(1)").html();
var itemDescrip= current_id.find("td:nth-child(2)").html();
var issueQty = current_id.find("td:nth-child(3)").html();
var openingQty =current_id.find("td:nth-child(4)").html();
var closingQty = current_id.find("td:nth-child(5)").html();
var corruptedQty = current_id.find("td:nth-child(6)").html();
var Remarks = current_id.find("td:nth-child(7)").html();
var postData = { "samId": samId, "itemDescrip": itemDescrip, "issueQty" : issueQty,
"openQty" : openingQty, "closeQty" :closingQty,
"corrupQty": corruptedQty, "remarks": Remarks};
var postJSON = JSON.stringify(postData);
if ($(el).val() == 'Edit') {
$.each(currentTD, function () {
$(this).prop('contenteditable', true);
});
} else {
$.each(currentTD, function () {
$(this).prop('contenteditable', false);
});
}
$(el).val($(el).val() == 'Edit' ? 'Save' : 'Edit');
if($(el).val() == 'Edit' ){
$.ajax({
url: "http://localhost:3000/api/updateRecord", // server url
type: "POST", //POST or GET
contentType: "application/json", // data to send in ajax format or querystring format
data: postJSON,
dataType : "JSON", //dataType is you telling jQuery what kind of response to expect
success: function(response) {
alert('success');
if(response){
var txt = "";
txt += "<tr class='rowdata'><td>"+response.samID+"</td>"
+"<td>"+response.itemDescription+"</td>"
+"<td>"+response.issuedQTY + "</td>"
+"<td>"+response.openingQTY + "</td>"
+"<td>"+response.closingQTY+"</td>"
+"<td>"+response.corruptedQTY+"</td>"
+"<td>"+response.Remarks+"</td>"
+"</td>"+"</tr>";
}
if(txt != ""){
$("#results").removeClass("hidden");
$("#bResults").append(txt);
}
},
error: function(response) {
alert('error');
}
});
}
}
Hope it will work.
Instead of using find after getting the currentTD, I have used it as an array.
Please check the jsfiddle https://jsfiddle.net/jkpjjmeu/
function edit(el) {
var currentTD = $(el).closest('tr').find('td');
var samId = currentTD[0].textContent;
}
You're <tr>s don't close!
Add </tr> in the right places and try again.

How to select all input fields that sits in a table

I have a form that "sits" inside a table
<form id="form">
<input type="submit" value="send" class="btn btn-w-m btn-primary" style="float: left;">Add transaction</input>
<table class="table table-striped table-bordered table-hover " id="editable" >
<thead>
<tr>
<th>Date</th>
<th>Name<br>(Last name, Firstname,<br>
or Business name)
</th>
<th>Address</th>
<th>Phone</th>
<th>Price with VAT</th>
<th>VAT</th>
<th>Transaction type</th>
<th>Currency</th>
<th>Installments</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="date" name="date"/></td>
<td><input type="text" name="name"/></td>
<td><input type="text" name="address"/></td>
<td><input type="text" name="phone"/></td>
<td><input type="text" name="price_with_vat"/></td>
<td>25%(from database)</td>
<td class="exclude"><select name="transaction_type">
<option>value1</option>
<option>value2</option>
<option>value3</option>
</select></td>
<td class="exclude"><select name="currency">
<option>Euro</option>
<option>USD</option>
<option>Pound</option>
</select></td>
<td class="exclude"><select name="installments">
<option>Yes</option>
<option>No</option>
</select></td>
</tr>
</tbody>
What I want is to select all input values and send an Ajax request to a php end. The problem is that in my jquery function (code following) i cannot gather all the inputs. Also altough i have a preventDefault page still get refreshed.
var request;
$('#form').submit(function(event){
if (request){
request.abort();
}
var form = $(this)
var $inputs = $form.find("input, select, button, textarea");
var serializedData = $form.serialize();
$inputs.prop("disabled", true);
console.log(serializedData);
event.preventDefault();
});
Try this code
For a form element's value to be included in the serialized string,
the element must have a name attribute.
$(document).ready(function() {
//Form submit event
$('#form').on('submit', function(e){
// validation code here
if(!valid) {
e.preventDefault();
}
//Serialized data
var datastring = $("#form").serialize();
//Ajax request to send data to server
$.ajax({
type: "POST",
url: "your url.php",
data: datastring,
success: function(data) {
alert('Data send');
}
});
});
});
Try using this code:
$('#form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'yourpage.php',
data: $('#form').serialize(),
success: function(){
alert('success');
},
});
});
});
});
Just change url: 'yourpage.php' with your php page where you want to send form values

$.ajax not working in chrome and firefox but is working in IE

I have the following code. It works fine in IE but not in Chrome and Firefox. There is no error displayed. It just doesn't get the value entered. Can someone help me fix the problem. Thanks in advance.
File 'main.php'
---------------
<tr>
<td width="11%" class="style171"></td>
<td width="55%" bgcolor="#A8D3FF" class="style171"><strong>APPROVE</strong></td>
<td width="16%" bgcolor="#A8D3FF" align="center"><input type="radio" name="approve" id="approve" value="1" <?php if ($approve== '1') echo "checked"; ?> /></td>
<td width="18%"></td>
</tr>
<tr>
<td width="11%" class="style171"></td>
<td class="style171" bgcolor="#A8D3FF"><strong>NOT APPROVE</strong></td>
<td bgcolor="#A8D3FF" align="center"><input type="radio" name="approve" id="approve" value="2" onClick="processForm()" <?php if ($approve== '2') echo "checked"; ?> /></td>
<td width="18%"></td>
</tr>
<tr>
<td width="11%" class="style171"></td>
<td colspan="2" align="left"><div id="div_data"></div></td>
<td width="18%"></td>
</tr>
<script type="text/javascript">
function processForm()
{
var val = 0;
if(window.document.getElementById('approve').checked)
var val = 1;
$.ajax( {
type: 'POST',
url: 'not_approved.php',
data: "value="+val,
cache: false,
success: function(html){
$("#div_data").html(html);
}
} );
}
</script>
File 'not_approved.php'
-----------------------
<form id="formt" name="formt" method="post" action="">
<table width="100%" border="0" align="left" cellpadding="1" cellspacing="0" bgcolor="#D8EEFE">
<tbody>
<tr>
<td colspan="3"><table width="100%" border="1" bordercolor="#33CCFF" cellspacing="0" cellpadding="1">
<tbody>
<tr class="style2">
<td align="left"><font color="#FF0000">*</font> Enter your comments here.
<table width="430" border="0">
<tr class="style2">
<td width="10" align="left" valign="top"></td>
<td width="410" colspan="2" align="left" valign="top"><textarea name="comment" id="comment" cols="45" rows="5"><?php echo $comment; ?></textarea></td>
</tr>
</table></td>
</tr>
</tbody>
</table></td>
</tr>
</tbody>
</table>
</form>
Try this
function processForm()
{
var val = 0;
if(window.document.getElementById('approve').checked)
var val = 1;
$.ajax( {
type: 'POST',
url: 'not_approved.php',
data: {value:val},
cache: false,
success: function(html){
$("#div_data").html(html);
}
} );
}
</script>
** The data filed is changed **
You are passing data in wrong way do as below
data: "{'value':"+val+"}",
and if the value is in string then
data: "{'value':'"+val+"'}",
or
data: JSON.stringify({value:val})
Your data variable must not be in string format because its a variable name. You should do it like this:
<script type="text/javascript">
function processForm()
{
var val = 0;
if(window.document.getElementById('approve').checked)
var val = 1;
$.ajax( {
type: 'POST',
url: 'not_approved.php',
data: {
value: val,
}
cache: false,
success: function(html){
$("#div_data").html(html);
}
} );
}
</script>
Here your script variable val value assigned to value variable and for assigning we use colon here ':' instead of = in AJAX. In server side the catching variable must also be of same name i.e value.

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