I have a PHP file which shows the entries of a specific id within a SQL table. Now i want to be able to delete entries and show the updated table without a page reload.
Iam trying my best with a solution via AJAX, but no matter which entry i choose to delete, everytime only the one at the top gets deleted.
I hope someone has clue why this happens.
Here is my show.php:
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$('.btn-primary').click(function (e) {
e.preventDefault();
var belegnrdel = $('#belegnrdel').val();
var iddel = $('#iddel').val();
$.ajax
({
type: "POST",
url: "del.php",
data: { "iddel": iddel, "belegnrdel": belegnrdel},
success: function (data) {
$('#showtabelle').html(data);
}
});
});
});
</script>
</html>
<?php
// Includes
require_once '../../admin/config/database.php';
require_once '../../admin/config/dbconfig.php';
require_once './config.php';
echo "<div id='showtabelle'>";
$select = $db->query(" SELECT
belegnr,
gewicht,
id FROM
tabelle2
WHERE id='$transitnr'
ORDER BY belegnr DESC");
$nachrichten = $select->fetchAll(PDO::FETCH_OBJ);
$summe = mysqli_query($dbi, " SELECT
SUM(gewicht) AS gewicht_summe
FROM tabelle2
WHERE id='$transitnr'");
$summeausgabe = mysqli_fetch_assoc($summe);
$sum = $summeausgabe['gewicht_summe'];
echo " <div class='form'>
<h1><b>Transitnummer:</b> $transitnr</h1>";
echo " <table>
<thead>
<tr>
<th>Belegnummer:</th>
<th>Gewicht:</th>
<th>Delete:</th>
</tr>
</thead>
<tbody>";
foreach($nachrichten as $nachricht) {
echo " <tr>
<td>$nachricht->belegnr<hr></td>
<td>$nachricht->gewicht kg<hr></td>
<td>
<form method='post' action='' id='contactform'>
<input type='hidden' class='form-control' id='belegnrdel' value='" . $nachricht->belegnr . "'>
<input type='hidden' class='form-control' id='iddel'' value='" . $transitnr . "'>
<button type='submit' class='btn btn-primary'>Submit</button>
</form> </td>";
}
echo " </tr>
</tbody>
</table>";
echo " <br><br>
<b><u><align='left'>Gesamtgewicht: $sum kg </u></b>";
echo "</div></div>";
?>
This is my del.php:
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$('.btn-primary2').click(function (e) {
e.preventDefault();
var belegnrdel = $('#belegnrdel').val();
var iddel = $('#iddel').val();
$.ajax
({
type: "POST",
url: "del.php",
data: { "iddel": iddel, "belegnrdel": belegnrdel},
success: function (data) {
$('#showtabelle').html(data);
}
});
});
});
</script>
</html>
<?php
// Includes
require_once '../../admin/config/database.php';
require_once '../../admin/config/dbconfig.php';
require_once './config.php';
if(isset($_POST["iddel"]))
{
$transitnr = $_POST['iddel'];
$belegnummerdel = $_POST['belegnrdel'];
echo $belegnummerdel;
$query = " DELETE
FROM tabelle2
WHERE id='".$transitnr."' AND belegnr='".$belegnummerdel."'";
$result = mysqli_query($dbi, $query) or die ( mysqli_error($dbi));
}
$output = '';
$select = $db->query(" SELECT
belegnr,
gewicht,
id
FROM tabelle2
WHERE id='$transitnr'
ORDER BY belegnr DESC");
$nachrichten = $select->fetchAll(PDO::FETCH_OBJ);
$summe = mysqli_query($dbi, " SELECT
SUM(gewicht) AS gewicht_summe
FROM tabelle2
WHERE id='$transitnr'");
$summeausgabe = mysqli_fetch_assoc($summe);
$sum = $summeausgabe['gewicht_summe'];
$output .= "
<div class='form'>
<h1><b>Transitnummer:</b> $transitnr</h1>
<table>
<thead>
<tr>
<th>Belegnummer:</th>
<th>Gewicht:</th>
<th>Delete:</th>
</tr>
</thead>
<tbody>";
foreach($nachrichten as $nachricht) {
$output .= " <tr>
<td>$nachricht->belegnr<hr></td>
<td>$nachricht->gewicht kg<hr></td>
<td><form method='post' action='' id='contactform'>
<input type='text' class='form-control' id='belegnrdel' value='" . $nachricht->belegnr . "'>
<input type='text' class='form-control' id='iddel'' value='" . $transitnr . "'>
<button type='submit' class='btn btn-primary2'>Submit</button>
</form> </td>";
}
$output .= " </tr>
</tbody>
</table>";
$output .= " <br><br>
<b><u><align='left'>Gesamtgewicht: $sum kg </u></b>";
echo $output;
?>
The show.php is included in a another file, where it gets the variables like $transitnr.
You cannot use same id for mutliple elements instead use class then you can use .closest() and .find() method to get required input values and then send same to your backend.
Demo Code :
$(document).ready(function() {
$('.btn-primary').click(function(e) {
e.preventDefault();
//get closest tr and then find inputs
var belegnrdel = $(this).closest("tr").find('.belegnrdel').val();
var iddel = $(this).closest("tr").find('.iddel').val();
console.log("belegnrdel -- " + belegnrdel + " || iddel--" + iddel)
//your ajaxcall
});
});
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<div id='showtabelle'>
<div class='form'>
<h1><b>Transitnummer:</b> $transitnr</h1>
<table>
<thead>
<tr>
<th>Belegnummer:</th>
<th>Gewicht:</th>
<th>Delete:</th>
</tr>
</thead>
<tbody>
<tr>
<td>12
<hr>
</td>
<td>1222
<hr>
</td>
<td>
<form method='post' action='' id='contactform'>
<!--added class-->
<input type='hidden' class='form-control belegnrdel' value='12'>
<input type='hidden' class='form-control iddel' value='1 '>
<button type='submit ' class='btn btn-primary '>Submit</button>
</form>
</td>
</tr>
<tr>
<td>1ss
<hr>
</td>
<td>somethinss
<hr>
</td>
<td>
<form method='post' action='' id='contactform'>
<!--added class-->
<input type='hidden' class='form-control belegnrdel' value='1'>
<input type='hidden' class='form-control iddel' value='2 '>
<button type='submit ' class='btn btn-primary '>Submit</button>
</form>
</td>
</tr>
</tbody>
</table>
Related
for my dissertation I need to categorize images. The image links are stored in table "ocr". In my search page I am showing all the images in rows. Using AJAX I am searching Table "diss_kategorien" and showing the results in a dropdown in the table OCR. Now I need to update table ocr with the results, but I do not know how to pass the variable from the row with the current image which I am processing
This is my search page:
<div class="card-body">
<table width="95%" class="table table-bordered tablehover">
<tr>
<th width="40">ID</th>
<th>Image</th>
<th width="200">Hauptgegenstand</th>
<th width="130">Save</th>
<th width="137">Löschen</th>
<th width="137">Update</th>
</tr>
<?php
foreach($result as $r)
{
?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" enctype="application/x-www-form-urlencoded">
<tr>
<td><input readonly name="id" type="text" class="form-control input-sm" value="<?php echo($r->id); ?>" id="id" /></td>
<td width="232"><img style="max-width: 400px" src="uploads/<?php echo($r->file_name);?>"></td>
<td>
<input type="text" name="search" id="search" autocomplete="off" placeholder="Gegenstand suchen">
<div id="output"></div>
</td>
</div>
<td><input type="submit" class="btn btn-primary" name="submit"></td>
<td><input type="submit" class="btn btn-primary" name="delete"></td>
<td width="5%">Update </td>
</tr>
</form>
<?php }?>
</table>
</div>
Here is the AJAX Code:
<script type="text/javascript">
$(document).ready(function(){
$("#search").keyup(function(){
var query = $(this).val();
if (query != "") {
$.ajax({
url: 'ajax-db-search.php',
method: 'POST',
data: {query:query},
success: function(data){
$('#output').html(data);
$('#output').css('display', 'block');
$("#search").focusout(function(){
$('#output').css('display', 'none');
});
$("#search").focusin(function(){
$('#output').css('display', 'block');
});
}
});
} else {
$('#output').css('display', 'none');
}
});
});
</script>
And here is my ajax-db-show.php
$conn=mysqli_connect($servername,$username,$password,$dbname);
mysqli_query($conn,"SET CHARACTER SET 'utf8'");
mysqli_query($conn,"SET SESSION collation_connection ='utf8_unicode_ci'");
if(!$conn){
die('Could not Connect MySql Server:' .mysql_error());
}
if (isset($_POST['query'])) {
$val = '%' . $_POST['query'] . '%';
$stmt = $conn->prepare("SELECT * FROM diss_kategorien WHERE ebene_1_txt LIKE ? OR ebene_2_txt LIKE ? or ebene_3_txt like ?");
$stmt->bind_param("sss", $val, $val, $val);
$stmt->execute();
$result = $stmt->get_result();
if (mysqli_num_rows($result) > 0) {
while ($user = mysqli_fetch_array($result)) {
// echo "Ebene 1: " . $user['ebene_1_txt']. "Ebene 2: " . $user['ebene_2_txt'] . "Ebene 3: ". $user['ebene_3_txt'] ."<br/>";
print "<td><a href='show_ocr_files_mainitem.php?param1=" . $user['ebene_1_nr'] . "¶m2=" . $user['ebene_2_nr'] . "¶m3=" .$user['ebene_3_nr']. "¶m4=" .$_POST['id']."'>ID: " . $_POST['id'] . " Ebene 1: " . $user['ebene_1_txt']. " Ebene 2: " . $user['ebene_2_txt'] . " Ebene 3: ". $user['ebene_3_txt'] . "<br/></a></td>";
}
} else {
echo "<p style='color:red'>Nichts gefunden..</p>";
}
When I type in a Search Term into field "Hauptgegenstand" I generate an hyperlink which should pass the Variables to the search page to update the table OCR:
print "<td><a href='show_ocr_files_mainitem.php?param1=" . $user['ebene_1_nr'] . "¶m2=" . $user['ebene_2_nr'] . "¶m3=" .$user['ebene_3_nr']. "¶m4=" .$_POST['id']."'>ID: " . $_POST['id'] . " Ebene 1: " . $user['ebene_1_txt']. " Ebene 2: " . $user['ebene_2_txt'] . " Ebene 3: ". $user['ebene_3_txt'] . "<br/></a></td>";
When I use ID of the search result for the update, then it is wrong, because I need the ID of the OCR table
I tried with
data: {query:query, id: <?php echo $r->id; ?>},
But the shown ID is 470 instead of 111. I do not get the ID of the OCR Field where I am doing the Search, I only get the ID of the last entry in the search of the OCR table. I have limited the search to 50 and so the last ID is 470
So I am getting the correct search results, but I am not aware how to pass the ID of the Table OCR to the Ajax file and from there back to the search page to update the table OCR.
Thank you for your help and advice how to solve this.
All the best,
Stefan
You cannot use same id for mutiple elements instead use class . So , change id="search" to class="search" and id="output" to class="output" . Then , you can use $(this).closest("tr").find("input[name=id]").val() to get the id of row where you are performing search currently.
Demo Code :
$(document).ready(function() {
$(".search").keyup(function() {
var $this = $(this); //for refering `this` inisde success fn
var selector = $(this).closest("tr"); //get closest tr
var query = $(this).val();
var id = $(this).closest("tr").find("input[name=id]").val(); //get id
console.log("Id -- " + id)
if (query != "") {
/*$.ajax({
url: 'ajax-db-search.php',
method: 'POST',
data: {
query: query,
id:id
},
success: function(data) {*/
//selector.find(".output").html(data);
selector.find(".output").html("somethinfsfsfsf"); //just for demo..
selector.find(".output").css('display', 'block');
$this.focusout(function() {
selector.find(".output").css('display', 'none');
});
$this.focusin(function() {
selector.find(".output").css('display', 'block');
});
/* }
});*/
} else {
selector.find(".output").css('display', 'none');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="card-body">
<table width="95%" class="table table-bordered tablehover">
<tr>
<th width="40">ID</th>
<th>Image</th>
<th width="200">Hauptgegenstand</th>
<th width="130">Save</th>
<th width="137">Löschen</th>
<th width="137">Update</th>
</tr>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" enctype="application/x-www-form-urlencoded">
<tr>
<td><input readonly name="id" type="text" class="form-control input-sm" value="1" id="id" /></td>
<td width="232"><img style="max-width: 400px" src="uploads/<?php echo($r->file_name);?>"></td>
<td>
<input type="text" name="search" class="search" autocomplete="off" placeholder="Gegenstand suchen">
<div class="output"></div>
</td>
<td><input type="submit" class="btn btn-primary" name="submit"></td>
<td><input type="submit" class="btn btn-primary" name="delete"></td>
<td width="5%">Update </td>
</tr>
</form>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" enctype="application/x-www-form-urlencoded">
<tr>
<td><input readonly name="id" type="text" class="form-control input-sm" value="2" id="id" /></td>
<td width="232"><img style="max-width: 400px" src="uploads/<?php echo($r->file_name);?>"></td>
<td>
<input type="text" name="search" class="search" autocomplete="off" placeholder="Gegenstand suchen">
<div class="output"></div>
</td>
<td><input type="submit" class="btn btn-primary" name="submit"></td>
<td><input type="submit" class="btn btn-primary" name="delete"></td>
<td width="5%">Update </td>
</tr>
</form>
</table>
</div>
Hello every one I need help for getting auto search product values for dynamic adding of a product search box, when I type a product id it will show from product table. Please help me to get a dynamic auto search box.
Here is the code for the main html page:
<table id="row2">
<tr id="row1">
<td>product id</td><td><input type="text" id="pid" class="pid" name="p_id">
<div id="suggesstion-box"></div></td>
<td>product name</td> <td><input type="text" id="pname" name="p_name"></td>
<td>product type</td> <td> <input type="text" id="ptype" name="p_type">
</td>
<td>product colour</td> <td> <input type="text" id="pcolor" name="p_colour"></td>
</tr>
</table>
<button name="b1" id="b1" onClick="addrow()">Add More</button>
This the code for jQuery:
$(document).ready(function(){
$("#pid").keyup(function(){
$.ajax({
type: "POST",
url: "readCountry.php",
data:'keyword='+$(this).val(),
beforeSend: function(){
$("#pid").css("background","#FFF url(LoaderIcon.gif) no-repeat 165px");
},
success: function(data1,data2){
$("#suggesstion-box").show();
$("#suggesstion-box").html(data1);
$("#fname").html(data2);
$("#pid").css("background","#FFF");
}
});
});
});
function addrow()
{
//alert('hello');
$('#row2').append("<tr><td>product id</td><td><input type='text' class='pid' id='pid' name='p_id'><div id='suggesstion-box'></div></td><td>product name</td> <td><input type='text' id='pname' name='p_name'></td><td>product type</td> <td> <input type='text' id='ptype' name='p_type'></td><td>product colour</td><td> <input type='text' id='pcolor' name='p_colour'></td></tr>");
}
function selectCountry(val) {
$("#pid").val(val);
$("#suggesstion-box").hide();
}
function name(val){
$("#pname").val(val);
}
function pt(val){
$("#ptype").val(val);
}
function colour(val){
$("#pcolor").val(val);
}
readcountery.php page code is:
<?php
require_once("dbcontroller.php");
$db_handle = new DBController();
if(!empty($_POST["keyword"])) {
$query ="SELECT * FROM raw_product WHERE p_id like '%" . $_POST["keyword"] . "%' ORDER BY p_id LIMIT 0,6";
$result = $db_handle->runQuery($query);
if(!empty($result)) {
?>
<ul id="country-list">
<?php
foreach($result as $country) {
?>
<li onClick="selectCountry('<?php echo $country["p_id"]; ?>'); colour('<?php echo $country["p_color"]; ?>'); pt('<?php echo $country["p_color"]; ?>'); name('<?php echo $country["p_name"]; ?>');"><?php echo $country["p_id"]; echo "-".$country["p_name"]; ?></li>
<?php } ?>
</ul>
<?php } } ?>
enter image description here
Hi Guys, I have the following problem:
In the url
"/media.php?module=riwayat&noreg=00020517"
All data with 'noreg = 00020517' is displayed. I want to filter the displayed data with 'keyword' entered in the textbox after the 'cari' button is clicked. How to without change the url?
the code on 'riwayat.php' is:
switch($_GET[act]){
default:
$aksi="modul/riwayat/aksi_riwayat.php";
$table = 'pasien';
$noreg = $_GET[noreg];
$text = "SELECT * FROM $table WHERE noreg = $noreg";
$sql1 = mysql_query($text);
$row1 = mysql_num_rows($sql1);
echo "<div id='dalam_content'>
<h2>RIWAYAT PASIEN</h2>
<div id='info_pasien'>
";
if ($row1>0){
while ($r=mysql_fetch_array($sql1)){
$lahir =new DateTime($r['tgl_lahir']);
// Convert Ke Date Time
$today = new DateTime();
$umur = $today->diff($lahir);
echo "
<table>
<tr>
<td>NO REG.</b></td>
<td><b>: $r[noreg]</b></td>
</tr>
<tr>
<td>Nama</b></td>
<td><b>: $r[nama_pasien]</b></td>
</tr>
<tr>
<td>Tgl Lahir</b></td>
<td><b>: ".jin_date_str($r[tgl_lahir])."</b></td>
</tr>
<tr>
<td>Jenis Kelamin</b></td>
<td><b>: $r[kelamin]</b></td>
</tr>
<tr>
<td>Alamat</b></td>
<td><b>: $r[alamat]</b></td>
</tr>
<tr>
<td>UMUR</b></td>
<td><b>: "; echo $umur->y; echo " Tahun, "; echo $umur->m; echo " Bulan, dan "; echo $umur->d; echo " Hari"; echo "</b></td>
</tr>
</table>
</div>";
}}
echo"
<div id='tampil_data1'>
<div id='tombol-cari'>
<form method=POST action='$aksi?module=riwayat&act=cari' enctype='multipart/form-data'>
<input name=kata type=text size=23 maxlength=50 />
<input type=submit value=Cari>
<input type=hidden name=noreg value=$noreg>
</form>
<input type=button value='Pemeriksaan Baru' onclick=\"window.location.href='?module=riwayat&act=periksabaru&noreg=$noreg';\">
</div>
<table id='theTable' width='100%'>
<tr>
<th width='10%'>Tanggal</th>
<th>Pemeriksaan</th>
<th>Terapi</th>
</tr>";
$kata = trim($_POST['kata']);
$kata = htmlentities(htmlspecialchars($kata), ENT_QUOTES);
$table2 = 'riwayat';
$where3 = "WHERE noreg= $noreg AND pemeriksaan LIKE '%$kata%' OR terapi LIKE '%$kata%'";
$sql3 = "SELECT * FROM $table2 $where3 ORDER BY id ASC";
$query3 = mysql_query($sql3);
while($rows=mysql_fetch_array($query3)){
if ($kata==$kata){
$pemeriksaan=$rows[pemeriksaan];
$pemeriksaan = preg_replace( "/$kata/i", '<span style="background-color:yellow;">' . $kata . '</span>', $pemeriksaan );
$terapi=$rows[terapi];
$terapi = preg_replace( "/$kata/i", '<span style="background-color:yellow;">' . $kata . '</span>', $terapi );
}
else {
$pemeriksaan=$rows[pemeriksaan];
$terapi=$rows[terapi];
}
echo "
<tr>
<td align='center'>".jin_date_str($rows[tgl_periksa])."</td>
<td>$pemeriksaan</td>
<td>$terapi</td>
</tr>";
}
echo "
</table>";
break;
and the 'aksi_riwayat.php' code is:
$module=$_GET[module];
$act=$_GET[act];
$noreg= $_POST[noreg];
// Input pemeriksaanbaru
if ($module=='riwayat' AND $act=='input'){
mysql_query("INSERT INTO riwayat(tgl_periksa,
noreg,
pemeriksaan,
terapi)
VALUES('$_POST[tgl]',
'$_POST[noreg]',
'$_POST[pemeriksaan]',
'$_POST[terapi]')");
header('location:../../media.php?module=riwayat&noreg='.$noreg);
}
// Input Cari
elseif ($module=='riwayat' AND $act=='cari'){
header('location:../../media.php?module=riwayat&noreg='.$noreg);
}
You can use AJAX for this purpose.
After click on Submit button you have to pass data to server and get back response from server end. Once you get data you have to render on target position.
This link will give you better idea how you can integrate AJAX.
The following is sample code from the above link:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.post("demo_test_post.asp",
{
name: "Donald Duck",
city: "Duckburg"
},
function(data,status){
alert("Data: " + data + "\nStatus: " + status);
});
});
});
</script>
</head>
<body>
<button>Send an HTTP POST request to a page and get the result back</button>
</body>
</html>
If anymore doubt please let me know.
Whenever the hyperlink with the yes id is clicked i dont want the page to refresh and then show the status, i want the status to change instant without page refreshing. I know Ajax deals with this, but can anyone provide me with a working example with my code please? As it melting my head :/
<h3 class="page-header"> Enquiries </h3>
<form id="enquiry" method="post" action="enquiry_csv.php">
<table class="table table-bordered table-hover">
<thead>
<tr>
<th> First Name</th>
<th> Last Name</th>
<th>Email</th>
<th>Message</th>
<th>Date</th>
<th>Responded to Enquiry?</th>
<th>Status</th>
<th></th>
<th><input class='btn-success' name='export' id='btnExport' type='submit' value='Export to CSV'/></th>
</tr>
</thead>
<tbody>
<?php
$query = "SELECT * FROM enquiries";
$select_enquiries = mysqli_query($connection,$query);
while($row = mysqli_fetch_assoc($select_enquiries)) {
$Enquiry_ID = $row['Enquiry_ID'];
$FirstName = $row['First_Name'];
$LastName =$row['Last_Name'];
$Email = $row['Email'];
$Message = $row['Message'];
$Date =$row['Date'];
$Responded =$row['Responded'];
echo "<tr>";
echo "<td>$FirstName </td>";
echo "<td>$LastName </td>";
echo "<td>$Email </td>";
echo "<td>$Message </td>";
echo "<td>$Date </td>";
echo "<td> <a id='yes' class='success' style='' href='enquiries.php?Yes=$Enquiry_ID'>Yes</a> | <a class='success' href='enquiries.php?No=$Enquiry_ID'>No</a> </td>";
echo "<td> $Responded</td>";
echo "<td> <a class='btn btn-danger' href ='enquiries.php?delete=$Enquiry_ID'>Delete</a> </td>";
echo "</tr>";
}
?>
<?php
if(isset($_GET['Yes'])){
$enquiry_id = $_GET['Yes'];
$query = "UPDATE enquiries SET Responded = 'Yes' WHERE Enquiry_ID = {$Enquiry_ID}";
$query = mysqli_query($connection, $query);
}
if(isset($_GET['No'])){
$enquiry_id = $_GET['No'];
$query = "UPDATE enquiries SET Responded = 'No' WHERE Enquiry_ID = {$Enquiry_ID}";
$query = mysqli_query($connection, $query);
}
if(isset($_GET['delete'])){
$review_id = $_GET['delete'];
$query = "DELETE FROM enquiries WHERE Enquiry_ID = {$Enquiry_ID} ";
$delete_query = mysqli_query($connection, $query);
}
?>
<tr>
<td></td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
</tbody>
</table>
</form>
You can do it with jquery ajax api it performs an asynchronous HTTP (Ajax) request
http://api.jquery.com/jquery.ajax/
Refer the above link which #Sanya Zahid posted and try to do some thing like this:
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" >
$(function() {
$(".submit").click(function() {
var name = $("#name").val();
var age = $("#age").val();
var dataString = 'name='+ name +'&age='+ age;
if(name=='' || age =='')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "submit.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
</script>
<form method="post" name="form">
<input id="name" name="name" type="text" /><br>
<input id="age" name="age" type="text"/>
<div>
<input type="submit" value="Submit" class="submit"/>
<span class="error" style="display:none"> Please Enter Data</span>
<span class="success" style="display:none"> Data Saved!!</span>
</div>
</form>
Here submit.php contains database related stuff(insert/update/delete). I just added name and age fileds here in code. Add fields as per your form.
submit.php :
<?php
$conn = mysqli_connect("localhost","root","","test");
/* Insert form data with out page refresh */
if($_POST)
{
$name=$_POST['name'];
$age = $_POST['age'];
mysqli_query($conn,"Query will come here");
}else{
echo "Please try again!!";
}
/* Insert form data with out page refresh */
?>
I have a dynamic table which is created in server side (php), and I'm using jquery to show it in html page.
in this table there are multiple values which I want to edit them and save this edits in mysql.
but I don't know how to get this values the way that I tried is just updating the first value and is not getting other element values :
jquery code :
$('#save_edit').on('click',function() {
$('#edit_test_show').hide();
$('#enable_edit').show();
$('#save_edit').hide();
var vop_id = localStorage.getItem('op_id');
var vop_title = $('#result_table').find('[name=op_title]').val();
var vop_descrip = $('#result_table').find('[name=op_descrip]').val();
var vobjects_count = $('#result_table').find('[name=objects_count]').val();
var vobject_val = [];
var vobject_id = $('#result_table').find('[name=object_id]').val();
for(i=0;i<vobjects_count;i++){
vobject_val[i] = $('#result_table').find('[name=object_val]').val();
}
$.post("Requests/OPS.php", //Required URL of the page on server
{ // Data Sending With Request To Server
EDIT_OPS : true,
op_id : vop_id,
op_title : vop_title,
op_descrip : vop_descrip,
objects_count : vobjects_count,
object_id : vobject_id,
object_val : vobject_val
},
function(response){ // Required Callback Function
$("#Response").text(response).css({color: 'green'});
});
});
dynamic table in php :
if($op_objects_count<=0) {
echo "<table class='styled-table' cellspacing = '0' width = '360' border = '1' >
<tr>
<th>
<label for='session_order' style = 'margin-right:10px;color:#595959;float: right;' >اهداف فرآیند : </label >
</th>
</tr>";
while ($objects_row = mysqli_fetch_assoc($op_objects)) {
echo "<tr>
<input name = 'object_id' type='hidden'
value = '" . $objects_row['id'] . "' />
<td>
<input name = 'object_val' style = 'width:340px;height: 36px;margin:0 3px 3px 3px;'
value = '" . $objects_row['object'] . "' />
</td>
<input name = 'objects_count' type='hidden'
value = '".$op_objects_count."' />
</tr>";
}
echo "</table>";
echo "<div class='cleaner h30'></div>";
my php query to update the database :
if($_POST['EDIT_OPS']==true){
$op_id = $_POST['op_id'];
$op_title = $_POST['op_title'];
$op_descrip = $_POST['op_descrip'];
//===================================
$objects_count = $_POST['objects_count'];
$object_id = $_POST['object_id'];
$object_val = $_POST['object_val'];
// print_r($object_val);
$save_edit = $DBM->RunQuery("UPDATE at_ops SET op_title='$op_title' , op_descrip='$op_descrip' WHERE id='$op_id'",true,false);
for($i=0;$i<$objects_count;$i++){
$save_edit = $DBM->RunQuery("UPDATE at_ops_objects SET object='$object_val[$i]' WHERE id='$i' AND ops_id='$op_id' ",true,false);
}
if(isset($save_edit) && $save_edit>0)
echo "success";
else
echo "failure";
}
If you change all names from for example
<input name='object_id'
to
<input name='object_id[]'
you can serialize the form and it will create arrays on the server.
As for getting all values in jQuery, this works for me:
$(function() {
$('#save_edit').on('click', function() {
var vobject_val = [];
$('#result_table').find('[name=object_val]').each(function() {
vobject_val.push(this.value);
});
console.log(vobject_val);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table class='styled-table' cellspacing='0' width='360' border='1' id="result_table">
<tr>
<th>
<label for='session_order' style='margin-right:10px;color:#595959;float: right;'>اهداف فرآیند :</label>
</th>
</tr>
<tr>
<input name='object_id' type='hidden' value='r1' />
<td>
<input name='object_val' style='width:340px;height: 36px;margin:0 3px 3px 3px;' value='1' />
</td>
<input name='objects_count' type='hidden' value='1' />
</tr>
<tr>
<input name='object_id' type='hidden' value='r2' />
<td>
<input name='object_val' style='width:340px;height: 36px;margin:0 3px 3px 3px;' value='2' />
</td>
<input name='objects_count' type='hidden' value='2' />
</tr>
<tr>
<input name='object_id' type='hidden' value='r3' />
<td>
<input name='object_val' style='width:340px;height: 36px;margin:0 3px 3px 3px;' value='3' />
</td>
<input name='objects_count' type='hidden' value='3' />
</tr>
</table>
<button type="button" id="save_edit">save</button>
I suggest something like this:
<table id="admTable">
<thead style="width:100%;">
<tr>
<th>row</th>
<th>name</th>
<th>username</th>
<th>pass</th>
<th>delete</th>
<th>edit</th>
</tr>
</thead>
<tbody id="adminsTb">
<?php
$i=1;
while( $admins=mysqli_fetch_array($results,MYSQLI_ASSOC))
{
echo '<form action="insert.php" method="post" id="formId">';
echo "<tr>
<td>$i</td><input type='hidden' name='id' value='$admins[id]'/>
<td><input name='adminname' type='text' value='$admins[name]' /></td>
<td><input name='user' type='text' value='$admins[user]'required='required' /></td>
<td><input name='pass' type='password' value='$admins[pass]' required='required' /></td>
<td> <input name='deladmin' type='submit' value='delete' /></td>
<td><input name='updateadmin' type='submit' value='save' /></td>
</tr>";
$i++;
echo " </form>";
}
?>
</tbody>
</table>
insert.php
if(isset($_POST['updateadmin'])){
$results=mysqli_query($dbCnn," update admins set name='$_POST[adminname]', user='$_POST[user]', pass='$_POST[pass]' where id=$_POST[id]");}
//Jquery ajax
(function($){
function processForm( e ){
$.ajax({
url: 'insert.php',
dataType: 'text',
type: 'post',
contentType: 'application/x-www-form-urlencoded',
data: $(this).serialize(),
success: function( data, textStatus, jQxhr ){
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
}
});
e.preventDefault();
}
$('#formId').submit( processForm );
})(jQuery);