Getting multiple dynamic html element values using jquery - php

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

Related

i echoed a form and ajax code to save that particular form using php but what ever i select it saves only the first row data

This is the page i am working with having issue.The data from the first row of table is getting saved even if i click the save button for below rows.Is there any solution or suggestions for the same.
<table>
<tr>
<th>BED</th>
<th>NAME</th>
<th>RBS<br>Serum Electrolytes<br>RFT</th>
<th>CBC</th>
<th>PT,APTT,INR</th>
<th>LFT</th>
<th>Urine <br>Electrolytes</th>
<th>Serum & <br>Urine<br> OSMOLALITY</th>
<th>Procalcitonine</th>
<th>TFT</th>
<th>LIPID<br>Profile</th>
<th>Ammonia <br>& Phosphate</th>
<th>ACTION</th>
</tr>
<?php
include'connection.php';
$sql = "SELECT id,fname,mname, lname,uhid,bednumber FROM patientlist WHERE status='active' ORDER BY `bednumber` ASC";
$result = mysqli_query($link, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$id=$row["id"];
$fname=$row["fname"];
$mname=$row["mname"];
$lname=$row["lname"];
$uhid=$row["uhid"];
$bednumber=$row["bednumber"];
$spacer=' ';
$name=$fname.$spacer.$mname.$spacer.$lname;
I am experiencing problem with the below segment of code that is dynamically rendered from db into a form.Each row will be a separate form with different id on sumbit button
echo"
<tr>
<form>
<input type='hidden' name='id' id='id' value='$id'>
<input type='hidden' name='fname' id='fname' value='$fname'>
<input type='hidden' name='mname' id='mname' value='$mname'>
<input type='hidden' name='lname' id='lname' value='$lname'>
<input type='hidden' name='uhid' id='uhid' value='$uhid'>
<input type='hidden' name='bednumber' id='bednumber' value='$bednumber'>
<td>$bednumber</td>
<td>$name</td>
<td><input type='checkbox' name='rbs' id='rbs' value='RBS,SE,RFT' checked></td>
<td><input type='checkbox' name='cbc' id='cbc' value='CBC' ></td>
<td><input type='checkbox' name='pt' id='pt' value='PT,APTT,INR' ></td>
<td><input type='checkbox' name='lft' id='lft' value='LFT' ></td>
<td><input type='checkbox' name='ue' id='ue' value='URINE ELECTROLYTES' ></td>
<td><input type='checkbox' name='osmo' id='osmo' value='SERUM & URINE OSMOLALITY' ></td>
<td><input type='checkbox' name='procal' id='procal' value='PROCALCITONINE' ></td>
<td><input type='checkbox' name='tft' id='tft' value='TFT' ></td>
<td><input type='checkbox' name='lipid' id='lipid' value='LIPID PROFILE' ></td>
<td><input type='checkbox' name='ammo' id='ammo' value='AMMONIA & PHOSPHATE' ></td>
<td>
<input id='$id' type='button' class='btn-submit' value='Save' ><input type='reset'></td>
</form>
</tr>
This is the ajax code which uses the submit button id to save data.
Both the form and ajax code will come inside an echo of php
<script>
$(document).ready(function() {
$('#$id').click(function() {
var id = $('#id').val();
var fname = $('#fname').val();
var mname = $('#mname').val();
var lname = $('#lname').val();
var uhid = $('#uhid').val();
var bednumber = $('#bednumber').val();
var rbs = $('#rbs').val();
var cbc = $('#cbc').val();
var pt = $('#pt').val();
var lft = $('#lft').val();
var ue = $('#ue').val();
var osmo = $('#osmo').val();
var procal = $('#procal').val();
var tft = $('#tft').val();
var lipid = $('#lipid').val();
var ammo = $('#ammo').val();
if(id==''||uhid==''||bednumber=='') {
alert('Form render error.Demographics return empty.');
return false;
}
$.ajax({
type: 'POST',
url: 'labbookformhandler.php',
data: {
id: id,
fname: fname,
mname: mname,
lname: lname,
uhid: uhid,
bednumber: bednumber,
rbs: rbs,
cbc: cbc,
pt: pt,
lft: lft,
ue: ue,
osmo: osmo,
procal: procal,
tft: tft,
lipid: lipid,
ammo: ammo
},
cache: false,
success: function(data) {
alert(data);
},
error: function(xhr, status, error) {
console.error(xhr);
}
});
});
});
</script>
";
}
}
My goal is to save each row data seperately for that particular save button provided at the end of each row.I tried my maximum.I am not a professional.I am doing it as a hobby.Kindly give me a suggestion so that i can correct it and learn something new.
I changed my code according to your suggestions and it worked like a charm
<form id='form-$id' method='POST' action='' >
<input type='hidden' name='id' id='id' value='$id'>
<input type='hidden' name='fname' id='fname' value='$fname'>
<input type='hidden' name='mname' id='mname' value='$mname'>
<input type='hidden' name='lname' id='lname' value='$lname'>
<input type='hidden' name='uhid' id='uhid' value='$uhid'>
<input type='hidden' name='bednumber' id='bednumber' value='$bednumber'>
<td>$bednumber</td>
<td>$name</td>
<td><input type='checkbox' name='rbs' id='rbs' value='RBS,SE,RFT' checked></td>
<td><input type='checkbox' name='cbc' id='cbc' value='CBC' ></td>
<td><input type='checkbox' name='pt' id='pt' value='PT,APTT,INR' ></td>
<td><input type='checkbox' name='lft' id='lft' value='LFT' ></td>
<td><input type='checkbox' name='ue' id='ue' value='URINE ELECTROLYTES' ></td>
<td><input type='checkbox' name='osmo' id='osmo' value='SERUM & URINE OSMOLALITY' ></td>
<td><input type='checkbox' name='procal' id='procal' value='PROCALCITONINE' ></td>
<td><input type='checkbox' name='tft' id='tft' value='TFT' ></td>
<td><input type='checkbox' name='lipid' id='lipid' value='LIPID PROFILE' ></td>
<td><input type='checkbox' name='ammo' id='ammo' value='AMMONIA & PHOSPHATE' ></td>
<td>
<input id='save-$id' type='button' class='btn-submit' value='Save' ><input type='reset'></td>
</form>
</tr>
<script>
$(document).on('click','#save-$id',function(e) {
var data = $('#form-$id').serialize();
$.ajax({
data: data,
type: 'post',
url: 'labbookformhandler.php',
success: function(data){
alert(data);
}
});
});
</script>
The corrected code is given.If there is any more suggestions please comment

