I have 3 different selectboxes. Second and third select boxes will be populated depending on first select boxes' value via ajax + php. But the response is not as i expected. It the shows error function. When i check it from the console there is no promlem with reading data from database as json format. But i'am unable to show these data as html to the screen. Here is my try:
HTML:
<table>
<tr>
<td valign="middle" align="center">
<label id="fieldOfBusinessLabel" for="fieldOfBusinessText">Field of Business</label>
</td>
<td valign="middle" align="center">
<select id="fieldOfBusinessSelectBox" class="selectBox" name="fieldOfBusinessSelectBox">
<option value="">--select--</option>
<?php
$result=mysqli_query($db,'SELECT * FROM field_of_business');
while($row=mysqli_fetch_assoc($result)) {
echo '<option value="'.$row["FobID"].'">'.$row['FobName'].'</option>';
}
?>
</select>
</td>
</tr>
<tr>
<td valign="middle" align="center">
<label id="typeOfProductionLabel" for="typeOfProductionText">Type of Production/Service</label>
</td>
<td valign="middle" align="center">
<select id="typeOfProductionSelectBox" clas="selectBox" name="typeOfProductionSelectBox">
<option value="">--select--</option>
</select>
</td>
</tr>
<tr>
<td valign="middle" align="center">
<label id="mainProductsLabel" for="mainProductsText">Main Products/Services</label>
</td>
<td valign="middle" align="center">
<select id="mainProductSelectBox" clas="selectBox" name="mainProductSelectBox">
<option value="">--select--</option>
</select>
</td>
</tr>
</table>
JS:
$(document).ready(function(){
$("#fieldOfBusinessSelectBox").change(function(){
var value = $("select#fieldOfBusinessSelectBox option:selected").val();
$.ajax({
type: 'POST',
url: 'listData.php',
dataType: "json",
data:{fobID:value},
success:function(answer){
var data1 = "<option>--select--</option>";
var data2 = "<option>--select--</option>";
$.each(answer, function(i, answer){
data1 += "<option>"+answer.TopsName+"</option>";
});
$.each(answer, function(i, answer){
data2 += "<option>"+answer.MpsName+"</option>";
});
$('#typeOfProductionSelectBox').html(data1);
$('#mainProductSelectBox').html(data2);
},
error:function(){
alert("An error has occured !");
}
});
});
});
PHP:
<?php
include './config.php';
if(strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest'){
die('Wrong request !');
}
$fobID = mysqli_real_escape_string($db,$_POST['fobID']);
if(isset($_POST['fobID'])){
$stmt1 = $db->prepare("SELECT TopsName FROM type_of_production_service WHERE FobID = ?");
if($stmt1 == "false"){
die('Query error !'.$db->error);
}
$stmt1->bind_param('i', $fobID);
$stmt1->execute();
$result = $stmt1 -> get_result();
$topsName = $result ->fetch_all(MYSQLI_BOTH);
echo json_encode($topsName);
$stmt2 = $db->prepare("SELECT MpsName FROM main_products_services WHERE FobID = ?");
if($stmt2 == "false"){
die('Query error !'.$db->error);
}
$stmt2->bind_param('i', $fobID);
$stmt2->execute();
$result2 = $stmt2 -> get_result();
$mpsName = $result2 ->fetch_all(MYSQLI_BOTH);
echo json_encode($mpsName);
}
$db->close();
You have 2 json_encoded strings in result and it not decoded. User one json object:
PHP:
echo json_encode(array('mps' => $mpsName, 'tops' => $topsName));
JS:
answer = $.parseJSON(answer);
$.each(answer.tops, function(k,v){...});
$.each(answer.mps, function(k,v){...});
Related
I am creating a small project to explain my students on how to update values in SQL database using PHP code. I have created table in MySQL with all the fields as VARCHAR. I have written the following code which throws following error :
Error in Updting valueYou have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Mbps WHERE dsl = '25610669'' at line 1 where 25610669 is an existing record in the database. Here is the code:
<?php
if((isset($_POST['B2'])))
{
$server = 'localhost' ;
$un = 'root' ;
$pass = 'icsk' ;
$db = 'yusuf' ;
$conn = mysqli_connect($server, $un, $pass, $db);
$update = "UPDATE homereg SET Fname = {$_POST['First']}, Lname = {$_POST['Last']}, cid = {$_POST['cid']}, pack = {$_POST['choice']} WHERE dsl = {$_POST['dsl']}" ;
$result = mysqli_query($conn, $update);
if($result == 1)
{
echo "Successfully Updated" ;
}
else
{
echo "Error in Updting value" . mysqli_error($conn) ;
}
}
?>
<html>
<head>
<title>Update User Information</title>
</head>
<body background="HomePageMap.gif">
<CENTER><B><FONT COLOR = 'RED'>SEARCH & UPDATE THE EXISTING RECORD HERE </FONT></B></CENTER><P>
<form method="POST" action="modify.php" name = "frm">
<div align="center">
<table border="1" width="314">
<tr>
<td width="130"><b>DSL Number</b></td>
<td width="168"><input type="text" name="dsl" size="20"></td>
</tr>
<tr>
<td width="130"><b>First Name</b></td>
<td width="168"><input type="text" name="First" size="20"></td>
</tr>
<tr>
<td width="130"><b>Last Name</b></td>
<td width="168"><input type="text" name="Last" size="20"></td>
</tr>
<tr>
<td width="130"><b>Civil ID</b></td>
<td width="168"><input type="text" name="cid" size="20"></td>
</tr>
<tr>
<td width="130"><b>Net Pack</b></td>
<td width="168"><select size="1" name="choice">
<option value = "2 Mbps">2 Mbps</option>
<option value = "5 Mbps">5 Mbps</option>
<option value = "10 Mbps">10 Mbps</option>
<option value = "15 Mbps">15 Mbps</option>
</select></td>
</tr>
</table>
</div>
<p align="center"><input type="submit" value="Search" name="B1">
<p align="center"><input type="submit" value="Modify" name="B2">
<input type="reset" value="Reset" name="B2"></p>
</form>
<p align="center"> </p>
</body>
</html>
If answer below me not work, try this:
$update = "UPDATE homereg SET Fname = `$_POST['First']}`, Lname = `$_POST['Last']`, cid = `$_POST['cid']`, pack = `$_POST['choice']` WHERE dsl = `$_POST['dsl']`" ;
You have to put quotes around strings like this:
$update = "UPDATE homereg SET Fname = '{$_POST['First']}', Lname = '{$_POST['Last']}', cid = '{$_POST['cid']}', pack = '{$_POST['choice']}' WHERE dsl = '{$_POST['dsl']}'" ;
Also, not sure if you left it out because it's just an example, but you'll want to escape your POST values to protect against SQL injection like so:
$first = mysqli_real_escape_string($conn, $_POST['First']);
I tried to update 1 row in table with ajax triggered by onchange dropdown, I succeed update data but it updating all data in my table.
so how I can get unique value (eg :User ID) to pass it from ajax to my php so i can update it only 1 row?
here's my code :
my table (transactions.php)
<table class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th>User ID</th>
<th>Pengirim</th>
<th>Jumlah Transfer</th>
<th>Berita Acara</th>
<th>Status</th>
<th>Rincian</th>
</tr>
</thead>
<tbody>
<?php
$query = mysqli_query($koneksi, "select * from konf_transf order by tanggal desc limit 7 ");
while($data1 = mysqli_fetch_array($query)){
?>
<tr>
<td>
<center><?php echo $data1['usr_id']; ?></center>
</td>
<td>
<center><?php echo $data1['nm_pengirim']; ?></center>
</td>
<td>
<center>Rp. <?php echo number_format($data1['jmlh_transf'],0,'','.'); ?>,-</center>
</td>
<td>
<center><?php echo $data1['berita_acara']; ?></center>
</td>
<td>
<center><?php echo $data1['status']; ?></center>
</td>
<td>
<center>
<select name="pilihstatus" id="pilihstatus" onchange="updatetransactions();">
<option value="Pilihan">Pilihan</option>
<option value="Sudah">Sudah</option>
<option value="Belum">Belum</option>
</select>
</center>
</td>
</tr>
<?php } ?>
</tbody>
</table>
and here my ajax
function updatetransactions(){
var id = $('select option:selected').val();
$.ajax({
type:"post",
url:"updatestatustransaksi.php",
data:"status="+id,
success:function(data){
alert('Successfully updated mysql database');
}
});
}
my updatestatustransaksi.php
<?php
require_once("koneksi.php");
session_start();
if (!isset($_SESSION['username'])) {
echo "<script>alert('You must register an account first, we will redirect you to register page !'); window.location = 'registuser.php'</script>";
}
$dataupd = $_POST["status"];
$query = mysqli_query($koneksi, "UPDATE `konf_transf` SET `status` = '$dataupd' WHERE `id` = '$penjualan_id'");
if ($query) {
echo "<script>alert('Update Success.'); window.location = 'transactions.php' </script>";
} else {
echo "<script>alert('Update Failure.'); window.location = 'transactions.php' </script>";
}
I assume that you update all of your rows in your database, with no WHERE condition. In your script, lets also get the corresponding id of that row in your database.
Lets assign first the id for each table row:
while($data1 = mysqli_fetch_array($query)){
?>
<tr id="<?=($data1['user_id'])?>">
Then, lets change how you trigger your javascript. Lets first change the <select> field:
<select name="pilihstatus" id="pilihstatus" class="pilihstatus">
Then, get the corresponding id using the script below:
$(".pilihstatus").change(function(){
var elem = $(this),
selecteditem = elem.val(),
id = elem.closest('tr').attr('id');
$.ajax({
type:"post",
url:"updatestatustransaksi.php",
data: {'status':selecteditem, 'id':id},
success:function(data){
alert('Successfully updated mysql database');
}
});
});
And on your updatestatustransaksi.php file (please use prepared statement):
$stmt = $koneksi->prepare("UPDATE `konf_transf` SET `status` = ? WHERE `id` = ?");
$stmt->bind_param("si", $_POST['selecteditem'], $_POST['id']);
$stmt->execute();
$stmt->close();
Try adding data_id attribute to select
<table class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th>User ID</th>
<th>Pengirim</th>
<th>Jumlah Transfer</th>
<th>Berita Acara</th>
<th>Status</th>
<th>Rincian</th>
</tr>
</thead>
<tbody>
<?php
$query = mysqli_query($koneksi, "select * from konf_transf order by tanggal desc limit 7 ");
while($data1 = mysqli_fetch_array($query)){
?>
<tr>
<td>
<center><?php echo $data1['usr_id']; ?></center>
</td>
<td>
<center><?php echo $data1['nm_pengirim']; ?></center>
</td>
<td>
<center>Rp. <?php echo number_format($data1['jmlh_transf'],0,'','.'); ?>,-</center>
</td>
<td>
<center><?php echo $data1['berita_acara']; ?></center>
</td>
<td>
<center><?php echo $data1['status']; ?></center>
</td>
<td>
<center>
<select name="pilihstatus" id="pilihstatus" onchange="updatetransactions();" data_id='<?php echo $data1['usr_id']; ?>'>
<option value="Pilihan">Pilihan</option>
<option value="Sudah">Sudah</option>
<option value="Belum">Belum</option>
</select>
</center>
</td>
</tr>
<?php } ?>
</tbody>
</table>
and get that data_id value in your function
function updatetransactions(){
var status = $('select option:selected').text();
var status = $('select').attr('data_id');
var id = $('select option:selected').val();
$.ajax({
type:"post",
url:"updatestatustransaksi.php",
data:{'status'=status,'id'=id}
success:function(data){
alert('Successfully updated mysql database');
}
});
}
and at your updatestatustransaksi.php
<?php
require_once("koneksi.php");
session_start();
if (!isset($_SESSION['username'])) {
echo "<script>alert('You must register an account first, we will redirect you to register page !'); window.location = 'registuser.php'</script>";
}
$dataupd = $_POST["status"];
$id = $_POST["id"];
$query = mysqli_query($koneksi, "UPDATE `konf_transf` SET `status` = '$dataupd' WHERE `id` = '$id'");
if ($query) {
echo "<script>alert('Update Success.'); window.location = 'transactions.php' </script>";
} else {
echo "<script>alert('Update Failure.'); window.location = 'transactions.php' </script>";
}
Have you initialised $penjualan_id? I think you need to initialise it like this:
$penjualan_id=$_SESSION['user_id']
We have a .aspx page with two HTML SELECT element and we want to load countries in one dropdownlist and load cities of a country in the other.
we are using entity framework to access data.
I tried PageMethods and &Ajax but I could not access my city dropdown from within a static web method. this is what we have so far:
<!-- Signup.aspx-->
<select id="cmb_Region" runat="server" onchange="GetCitiesOfRegion();" datatextfield="region_title" datavaluefield="region_id"></select>
<select runat="server" id="cmb_City" datatextfield="city_title" datavaluefield="city_id" class="ui dropdown"></select>
<script type="text/javascript">
function GetCitiesOfRegion(regionId)
{
$.ajax({
url:"Signup.aspx/GetCities",
type:"POST",
data:'{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
alert("success");
}
});
}
</script>
and this is code-behind code:
//Signup.aspx.cs
[WebMethod]
public static List<City> GetCities(int RegionId)
{
behbimeh_informationEntities db = new behbimeh_informationEntities();
return db.City.Where(i => i.region_id == RegionId).ToList();
}
Actually the code is not correct and I dont know how to pass the cmb_region selected value to the webmethod? and I dont know how to bind the cmb_city to the returned List of cities.
please share your knowledge. thanks...
To get cmb_Region value
var regionId = $('#<%= cmb_Region.ClientID %>').val();
To get cities by region and bind at client side
[WebMethod]
public static string GetCities(int RegionId)
{
behbimeh_informationEntities db = new behbimeh_informationEntities();
var cities= db.City.Where(i => i.region_id == RegionId).Select(item=>new { item.ValueField, item.TextField }).ToList();
return Newtonsoft.Json.JsonConvert.SerializeObject(cities);
}
<script type="text/javascript">
function GetCitiesOfRegion(regionId)
{
$.ajax({
url:"Signup.aspx/GetCities",
type:"POST",
data:'{"RegionId":'+regionId+'}',
success: function (r) {
var cities=JSON.parse(r.d);
var citiesOptions="";
for(var i=0;i<cities.length;i++){
citiesOptions+='<option value="'+cities[i].Value+'">'+cities[i].Text+'</option>';
}
$('#<%= cmb_City.ClientID %>').html(citiesOptions);
}
});
}
first you will need to clear the existing data, like so:
$('#cmb_city').empty();
next, you need to load the returned list to your ddl.
$.ajax({
url:"Signup.aspx/GetCities",
type:"POST",
data:'{"RegionId":'+$('#cmb_Region').val()+'}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
$.each(r, function() {
$('#cmb_city').append($('<option>').text(this.Name).attr('value', this.Id));
});
}
});
where Name and Id are your text and value fields respectively.
you will also probably need to send the selected region.
Here is your answer like how to bind data from database using Ajax in php
<!-- edit.php -->
<?php
include("config.php");
$id=$_REQUEST['id'];
echo $id;
$query=mysqli_query($con,"SELECT * FROM register r
INNER JOIN country c ON r.cuid = c.cuid
INNER JOIN state s ON r.sid = s.sid
INNER JOIN city ct ON r.cid = ct.cid where id='$id'");
while($r=mysqli_fetch_array($query))
{
$fn=$r['firstname'];
$add=$r['address'];
$gn=$r['gender'];
$hobby=$r['hobby'];
$h=explode(',',$hobby);
$q=array('reading','traveling','cricket','drawing');
$country=$r['cuid'];
$state=$r['sid'];
$city=$r['cid'];
echo $gn;
$edu= $r['education'];
$email=$r['email'];
$pass=$r['password'];
$conpass=$r['conpassword'];
$phno=$r['phoneno'];
}
?>
<html>
<head>
<script src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#country').on('change',function(){
var countryID = $(this).val();
if(countryID){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'cuid='+countryID,
success:function(html){
$('#state').html(html);
$('#city').html(html);
}
});
}else{
$('#state').html(html);
$('#city').html(html);
}
});
$('#state').on('change',function(){
var stateID = $(this).val();
if(stateID){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'sid='+stateID,
success:function(html){
$('#city').html(html);
}
});
}else{
$('#city').html(html);
}
});
});
</script>
</head>
<body>
<form method="post" action="update.php">
<table border="1" align="center">
<caption>Edit user data</caption>
<tr>
<td>First name</td>
<td><input type="text" name="fn" value="<?php echo $fn;?>"></td>
</tr>
<tr>
<td>Address</td>
<td><input type="text" name="add" value="<?php echo $add;?>"></td>
</tr>
<tr>
<td>Gender</td>
<td><input type="radio" name="gn" value="male" <?php echo ($gn=='male')?'checked':'' ; ?> size="17">Male
<input type="radio" name="gn" value="female" <?php echo ($gn=='female')?'checked':'' ; ?> size="17">Female
</td>
</tr>
<tr>
<td>Hobby</td>
<td><input type="checkbox" name="hobby[]" value="reading" <?php if(in_array('reading',$h)){echo ("checked:'checked'");}?> >reading
<input type="checkbox" name="hobby[]" value="traveling" <?php if(in_array('traveling',$h)){echo ("checked:'checked'");}?> >traveling
<input type="checkbox" name="hobby[]" value="cricket" <?php if(in_array('cricket',$h)){echo ("checked:'checked'");}?> >cricket
<input type="checkbox" name="hobby[]" value="drawing" <?php if(in_array('drawing',$h)){echo ("checked:'checked'");}?> >drawing</td>
</tr>
<?php
$query = mysqli_query($con,"SELECT * FROM country");
//Count total number of rows
$rowCount = mysqli_num_rows($query);
?>
<td>Country</td>
<td><select name="country" id="country">
<option value="<?php echo $country;?>"><?php echo $country;?></option>
<?php
if($rowCount > 0)
{
while($row = mysqli_fetch_array($query))
{
echo '<option value="'.$row['cuid'].'">'.$row['country'].'</option>';
}
}
else
{
echo '<option value="">Country not available</option>';
}
?>
</select>
</td></tr>
<tr>
<td>State</td>
<td>
<select name="state" id="state">
<option value="<?php echo $state;?>"><?php echo $state;?></option>
</select>
</td></tr>
<tr>
<td>City</td>
<td>
<select name="city" id="city">
<option value="<?php echo $city;?>"><?php echo $city;?></option>
</select>
</td>
</tr>
<tr>
<td>Education</td>
<td><input type="text" name="edu" value="<?php echo $edu;?>"></td>
</tr>
<td>Email</td>
<td><input type="text" name="email" value="<?php echo $email;?>"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="text" name="pass" value="<?php echo $pass;?>"></td>
</tr>
<tr>
<td>Confirm password</td>
<td><input type="text" name="conpass" value="<?php echo $conpass;?>"></td>
</tr>
<tr>
<td>Phone no</td>
<td><input type="text" name="phno" value="<?php echo $phno;?>"></td>
</tr>
<tr>
<td><input type="hidden" name="id" value="<?php echo $id;?>">
<input type="submit" name="update" value="update"></td>
</tr>
</table>
</form>
</body>
</html>
--------------------
<!--ajaxData.php-->
<?php
//Include database configuration file
include("config.php");
if(isset($_POST["cuid"]) && !empty($_POST["cuid"]))
{
//Get all state data
$query = mysqli_query($con,"SELECT * FROM state WHERE cuid = ".$_POST['cuid']."");
//Count total number of rows
$rowCount = mysqli_num_rows($query);
//Display states list
if($rowCount > 0)
{
echo '<option value="">Select state</option>';
while($row = mysqli_fetch_array($query))
{
echo '<option value="'.$row['sid'].'">'.$row['state'].'</option>';
}
}
else
{
echo '<option value="">State not available</option>';
}
}
if(isset($_POST["sid"]) && !empty($_POST["sid"]))
{
//Get all city data
$query = mysqli_query($con,"SELECT * FROM city WHERE sid =".$_POST['sid']."");
//Count total number of rows
$rowCount = mysqli_num_rows($query);
//Display cities list
if($rowCount > 0)
{
echo '<option value="">Select city</option>';
while($row = mysqli_fetch_array($query))
{
echo '<option value="'.$row['cid'].'">'.$row['city'].'</option>';
}
}
else
{
echo '<option value="">City not available</option>';
}
}
?>
I am trying to figure out how to submit button with two actions based on dropdown list that I get from MySQL. One is for updating to database and then proceed to nextpage while the other actions is to proceed to specific page. I've tried all the solution but most of them only has a few dropdown menu, mine have 40 menus.
This is my JavaScript
<script type='text/javascript'>
$(window).load(function(){
//$(document).ready(function() {
<!--To Enable button "MULA"-->
$('#lst_respon').change(function() {
if ($(this).find(":selected").val()!='11') {
$('#button').attr('disabled',true);
} else {
$('#button').removeAttr('disabled');
}
});
$('#lst_respon').change(function()
{
$('#form1').submit();
});
});
function changeTextBox()
{
var val=$('#lst_respon').val();
if(val==='11')
{
$('#value').prop('disabled', true);
}
else{$('#value').removeAttr("disabled");}
}
</script>
And this is my HTML
<div align="center">
<table width="60%" border="1" class="zui-table">
<thead>
<tr>
<th colspan="3" align="center">Status</th>
</tr>
</thead>
<tr>
<?php
$smt = $conn->prepare('select * From lookup_caraterima');
$smt->execute();
$data = $smt->fetchAll();
$smt2 = $conn->prepare('select * From lookup_kodrespon');
$smt2->execute();
$data2 = $smt2->fetchAll();
?>
<td width="253">Cara Terima</td>
<td width="5">:</td>
<td width="164">
<select name="lst_cterima" id="lst_cterima">
<?php foreach ($data as $row): ?>
<option value="<? echo $row["kodterima"];?>"><? echo $row["jenis"];?>
</option>
<?php endforeach ?>
</select>
</td>
</tr>
<tr>
<td>Kod Respon</td>
<td>:</td>
<td>
<select name="lst_respon" id="lst_respon" onchange="changeTextBox()">
<?php foreach ($data2 as $row2): ?>
<option value="<? echo $row2["kod"];?>"><? echo $row2["kod"].'- '.$row2 ["Keterangan"];?></option>
<?php endforeach ?>
</select></td>
</tr>
<tr>
<td><label for ="sebab">Sebab</label></td>
<td>:</td>
<td><input type="textbox" id="value" size="100" disabled</td>
</tr>
<tr>
<td colspan="3" align="center"><form name="form1" method="post" action="main.php?load=4&SerialID=<?php echo $noSiri; ?>&month=<?php echo $monthA;?>&year=<?php echo $yearA;?>&tab=A">
<input type="submit" name="button" id="button" value="Teruskan" class="myButton">
</form></td>
</tr>
</table>
</div>
For an automated solution to submit a form based a dropdown selection, you could try using the data attribute, something like:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<form id="tester">
<select name="test">
<option value="best" data-instructions='<?php echo json_encode(array('action'=>'page1')); ?>'>Best</option>
<option value="rest" data-instructions='<?php echo json_encode(array('action'=>'page2')); ?>'>Rest</option>
<option value="guest" data-instructions='<?php echo json_encode(array('action'=>'page3')); ?>'>Guest</option>
<option value="lest" data-instructions='<?php echo json_encode(array('action'=>'page4')); ?>'>Lest</option>
</select>
<input type="submit" name="submit" value="SUBMIT" />
</form>
<script>
$(document).ready(function() {
$('#tester').submit(function(e) {
// Stop form from submitting
e.preventDefault();
// Get the select dropdown
var thisSelect = $(this).find('select[name=test]');
// Get the value
var thisVal = thisSelect.val();
// Get the options separately
var thisOpts = thisSelect.children();
// Create a holder
var thisData = {};
// Loop through the options
$.each(thisOpts,function(k,v) {
// Get the current value
var currVal = $(v).attr('value');
// If the current value is the same as the value selected
if(currVal == thisVal) {
// Get the instructions from the option
thisData = $(v).data('instructions');
// Stop looping
return false
}
});
console.log(thisData);
});
});
</script>
On submission, the selection will give you an object that you can use to instruct how to submit the form:
// thisData.action
{action: "page2"}
I have a table like the following:
<script>
$("#edit").hide(); // Hide the edit table first
$("#update").click(function() {
$("#edit").toggle();
$("#shown").toggle();
// If we are going from edit table to shown table
if($("#shown").is(":visible")) {
var vouchertype = $('input[name="vouchertype[]"]').map(function(){return $(this).val();}).get();
var mode= $('select[name="mode[]"]').map(function(){return $(this).val();}).get();
// Then add it to the shown table
var baseurl='<?php echo base_url()."index.php/account/insert_voucher";?>';
$.ajax({
type: "POST",
url: baseurl,
data: $('#edit *').serialize() ,
cache: false,
success: function(html) {
alert(html);
}
});
$(this).val("Edit");
}
else $(this).val("Update");
});
</script>
<table width="62%" height="70" border="1" cellpadding="0" cellspacing="0" class="tbl_grid" id="shown">
<?php if(count($voucher_info) > 0 ){ ?>
<tr class="bgcolor_02">
<td width="22%" height="25" align="center" class="admin" >S.no</td>
<td width="37%" align="center" class="admin">Voucher Type</td>
<td width="37%" align="center" class="admin">Voucher Mode</td>
</tr>
<?php
$rownum = 1;
foreach ($voucher_info as $eachrecord){
$zibracolor = ($rownum%2==0)?"even":"odd";
?>
<tr align="center" class="narmal">
<td height="25"><?php echo $eachrecord->voucher_id; ?></td>
<td><?php echo $eachrecord->voucher_type; ?></td>
<td><?php echo ucwords($eachrecord->voucher_mode); ?></td>
</tr>
<?php }
}
else {
echo "<tr class='bgcolor_02'>";
echo "<td align='center'><strong>No records found</strong></td>";
echo "</tr>";
}
?>
</table>
<table width="62%" height="70" border="1" cellpadding="0" cellspacing="0"
id="edit">
<?php if(count($voucher_info) > 0 ){ ?>
<tr class="bgcolor_02">
<td width="27%" align="center" class="admin" >S.no</td>
<td width="37%" align="center" class="admin" >Voucher Type</td>
<td width="47%" align="center" class="admin" >Voucher Mode</td>
<!-- <td width="41%" align="center" class="narmal"> <strong>Actions</strong></td>-->
</tr>
<?php
$rownum = 1;
foreach ($voucher_info as $eachrecord){
$zibracolor = ($rownum%2==0)?"even":"odd";
?>
<tr align="center" class="narmal">
<td height="25"><?php echo $eachrecord->voucher_id ; ?><input type="hidden" name="voucher_id[]" value="<?php echo $eachrecord->voucher_id; ?>" /></td>
<td><input name="vouchertype[]" type="text" value="<?php echo $eachrecord->voucher_type; ?>" /></td>
<td><select name="mode[]" >
<option value="paidin" <?php if($eachrecord->voucher_mode=='paidin') { ?> selected="selected" <?php } ?>>Paid In</option>
<option value="paidout" <?php if($eachrecord->voucher_mode=='paidout') { ?> selected="selected" <?php } ?>>Paid Out</option>
</select></td>
</tr>
<?php } }
else {
echo "<tr class='bgcolor_02'>";
echo "<td align='center'><strong>No records found</strong></td>";
echo "</tr>";
}
?>
</table>
</td>
</tr>
<input id="update" type="submit" name="submit" value="Edit"/
In first table I am displaying values from database. But when user click on edit button below the table, Then that table values should be editable for user. I have succeeded in making editable fields but again when user click on submit then updated values are not displaying in first table. I know it's possible with jQuery or JavaScript. When I alert(newsales), the alert is undefined.
An easy way to handle this would be have two separate tables, and toggle between them when you edit a table. So for example we have a table that shows our normal data called shown and one with the input and select for a user to enter data called edit. These tables will share the same button, and when clicked it will toggle between the tables, making it look like it's switching between edit and show mode. This way we can just copy the values from the edit table to the text in the shown table. Here is an example:
$("#edit").hide(); // Hide the edit table first
$("#update").click(function() {
$("#edit").toggle();
$("#shown").toggle();
// If we are going from edit table to shown table
if($("#shown").is(":visible")) {
// Get the data from the edit table
var newSales = $("#edit tr:nth-child(1) td input[name='vouchertype']").val();
var newPay = $("#edit tr:nth-child(1) td select[name='mode']").val();
var newTax = $("#edit tr:nth-child(2) td select[name='tax']").val();
// Then add it to the shown table
$("#shown tr:nth-child(1) td:nth-child(2)").text(newSales);
$("#shown tr:nth-child(1) td:nth-child(3)").text(newPay);
$("#shown tr:nth-child(2) td:nth-child(1)").text(newTax);
$(this).val("Edit");
}
else $(this).val("Update");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="shown">
<tr>
<td>Sr no</td><td>Sales</td><td>Paid in</td>
</tr>
<tr><td>Taxed</td></tr>
</table>
<table id="edit">
<tr>
<td>Sr no</td><td><input type="text" name="vouchertype" value="Sales" /></td>
<td>
<select name="mode">
<option value="paidin">Paidin</option>
<option value="paidout">Paidout</option>
</select>
</td>
</tr>
<tr>
<td>
<select name="tax">
<option value="Taxed">Taxed</option>
<option value="Not Taxed">Not Taxed</option>
</select>
</td>
</tr>
</table>
<input id="update" type="submit" name="submit" value="Edit"/>
Notice: This is an answer to the original question, which is quite different then the new question added in as an edit.