javascript - shorter way to collect data and update a table
here is my way to submit a form.
In reality it has much more text inputs.
Everything works fine, but I hope there is a shorter way, especially on server side, regarding that data-col
on client side is in fact a corresponding column name on server.
html
<form id='dform'>
<input type='text' class='dinp' data-col='nick'>
<input type='text' class='dinp' data-col='state'>
<input type='text' class='dinp' data-col='city'>
<input type='text' class='dinp' data-col='uname'>
<input type='text' class='dinp' data-col='pass'>
</form>
js
$('#msave').on('click', function(){
let id=$('.aact').attr('data-id');
let obj = {};
$('.dinp').each(function(){
let col = $(this).attr('data-col');
obj[col] = $(this).val().trim();
});
obj = JSON.stringify(obj);
$.post('a_users_pro.php', {fn: 'm_save', args: [id, obj]}, function(data){
console.log(data);
});
});
php
function m_save($id, $obj){
global $db;
$obj = json_decode($obj);
$sql = "
update users
set nick = :anick
, state = :astate
, city = :acity
, uname = :auname
, pass = :apass
where id = :aid
";
$st = $db->prepare($sql);
$st -> execute([
":aid" => $id,
":anick" => $obj->nick,
":astate" => $obj->state,
":acity" => $obj->city,
":auname" => $obj->uname,
":apass" => $obj->pass
]);
}
Answer
Solution:
You can use the name
attribute of input
elements with your data-col
value and pass the serialized form data to the AJAX request. Here is a implementation:
HTML:
<form id="myForm">
<input type="text" name="name" placeholder="name">
<input type="email" name="email" placeholder="email">
<input type="number" name="age" placeholder="age">
<input type="hidden" name="id" value="1">
<button type="submit">Submit</button>
</form>
JavaScript:
$(document).ready(function() {
$('#myForm').on('submit', function(e) {
e.preventDefault();
$.post('update.php', $('#myForm').serialize());
});
});
PHP:
<?php
if (isset($_POST)) {
// Validate request
$sql = 'UPDATE users
SET
name = :name,
email = :email,
age = :age
WHERE id = :id
';
$st = $db->prepare($sql);
$st->execute([
':id' => $_POST['id'],
':name' => $_POST['name'],
':email' => $_POST['email'],
':age' => $_POST['age'],
]);
}
?>
In your example I can't see where .aact
and data-id
come from. I assumed that the id
value would be available to the view so I passed it to the request as a hidden input.