Pass Item data value into controller using js - javascript

Hello i have problem with my project, i try to JSON but i have multiple variable so i dont know if it works, and when i try passing $id into controller snap and calling data using mysql items data is null. im stuck at here
here my view
<div class="row">
<table class="table mt-3" id="t_detail">
<thead class="thead">
<tr>
<th scope="col">#</th>
<th scope="col">Gambar</th>
<th scope="col">Nama Barang</th>
<th scope="col">Harga</th>
</tr>
</thead>
<tbody>
<?php $no=0;foreach ($produk as $id=>$prd): ?>
<?php $no++?>
<tr>
<?php $barang []= array(
'id' => $prd->id_barang,
'quantity' => 1,
'price' => $prd->harga,
'name' => $prd->nama_barang,
);?>
<th scope="row"><?=$no?></th>
<td><img height="280" width="auto" src="<?=base_url('uploads/' . $prd->gambar)?>" ></td>
<td><?=$prd->nama_barang?></td>
<td>Rp. <?php echo number_format($prd->harga,0,",",".");?></td>
</tr>
<?php endforeach;?>
<?php $no++?>
<tr>
<th scope="row"><?=$no?></th>
<td></td>
<td>Biaya Ongkir</td>
<td>Rp. <?php echo number_format($transaksi->ongkir,0,",",".");?></td>
</tr>
</tbody>
<tfoot>
<tr>
<th scope="row"></th>
<td></td>
<td>Total Bayar</td>
<td>Rp. <?php echo number_format($transaksi->total_bayar,0,",",".");?></td>
</tr>
</tfoot>
</table>
</div>
<?php if ($produk):?>
<div class="row">
<div class="col-md-6 offset-md-6">
<button class="btn btn-sm btn-success float-right" id="tombol-bayar">Bayar</button>
</div>
</div>
<?php endif;?>
<input name="transaksi_id" value="<?=($transaksi->id)?>" type="hidden">
<input name="nama" value="<?=($transaksi->namalengkap)?>" type="hidden">
<input name="alamat" value="<?=($transaksi->alamat)?>" type="hidden">
<input name="kodepos" value="<?=($transaksi->kodepos)?>" type="hidden">
<input name="kabupaten" value="<?=($transaksi->kabupaten)?>" type="hidden">
<input name="no_hp" value="<?=($user['no_hp'])?>" type="hidden">
<input name="email" value="<?=($user['email'])?>" type="hidden">
<input name="total_bayar" value="<?=($transaksi->total_bayar)?>" type="hidden">
<input name="ongkir" value="<?=($transaksi->ongkir)?>" type="hidden">
<input name="ekspedisi" value="<?=($transaksi->ekspedisi)?>" type="hidden">
<input name="paket" value="<?=($transaksi->paket)?>" type="hidden">
and my JS
<script>
$('#tombol-bayar').click(function(event) {
var transaksi_id = $("input[name=transaksi_id]").val();
var nama = $("input[name=nama]").val();
var alamat = $("input[name=alamat]").val();
var email = $("input[name=email]").val();
var kodepos = $("input[name=kodepos]").val();
var ongkir = $("input[name=ongkir]").val();
var ekspedisi = $("input[name=ekspedisi]").val();
var paket = $("input[name=paket]").val();
var kabupaten = $("input[name=kabupaten]").val();
var no_hp = $("input[name=no_hp]").val();
var total_bayar = $("input[name=total_bayar]").val();
$(this).attr("disabled", "disabled");
$.ajax({
type: "POST",
url: '<?= base_url() ?>/snap/token',
cache: false,
data: {
barang: barang,
'transaksi_id': transaksi_id,
'nama': nama,
'alamat': alamat,
'email': email,
'kodepos': kodepos,
'ongkir': ongkir,
'ekspedisi': ekspedisi,
'paket': paket,
'kabupaten': kabupaten,
'no_hp': no_hp,
'total_bayar': total_bayar,
},
success: function(data) {
//location = data;
console.log('token = ' + data);
var resultType = document.getElementById('result-type');
var resultData = document.getElementById('result-data');
function changeResult(type, data) {
$("#result-type").val(type);
$("#result-data").val(JSON.stringify(data));
//resultType.innerHTML = type;
//resultData.innerHTML = JSON.stringify(data);
}
snap.pay(data, {
onSuccess: function(result) {
changeResult('success', result);
console.log(result.status_message);
console.log(result);
$("#payment-form").submit();
},
onPending: function(result) {
changeResult('pending', result);
console.log(result.status_message);
$("#payment-form").submit();
},
onError: function(result) {
changeResult('error', result);
console.log(result.status_message);
$("#payment-form").submit();
}
});
}
});
});
and my controller
public function token()
{
$nama = $this->input->post('nama');
$email = $this->input->post('email');
$kabupaten = $this->input->post('kabupaten');
$kodepos = $this->input->post('kodepos');
$alamat = $this->input->post('alamat');
$no_hp = $this->input->post('no_hp');
$ekspedisi = $this->input->post('ekspedisi');
$paket = $this->input->post('paket');
$ongkir = $this->input->post('ongkir');
$total_bayar = $this->input->post('total_bayar');
$barang = $this->input->post('barang');
$item_details [] = $barang;
how can i post items data into that controller.. im confuse please help

Related

Knockout Observable not updating on Modal DOM/UI

Knockout observable value not updating on bootstrap Modal. In debug I can see that the value have been successfully added to observable. It just not updating/appearing on the modal DOM.
self.getSdsById = function (val) {
var ID = val.ID;
var operation = event.currentTarget.dataset['operation'];
$.ajax({
url: baseUrl + '/SdsView/getSdsByID',
cache: false,
type: 'GET',
contentType: 'application/json; charset=utf-8',
data: { 'ID': ID },
success: function (data) {
self.CopySdsDetail().RegistrationNo(data.Sds.RegistrationNo);
self.CopySdsDetail().MSDSIssueDate(data.Sds.MSDSIssueDate);
self.CopySdsDetail().Place(data.Sds.Place);
self.CopySdsDetail().Dept(data.Sds.Dept);
self.CopySdsDetail().Div(data.Sds.Div);
if (operation == 'COPY') {
$('#copyModalTitle').text('Copy & Add SDS to other Division');
$('#copyModal').modal();
}
}
}).fail(
function (xhr, textStatus, err) {
swal("Error", err, "error");
});
}
Modal :
<div class="modal fade" id="copyModal">
<div class="table-responsive" data-bind="with: CopySdsDetail">
<table class="table table-bordered table-sm">
<tr>
<td>Division: </td>
<td>Department: </td>
<td>Place: </td>
</tr>
<tr>
<td><input type="text" data-bind="value: Div"/></td>
<td><input type="text" data-bind="value: Dept"/></td>
<td><input type="text" data-bind="value: Place"/></td>
</tr>
<tr>
<td data-bind="text: RegistrationNo" colspan="2"></td>
<td data-bind="text: MSDSIssueDate"></td>
</tr>
</table>
</div>
</div>
Ko observable value in debug:
Any idea why?
in the short time I had to look at this, it generally looks ok, I got a very basic sample working with what you have provided. maybe it will help
var data = {
Dept: "Dicing",
Div: "DCG",
ID: 0,
MSDSIssueDate: "/Date(1602172800000)/",
Place: "Etching Process",
RegistrationNo: "DS-033"
}
function ViewModel() {
var self = this;
self.CopySdsDetail = ko.observable(new ModalViewModel());
self.clearData = function(){
self.CopySdsDetail(new ModalViewModel());
}
self.getData = function() {
self.CopySdsDetail(new ModalViewModel(data));
// self.CopySdsDetail().RegistrationNo(data.RegistrationNo);
// self.CopySdsDetail().MSDSIssueDate(data.MSDSIssueDate);
// self.CopySdsDetail().Place(data.Place);
// self.CopySdsDetail().Dept(data.Dept);
// self.CopySdsDetail().Div(data.Div);
}
}
function ModalViewModel(data){
var self = this;
data = data || {};
self.RegistrationNo = ko.observable(data.RegistrationNo || "");
self.Dept = ko.observable(data.Dept || "");
self.Div = ko.observable(data.Div || "");
self.ID = ko.observable(data.ID || "");
self.MSDSIssueDate = ko.observable(data.MSDSIssueDate || "");
self.Place = ko.observable(data.Place || "");
}
var vm = new ViewModel();
ko.applyBindings(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<div class="modal fade" id="copyModal">
<div class="table-responsive" data-bind="with: CopySdsDetail">
<table class="table table-bordered table-sm">
<tr>
<td>Division: </td>
<td>Department: </td>
<td>Place: </td>
</tr>
<tr>
<td><input type="text" data-bind="value: Div" /></td>
<td><input type="text" data-bind="value: Dept" /></td>
<td><input type="text" data-bind="value: Place" /></td>
</tr>
<tr>
<td data-bind="text: RegistrationNo" colspan="2"></td>
<td data-bind="text: MSDSIssueDate"></td>
</tr>
</table>
</div>
</div>
<button data-bind="click: getData">Get Data</button>
<button data-bind="click: clearData">Clear Data</button>

Why is .getElementById("name_val"+id).innerHTML is null?

I am trying to differentiate each id with their corresponding id from database. For Eg: Name_val19. The line var name=document.getElementById("name_val"+id).innerHTML; is returning null value. The value is being stored in database also
function edit_row(id)
{
var name=document.getElementById("name_val"+id).innerHTML;
var age=document.getElementById("age_val"+id).innerHTML;
document.getElementById("name_val"+id).innerHTML="<input type='text' id='name_text"+id+"' value='"+name+"'>";
document.getElementById("age_val"+id).innerHTML="<input type='text' id='age_text"+id+"' value='"+age+"'>";
document.getElementById("edit_button"+id).style.display="none";
document.getElementById("save_button"+id).style.display="block";
}
function save_row(id)
{
var name=document.getElementById("name_val"+id).value;
var age=document.getElementById("age_val"+id).value;
$.ajax
({
type:'post',
url:'modify_records.php',
data:{
edit_row:'edit_row',
row_id:id,
name_val:name,
age_val:age
},
success:function(response) {
if(response=="success")
{
document.getElementById("name_val"+id).innerHTML=name;
document.getElementById("age_val"+id).innerHTML=age;
document.getElementById("edit_button"+id).style.display="block";
document.getElementById("save_button"+id).style.display="none";
}
}
});
}
function delete_row(id)
{
$.ajax
({
type:'post',
url:'modify_records.php',
data:{
delete_row:'delete_row',
row_id:id,
},
success:function(response) {
if(response=="success")
{
var row=document.getElementById("row"+id);
row.parentNode.removeChild(row);
}
}
});
}
function insert_row()
{
var name=document.getElementById("new_name").value;
var age=document.getElementById("new_age").value;
$.ajax
({
type:'post',
url:'modify_records.php',
data:{
insert_row:'insert_row',
name_val:name,
age_val:age
},
success:function(response) {
if(response!="")
{
var id=response;
var table=document.getElementById("user_table");
var table_len=(table.rows.length)-1;
var row = table.insertRow(table_len).outerHTML="<tr id='row"+id+"'><td id='name_val"+id+"'>"+name+"</td><td id='age_val"+id+"'>"+age+"</td><td><input type='button' class='edit_button' id='edit_button"+id+"' value='Edit' onclick='edit_row("+id+");'/><input type='button' class='save_button' id='save_button"+id+"' value='Save' onclick='save_row("+id+");'/><input type='button' class='delete_button' id='delete_button"+id+"' value='Delete' onclick='delete_row("+id+");'/></td></tr>";
document.getElementById("new_name").value="";
document.getElementById("new_age").value="";
}
}
});
}
$("#insert").submit(function() {
var name= $("#new_name").val();
var password= $("#new_age").val();
$.ajax({
type: "POST",
url: "connect.php",
data: "name=" + name+ "&password=" + password,
success: function(data) {
alert("sucess");
}
});
});
PHP Code:
<html>
<head>
</head>
<body>
<div id="wrapper">
<table align="center" cellpadding="10" border="1" id="user_table">
<tr>
<th>NAME</th>
<th>AGE</th>
<th></th>
</tr>
<?php
include "connect.php";
$select=mysqli_query($connection,"SELECT * FROM user_detail");
if($select!=NULL){
while ($row=mysqli_fetch_array($select,MYSQLI_BOTH))
{
?>
<tr id="row<?php echo $row['id'];?>">
<td id="name_val<?php echo row['id'];?>"><?php echo $row['name'];?></td>
<td id="age_val<?php echo $row['id'];?>"><?php echo $row['age'];?></td>
<td>
<button class="edit_button" id="edit_button<?php echo $row['id'];?>" onclick="edit_row('<?php echo $row['id'];?>');">Edit</button>
<button class="save_button" id="save_button<?php echo $row['id'];?>" onclick="save_row('<?php echo $row['id'];?>');">Save</button>
<button class="delete_button" id="delete_button<?php echo $row['id'];?>" onclick="delete_row('<?php echo $row['id'];?>');">Delete</button>
</td>
</tr>
<?php
}
}
?>
<tr id="new_row"><form id="insert" onclick="insert_db()">
<td><input type="text" id="new_name"></td>
<td><input type="text" id="new_age"></td>
<td><button type="button" value="Insert Row" onclick="insert_row()">Insert</button></td>
</form></tr>
</table>
</div>
</body>
<script type="text/javascript" src="./js/jquery-3.2.0.js"></script>
<script type="text/javascript" src="./js/modify_records.js"></script>
</html>
looks like a few things, first i recommend getting the element by class since your id is complicated, try using getElementByClass("edit_button") to get <button class="edit_button" id="...">
getElementById() does exactly that, you are trying to get a dom (html) element by its id="" attribute, into the js Scope so you can do something with it. it should be getElementById("IDofElement")
getElementById("row") gets <p id="row"> </p>
but it looks like you set
var id=response; which makes your
getElementById("IDofElement"+"ENTIRE AJAX RESPONSE") call throw an error because there is no dom element with an id of e.g.
<div id="rowENTIRE-AJAX-RESPONSE"></div>
You're killing yourself with all these IDs. Use HTML5 data-attribute to store your record's ID once per row.
<tr data-id="<?php echo $row['id'] ?>">
<!-- added class names to cells bc we'll be using them later -->
<td class="name"><?php echo $row['name'] ?></td>
<td class="age"><?php echo $row['age'] ?></td>
<td>
<button type="button" class="edit_button">Edit</button>
<button type="button" class="save_button">Save</button>
<button type="button" class="delete_button">Delete</button>
</td>
</tr>
Utilize jQuery to its full potential to find elements (e.g. .find() and .closest()) and attach event handlers. document.getElementById and onclick attributes are so passé when it comes to jQuery.
Your code can be cleaner:
$('.edit_button').click(function () {
var tr = $(this).closest('tr'),
tdName = tr.find('td.name'),
tdAge = tr.find('td.age');
var id = tr.data('id'),
name = tdName.text(),
age = tdAge.text();
tdName.html('<input type="text" name="name" value="' + name + '">');
tdAge.html('<input type="text" name="age" value="' + age + '">');
tr.find('.edit_button').hide();
tr.find('.save_button').show();
});
$('.save_button').click(function () {
var tr = $(this).closest('tr'),
tdName = tr.find('td.name'),
tdAge = tr.find('td.age');
var id = tr.data('id'),
name = tdName.find('input').val(),
age = tdAge.find('input').val();
// shorthand method for $.ajax POST
$.post('modify_records.php', {
edit_row: 'edit_row',
row_id: id,
name_val: name,
age_val: age
}, function (response) {
if (response == "success") {
tdName.html(name);
tdAge.html(age);
tr.find('.edit_button').show();
tr.find('.save_button').hide();
}
});
});
$('.delete_button').click(function () {
var tr = $(this).closest('tr')
var id = tr.data('id');
$.post('modify_records.php', { delete_row: 'delete_row', row_id: id }, function (response) {
if (response == "success") {
tr.remove();
}
});
});
Quick demo
$('.edit_button').click(function() {
var tr = $(this).closest('tr'),
tdName = tr.find('td.name'),
tdAge = tr.find('td.age');
var id = tr.data('id'),
name = tdName.text(),
age = tdAge.text();
tdName.html('<input type="text" name="name" value="' + name + '">');
tdAge.html('<input type="text" name="age" value="' + age + '">');
tr.find('.edit_button').hide();
tr.find('.save_button').show();
});
$('.save_button').click(function() {
var tr = $(this).closest('tr'),
tdName = tr.find('td.name'),
tdAge = tr.find('td.age');
var id = tr.data('id'),
name = tdName.find('input').val(),
age = tdAge.find('input').val();
console.log('saving', id, name, age)
$.post('modify_records.php', {
edit_row: 'edit_row',
row_id: id,
name_val: name,
age_val: age
}, function(response) {
if (response == "success") {
tdName.html(name);
tdAge.html(age);
tr.find('.edit_button').show();
tr.find('.save_button').hide();
}
});
});
$('.delete_button').click(function() {
var tr = $(this).closest('tr')
var id = tr.data('id');
console.log('deleting', id)
$.post('modify_records.php', {
delete_row: 'delete_row',
row_id: id
}, function(response) {
if (response == "success") {
tr.remove();
}
});
});
.save_button {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr data-id="1">
<td class="name">Bill</td>
<td class="age">21</td>
<td>
<button type="button" class="edit_button">Edit</button>
<button type="button" class="save_button">Save</button>
<button type="button" class="delete_button">Delete</button>
</td>
</tr>
<tr data-id="2">
<td class="name">Sarah</td>
<td class="age">22</td>
<td>
<button type="button" class="edit_button">Edit</button>
<button type="button" class="save_button">Save</button>
<button type="button" class="delete_button">Delete</button>
</td>
</tr>
<tr data-id="3">
<td class="name">Jean</td>
<td class="age">34</td>
<td>
<button type="button" class="edit_button">Edit</button>
<button type="button" class="save_button">Save</button>
<button type="button" class="delete_button">Delete</button>
</td>
</tr>
</table>

$(.class).click(function(){}) not working [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 7 years ago.
I am facing problem in $(.class).click(function(){}); which is not working with my code.
Can any one help me on this.
My code is:
whenever i click on edit button popup div open but since click event not fire so text boxes in popup not filled due to which i am not able to update the record.
Please help me to resolve the issue:
$(document).ready(function(){
$(".btn-ed").click(function(e) {
try{
var $row = $(this).closest("tr");
var id = $row.find('td:eq(0)').text();
var className = $row.find('td:eq(1)').text();
var schoolName = $row.find('td:eq(2)').text();
var status = $row.find('td:eq(3)').text();
$("#txtId").val(id);
$("#txtClass").val(className);
$("#txtSchool").val(schoolName);
$("#ddlStatus").val((status=='Active'?'1':'0'));
}
catch(err){alert(err);}
});
$("#btnUpdate").click(function() {
var id = $('#txtId').val();
var status = $("#ddlStatus").val();
$.ajax({
cache: false,
type:"post",
url:"updateClass.php",
data: {cId: id, cStatus: status},
success:function(ret){
if(ret=='1')
{
location.reload(true);
window.location="?u=1&#close";
}
else
{
location.reload(true);
window.location="?u=0&#close";
}
}
});
});
});
$(document).ready(function(){
try{
getClassData();
var res = GetParameterValues('u');
var res1='';
if(res)
{
res1 = res.split('#')[0];
if(res1=='1')
{
$("#msg-inf").hide();
$("#msg-fail").hide();
$("#msg-sucess").show();
}
else
{
$("#msg-inf").hide();
$("#msg-fail").show();
$("#msg-sucess").hide();
}
}
}
catch(er){alert(er);}
function GetParameterValues(param) {
var url = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < url.length; i++) {
var urlparam = url[i].split('=');
if (urlparam[0] == param) {
return urlparam[1];
}
}
}
function getClassData(){
$.ajax({
cache: false,
type:"post",
url:"classdata.php",
datatype: 'json',
data: {qry: 'ClassData'},
success:function(ret){
var jobj = $.parseJSON(ret);
loadTable(jobj);
}
});
}
function loadTable(dt){
try{
var dLength = dt.length;
var tableData = '';
if(dLength > 0){
for(var i=0;i < dLength; i++){
tableData += "<tr class='data'><td class='data' width='30px'>"+dt[i].id+"</td><td class='data' width='70px'>"+dt[i].class_name+"</td><td class='data' width='70px'>"+dt[i].school_name+"</td><td class='data' width='60px'>"+(dt[i].is_active=='1'?'Active':'Deacive')+"</td><td class='data' width='70px'><a href='#openModal'><button id='button' class='btn-ed'>Edit</button></a></td></tr>";
}
$("#tblClass").append(tableData).show();
}
}
catch(err){alert(err);}
}
});
and HTML
<body>
<?php
include 'header.php';
?>
<div id="wrapper">
<?php include 'left-sidebar.php'; ?>
<div id="rightContent">
<h3>Classes</h3>
<div><div class='informational' id="msg-inf">To update status of any class click on Edit button.</div>
<div class='failure' id="msg-fail" style="display:none;">Class status changing failed due to some error.</div>
<div class='success' id="msg-sucess" style="display:none;">Class status successfully changed. Reload page to view changes</div>
</div>
<table class="data" id="tblClass" style="display:none;">
<tr class="data">
<th class="data" width="30px">No</th>
<th class="data" width="70px">Class Name</th>
<th class="data" width='70px'>School Name</th>
<th class="data" width='60px'>Status</th>
<th class="data" width="70px">Action</th>
</tr>
<!--<tr class="data">
<td class="data" width="30px"><?php echo $row['id'];?></td>
<td class="data" width="70px"><?php echo $row['class_name'];?></td>
<td class="data" width="70px"><?php echo $row['school_name'];?></td>
<td class="data" width="60px"><?php echo $status;?></td>
<td class="data" width="70px">
<button id="button" class="btn-ed">Edit</button>
</td>
</tr>-->
</table>
</div>
<div class="clear"></div>
<!-- modal dialog div --->
<div id="openModal" class="modalDialog">
<div> X
<h2>Update Class Status</h2>
<div style="text-align:center;">
<table width="100%">
<tr>
<td>Id</td>
<td><input type="text" id="txtId" disabled="true"></td>
</tr>
<tr>
<td>Class:</td>
<td><input type="text" id="txtClass" disabled="true"></td>
</tr>
<tr>
<td>School</td>
<td><input type="text" id="txtSchool" disabled="true"></td>
</tr>
<tr>
<td>Status</td>
<td><select id="ddlStatus"><option value="1">Active</option><option value="0">Deactive</option></select></td>
</tr>
<tr><td></td>
<td>
<button id="btnUpdate" class="button">Update</button>
Cancel
</td>
</tr>
</table>
</div>
</div>
</div>
Thanks in advance..
When dynamically adding an element to the DOM, you cannot attach an event handler to it on document.ready. You need to redefine you event handler to the document, and "look" for the element instead.
The handler should be:
$(document).on('click', '.btn-ed', function(e) {
try{
var $row = $(this).closest("tr");
var id = $row.find('td:eq(0)').text();
var className = $row.find('td:eq(1)').text();
var schoolName = $row.find('td:eq(2)').text();
var status = $row.find('td:eq(3)').text();
$("#txtId").val(id);
$("#txtClass").val(className);
$("#txtSchool").val(schoolName);
$("#ddlStatus").val((status=='Active'?'1':'0'));
}
catch(err){alert(err);}
});
You can try this:
$(document.body).on('click', '.btn-ed' ,function(e){
// your code
});

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
}

Updating table rows in datatables with jquery

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,
});

Categories

Resources