Delete SQL values without page reload (AJAX, PHP)

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>

List Table A, Search Table B and update Table A with result

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'] . "&param2=" . $user['ebene_2_nr'] . "&param3=" .$user['ebene_3_nr']. "&param4=" .$_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'] . "&param2=" . $user['ebene_2_nr'] . "&param3=" .$user['ebene_3_nr']. "&param4=" .$_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>

jQuery / AJAX send content of changed divs

I have this CRUD system where a customer should be able to specify the amount of the desired product. When the amount is > 0, I add a new class "active" to that table row.
When the "continue" button is clicked, the rows containing a value of 0 are filtered out. After clicking the "order" button I want to send an email to the admin containing the list of desired products and the corresponding amount.
The code below works, however, the email sent contains only one field (it must be able to handle several of them) and the amount is always 0.
<form role="form" method="post" action="email.php">
<input type="text" class="sendmail" name="name" placeholder="Your name" />
<input type="text" class="sendmail" name="email" placeholder="Your email" />
</form>
<table>
<tr class='".$row['id']."'>
<td class='name'>".$row['name']."</td>
<td class='category'></td>
<td class='price'>€".$row['price']."</td>
<td class='unit'>per ".$row['unit']."</td>
<td class='actions'><input type='number' name='amount[]' min='0' value='0' id='".$row['id']."'></td>
</tr>
</table>
<button id="order"><i class="fas fa-angle-right"></i> Volgende</button>
<button id="confirm"><i class="fas fa-paper-plane"></i> Bestellen</button>
jQuery
$(document).ready(function() {
$('input').on('change', function() {
var id = $(this).attr('id');
if(parseInt(this.value) > 0){
$('.'+id).addClass('active');
}
else {
$('.'+id).removeClass('active');
}
});
$('#order').click(function() {
$("#order").hide();
$("#confirm").show();
$('.heading').html('<i class="fas fa-apple-alt"></i> Overzicht');
$('tr').not(document.getElementsByClassName('active')).empty();
$(':input[type="number"]').prop('disabled', true);
});
});
$(function() {
$('#confirm').click(function(e) {
$.ajax({
url: 'email.php',
type: 'POST',
data: {
'message': $('.active').html(),
'email': $('[name="email"]').val(),
'name': $('[name="name"]').val()
},
success: function(data) {
alert('You data has been successfully e-mailed');
}
});
});
});
email.php
$email = $_POST['email'];
$subject = "Subject";
$name = $_POST['name'];
$content = $_POST['message'];
$to = 'myemail#gmail.com';
$body = '
<html>
<head>
<title>Email: '. $email .'</title>
</head>
<body>
<p>From: '. $name .'</p>
<div>
'. $content .'
</div>
</body>
</html>
';
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
$headers .= "From: $email\r\n";
mail($to, $subject, $body, $headers);
This is the email I receive:
I've been testing your code.
The first thing I noticed, you are using the ".active" class to reference several elements, which is fine because then you can call them as an array, but using $('.active').html() only returns the first element and NOT the outerhtml for the TR. And you also need the TABLE tags for your mail to have a correct html.
So I would do something like this:
$(function() {
$('#confirm').click(function(e) {
var data = "<table>";
$('.active').each(function(i, obj) {
data += obj.outerHTML;
});
data += "</table>";
$.ajax({
url: 'email.php',
type: 'POST',
data: {
'message': data,
'email': $('[name="email"]').val(),
'name': $('[name="name"]').val()
},
success: function(data) {
alert('You data has been successfully e-mailed');
}
});
});
});
And then when you want to reference the HTML itself to use in the mail maybe you should delete the input and paste the value of the input instead. Because the actual value of the input may not be copied:
$('#order').click(function() {
$("#order").hide();
$("#confirm").show();
$('.heading').html('<i class="fas fa-apple-alt"></i> Overzicht');
$('tr').not(document.getElementsByClassName('active')).empty();
//$(':input[type="number"]').prop('disabled', true);
$(':input[type="number"]').each(function(i,obj){
obj.after( obj.value );
obj.parentNode.removeChild(obj);
});
});
Here are the sinppets:
$(document).ready(function() {
$('input').on('change', function() {
var id = $(this).attr('id');
if(parseInt(this.value) > 0){
$('.'+id).addClass('active');
}
else {
$('.'+id).removeClass('active');
}
});
$('#order').click(function() {
$("#order").hide();
$("#confirm").show();
$('.heading').html('<i class="fas fa-apple-alt"></i> Overzicht');
$('tr').not(document.getElementsByClassName('active')).empty();
//$(':input[type="number"]').prop('disabled', true);
$(':input[type="number"]').each(function(i,obj){
obj.after( obj.value );
obj.parentNode.removeChild(obj);
});
});
});
$(function() {
$('#confirm').click(function(e) {
var data = "<table>";
$('.active').each(function(i, obj) {
data += obj.outerHTML;
});
data += "</table>";
console.log(data);
});
});
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>test</title>
</head>
<body>
<table>
<tr class='1'>
<td class='name'>lala</td>
<td class='category'></td>
<td class='price'>€125</td>
<td class='unit'>por kilo</td>
<td class='actions'><input type='number' name='amount[]' min='0' value='0' id='1'></td>
</tr>
<tr class='2'>
<td class='name'>lele</td>
<td class='category'></td>
<td class='price'>€225</td>
<td class='unit'>por kilo</td>
<td class='actions'><input type='number' name='amount[]' min='0' value='0' id='2'></td>
</tr>
<tr class='3'>
<td class='name'>lili</td>
<td class='category'></td>
<td class='price'>€325</td>
<td class='unit'>por kilo</td>
<td class='actions'><input type='number' name='amount[]' min='0' value='0' id='3'></td>
</tr>
<tr class='4'>
<td class='name'>lolo</td>
<td class='category'></td>
<td class='price'>€425</td>
<td class='unit'>por kilo</td>
<td class='actions'><input type='number' name='amount[]' min='0' value='0' id='4'></td>
</tr>
</table>
<button id="order"><i class="fas fa-angle-right"></i> ORDER</button>
<button id="confirm" style="display:none;"><i class="fas fa-paper-plane"></i> CONFIRM</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</body>
</html>
Hope I can help
First of all, when your are dealing with input type=number you have to update it's attr value manually. Then, according to doc, if you are using jquery html() method against array it takes first element and return it's html. So, in your case you have to do few changes:
$(function() {
$('input').on('change', function() {
$(this).closest('tr').toggleClass('active', parseInt(this.value) > 0);
$(this).attr('value', $(this).val()); // manually set attr value
});
$('#order').on('click', function() {
$("#order").hide();
$("#confirm").show();
$('.heading').html('<i class="fas fa-apple-alt"></i> Overzicht');
$('tr').not('.active').empty();
$(':input[type="number"]').prop('disabled', true);
});
$('#confirm').click(function(e) {
let messages = [];
$('.active').each(function(el){
messages.push($(this).html());
});
console.log(messages); // composed messages array
$.ajax({
url: 'email.php',
type: 'POST',
data: {
'message': messages,
'email': $('[name="email"]').val(),
'name': $('[name="name"]').val()
},
success: function(data) {
alert('You data has been successfully e-mailed');
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form role="form" method="post" action="email.php">
<input type="text" class="sendmail" name="name" placeholder="Your name" />
<input type="text" class="sendmail" name="email" placeholder="Your email" />
</form>
<table>
<tr class='class1'>
<td class='name'>name</td>
<td class='category'></td>
<td class='price'>€10</td>
<td class='unit'>per 1</td>
<td><input type='number' name='amount[]' min='0' id='class1'></td>
</tr>
<tr class='class2'>
<td class='name'>name</td>
<td class='category'></td>
<td class='price'>€10</td>
<td class='unit'>per 1</td>
<td><input type='number' name='amount[]' min='0' id='class2'></td>
</tr>
<tr class='class3'>
<td class='name'>name</td>
<td class='category'></td>
<td class='price'>€10</td>
<td class='unit'>per 1</td>
<td><input type='number' name='amount[]' min='0' id='class3'></td>
</tr>
</table>
<button id="order"><i class="fas fa-angle-right"></i> Volgende</button>
<button id="confirm"><i class="fas fa-paper-plane"></i> Bestellen</button>

How to get data from server when I enter something in search box and I press add more button? Adds other row of product search box in jQuery AJAX

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 } } ?>

Categories