i have two questions which are below;
1)How do i pass a value from a foreach to ajax. this is my code and what i have so far, tried putting the ajax inside the foreach but it kept on giving me the id of the last name in the for each.
2)Is there a way that i can click on add and and the data will be held and put in another html table below this html table but wont be inserted into database until i click on insert in the second table.
<table class="table table-bordered datatable" id="table_export">
<thead>
<tr>
<th>#</th>
<th><div>Item</div></th>
<th><div>Quantity Left</div></th>
<th><div>Price</div></th>
<th><div>Quantity</div></th>
<th><div>Sell</div></th>
</tr>
</thead>
<tbody>
<?php
$count = 1;
$notarray = DataDB::getInstance()->get_rows_from_field('name');
foreach($notarray as $row):?>
<tr>
<td><?php echo $count++;?></td>
<td><?php echo $row['name'];?></td>
<td><?php echo $row['nickname'];?></td>
<td><?php echo $row['surname']; ?></td>
<form method="post" action="" role="form">
<td>
<div class="form-group">
<div class="">
<input type="number" class="form-control" name="kin" data-validate="required" data-message-required="Kin required" autofocus>
</div>
</div>
</td>
<td>
<div class="btn-group">
<button type="submit" class="btn btn-primary" name = "check">Add</button>
</div>
</td>
</form>
</tr>
<?php endforeach;?>
</tbody>
</table>
<br><br>
<div id="get_result">
</div>
<script type="text/javascript">
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'verify.php',
data: $('form').serialize() + '&ins=sellin' + '&id=<?php echo $row['name_id'];?>',
success: function(data)
{
jQuery('#get_result').html(data);
}
});
});
});
If I get you right, you mean you wanted to pick an item from list of items in table A and it should display in table B. Afterwards, you wanted to click submit button in table B to save the picked items from Table A?
Here is the solution:
Kindly name this file as test.php
<?php
/**
* Created by PhpStorm.
* User: SQ05
* Date: 06/01/2017
* Time: 06:31 PM
*/
//Note that data is a typical example of data u gotten from DB. so make sure u push all $row into an array
//such that u create something of this nature eg
// $data=array();
// $i=0;
//while($row=mysql_fetch_assoc($query)){
//$data[$i]=$row;
//$i++;
//}
// this will then create data of this nature below,
$data=array(
array('id'=>1,'name'=>'Loveth','age'=>23,'phone'=>'9889087455'),
array('id'=>2,'name'=>'Susan','age'=>51,'phone'=>'787987455'),
array('id'=>3,'name'=>'Precious','age'=>13,'phone'=>'98989087455'),
array('id'=>4,'name'=>'Hannah','age'=>21,'phone'=>'987087455'),
array('id'=>5,'name'=>'Kenneth','age'=>43,'phone'=>'569087455'),
);
?>
<div style="float:left;width:50%">
THE LIST OF ALL ITEMS
<table>
<tr>
<td>Name</td>
<td>Age</td>
<td>Phone</td>
<td>Action</td>
</tr>
<?php
$i=0;
for ($i=0;$i<count($data);$i++) {
$item=$data[$i];
?>
<tr>
<td><?php echo $item['name'];?></td>
<td><?php echo $item['age'];?></td>
<td><?php echo $item['phone'];?></td>
<td><button onclick='addToList(<?php echo json_encode($item);?>);'>Add</button></td>
</tr>
<?php
}
?>
</table>
</div>
<div style="float:left; width:50%">
THE ITEM TO BE SAVED
<div id="showToSave"></div>
</div>
<script src="bower_components/jquery/dist/jquery.js"></script> <!--Please install jquery base on ur own directory path-->
<script>
var listToSave=[]; // must be global
/**
* The add to list function that process data and add to list
* #param data
*/
var addToList= function(data){
var lenData=listToSave.length;
if(lenData>0){
//this is used to avoid duplicate
for(var j=0;j<lenData;j++){
if(data.id==listToSave[j].id) return;
}
}
listToSave.push(data);
console.log(listToSave);
document.getElementById('showToSave').innerHTML=createData(listToSave);
};
var createData= function (data) {
var len=data.length;
var tableToSave="<table><tr><td>Name</td> <td>Age</td> <td>Phone</td> <td>Action</td></tr>";
var i;
for(i=0;i<len;i++){
content=data[i];
tableToSave+="<tr><td>"+content.name+"</td><td>"+content.age+"</td><td>"+content.phone+"</td><td>" +
"<button onclick='deleteFromSave("+i+")'>Delete</button></td></tr>";
}
tableToSave+="</table><div><button onclick='saveData()' type='button'>Save</button></div>";
return tableToSave;
};
/**
* This is use to delete data added locally
*/
var deleteFromSave=function (index) {
listToSave.splice(index,1); //this is use to delete from list to save
document.getElementById('showToSave').innerHTML=createData(listToSave); //to rerender after delete
};
/**
* This is use to submit data
*/
var saveData=function () {
console.log('thjis=',listToSave);
$.ajax({
type: "POST",
url: "getData.php",
data: {list : JSON.stringify(listToSave)},
success: function(resp){
console.log('response=',resp);
}
});
};
</script>
Kindly name this as getData.php to process the submission of the list of added data using multiple value insertion approach.
<?php
/**
* Created by PhpStorm.
* User: SQ05
* Date: 06/01/2017
* Time: 07:28 PM
*/
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$data = json_decode(stripslashes($_POST['list'])); //the data here can now be used to create a multiple value insert to ur mysql db.
print_r(json_encode($data)); // this is used to send response back to ur page if using array buh echo if string
}
Related
Im new here and I have some difficulties to make my code to work. Hope u guys can help me. Im displaying records form MySQL in a modal box in a table format. Each row has its own add (+) button generated via php loop which displays records that should be leter on, added to a different table using jquery on click event and AJAX. Each td row is provided with an input field with class name "idKont", but only the first one will be added after I click on the + / add button.
$('#add_kontpers').on("click", function(e) {
e.preventDefault();
var ptId = $('#idAj').text(); // ID of the customer that will be passed
var idKont = $('.idKont').val(); // ID of the contact person
$.ajax ({
url: "folder/insert_data.php",
method:"POST",
data:
{
id: ptId,
idKont: idKont
},
dataType:'text',
success: function(result) {
//$('#myModal').modal('hide');
$('#alert_modal').append( '<div class="alert alert-success">Success</div>' ).fadeIn(1000).fadeOut(4000);
}
})
})
and this is the HTML Code with PHP:
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header" style="padding:10px 50px;">
<p><span class="glyphicon glyphicon-lock"></span> Choose Contact Person</p>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body" style="padding: 40px 50px;">
<form role="form" method="post">
<div id="alert_modal"></div>
<table class="table table-responsive">
<thead class="thead-light">
<tr>
<th>ID</th>
<th>Vorname</th>
<th>Name</th>
<th>Tel</th>
<th>Mobil</th>
</tr>
</thead>
<tbody>
<?php
try {
$stmt = $connser->prepare("SELECT ID, Vorname, Name, Tel, Mobil FROM Contactperson ORDER BY ID DESC");
$stmt->execute();
while ($row = $stmt->fetch()) {
$kontID = $row['ID'];
?>
<tr>
<td><?php echo $row['ID']; ?></td>
<td><?php echo $row['Vorname']; ?></td>
<td><?php echo $row['Name']; ?></td>
<td><?php echo $row['Tel']; ?></td>
<td><?php echo $row['Mobil']; ?></td>
<td><input class="idKont" value="<?php echo $kontID; ?>" type="hidden" /></td>
<td><button type="submit" class="btn btn-success add_kontpers">+</button></td>
</tr>
<?php
}
}
catch(PDOException $e) {
echo "Error";
//echo "Error: " . $e->getMessage();
exit;
}
?>
</tbody>
</table>
</form>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-danger btn-default pull-left" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
The modal box stays open and it shoud be, but if I click the first element on the top, then only this one will be added. I would like to have the oportunity to click for example one position on the list to add it to the table, the the second one, and so on, but if I click other butten then the first one then the modalbox will be closed and the website reloads. Any help or pinting in the right direction will be highly appreciated.
Two things, first you can't reuse the same ID and by having add_kontpers in a loop, you will reusing that.
So first, change that to a class and idAj doesn't exist in the provided code.
<button type="submit" class="btn btn-success add_kontpers">
Then make this change in your jQUERY
$('.add_kontpers').on("click", function(e) {
e.preventDefault();
var ptId = $('#idAj').text(); ?????????????????????
var idKont = $(this).parents("tr").find('.idKont').val(); // ID of the contact person
Javascript
$(document)
.on('click', 'button#add_kontpers', function(a){
a.preventDefault();
var button = $(this);
var row = button.closest('tr');
var id = row.find('input').val();
$.post("folder/insert_data.php", {id : id, idKont : id})
.done(function(response){
//Your response
})
})
I have a table that is given based on the option selected in a . This table generates list of students based on class selected. I want a dynamic modals popup each time the SMS button on a student row is clicked it is suppose to show the related parent's name dynamically. It's actually doing this but the issue is it is not dynamic one i refresh the page the data for the first student button clicked is what shows as response for every other one. until i refresh again. I select another and it shows thesame for every other student
Though when i used develop tool(network) in browser the xmlrequest was sent sucessfully and the interesting thing is the passed "id" param for the selected student is correct. but it just showing the same one that's selected first in the modal popup after refresh
the code looks like this
`
function smsmodal(id){
var data= {"id" : id};
jQuery.ajax({
url : '/sms/include/smsmodal.php',
method : "post",
data : data,
success: function(data){
jQuery('body').append(data);
jQuery('#sms-modal').modal('toggle');
},
error: function(){
alert("Something went wrong")
}
});
}
`
And for the loop:
<?php
require_once '../../service/mysqlcon.php';
$parentID = $_POST['parentID'];
$selected = sanitize($_POST['selected']);
$studentquery = $conn->query("SELECT * FROM students WHERE class = '$parentID' ORDER BY lastname");
$count = mysqli_num_rows($studentquery);
$i = 1;
ob_start(); ?>
<?php
if($count < 1){
?>
<br><br>
<h4 class="text-warning text-center bg-warning" style="padding:20px">No student has been registered in this class.</h4>
<?php
}else{
?> ...... other html..
<div class="table-responsive">
<table class="table table-hover">
<thead><th><input type="checkbox"> Roll</th><th>Photo</th><th>Student Name</th><th>Address</th><th>Actions</th></thead>
<tbody>
<?php while($s = mysqli_fetch_assoc($studentquery)) :?>
<tr>
<td><input type="checkbox"> <?=$i;?></td>
<td> <img src="<?=$s['photo'];?>" alt="photo" class="img-responsive" id="photo"></td>
<td><?php echo $s['lastname'].' '.$s['firstname'];?></td>
<td><?=$s['address'];?></td>
<td><button class="btn btn-success btn-xs" type="button" onclick="smsmodal(<?=$s['id']; ?>)" style="width:80px"><span class="fa fa-mobile"></span> SMS</button> </td>
</tr>
<?php $i++;?>
<?php endwhile; ?>
</tbody>
</table>
</div>
<?php } ?>
<?php echo ob_get_clean(); ?>
When we use ajax the value is in server side, which on successful execution can be shown using
.done(function(data) {console.log(data)}
The result of the ajax is inside "data". My question is can we pass the value of "data" in a php variable.
My scenario is : There is a dropdown, below this is an html table. So when the user selects an item in the dropdown, using ajax the selected values passes in the "data".
After this I am running a Mysql query
"Select name, age, sex from student where name = '{$retvalue}';
Now instead of "??", I want to pass value inside "data" in a php variable $retvalue.
How can I achieve this?
I have tried my level best and even after a thorough search in the net, I am not able to find anything.
Code is as follows :
Main - File
<?php
include ("dbcon.php");
include ("included_functions.php");
?>
<section>
<script type="text/javascript" src="<?php bloginfo('template_url');?>/js/jquery.min.js"></script>
<script src="<?php bloginfo('template_url');?>/js/jquery-1.9.1.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#fyearddl").change(function(){ /* Drop down List */
var fyear = $(this).val();
data = {fyear:fyear};
$.ajax({
type: "GET",
url: '<?php bloginfo("template_url");?>/showonselectFY.php',
data: data,
cache: false
})
.done(function(data) {
console.log(data);
$('#inboxfy').empty();
$('#inboxfy').val(fyear);
})
});
});
</script>
<div style="width:100%; height:30px; padding-bottom:45pt; background-color:#fff"></div>
<form id="formCatg" action="" method="POST">
<div class="centr-div">
<div class="divbox">
<label id="ddltxt">To view : </label>
<?php
$fyquery = "select fyear from finyear";
$fyresult = mysqli_query($connection, $fyquery);
echo "<select id='fyearddl' name='fyearddl'>";
echo "<option value = '-- Select Financial Year --'>-- Select Financial Year --</option>";
while ($resultarr = mysqli_fetch_assoc($fyresult)){
echo "<option value = '$resultarr[fyear]'>$resultarr[fyear]</option>";
}
echo "</select>";
?>
<input id="inboxfy" type="text" name="inboxfy" value="" style="width:20%; height:15pt" />
</div>
<div id="tablediv" class="scroll">
<table id="showselfy">
<thead>
<tr>
<th>S.no.</th>
<th>Quantity</th>
<th>Price ( £ ) </th>
</tr>
</thead>
<?php
//$query="select rt_id, rt_qty, rt_cost,fin_yr from rate_mast where fin_yr='2014-2015'";
$ddlvalue = $_POST['fyearddl'];
$query="select rt_id, rt_qty, rt_cost from rate_mast where fin_yr='{$ddlvalue}'";
$retval = mysqli_query($connection, $query);
while( $retvalarr = mysqli_fetch_assoc($retval)){
?>
<tbody>
<tr>
<td><?php echo $retvalarr['rt_id'] ?></td>
<td><?php echo $retvalarr['rt_qty'] ?></td>
<td><?php echo $retvalarr['rt_cost'] ?></td>
<td style="display:none"><?php echo $retvalarr['fin_yr'] ?></td>
</tr>
</tbody>
<?php } ?>
</table>
</div>
<span id="dataresult"></span>
</div>
</div>
</div>
</form>
</section>
<?php
mysqli_close($connection);
?>
<?php //get_footer(); ?>
showonselectFY.php
<?php var_dump($_GET); ?>
<?php
include("dbcon.php");
include("included_functions.php");
if(isset($_GET['fyear'])){
$getfinyear = $_GET['fyear'];
echo $getfinyear;
}
?>
<?php
mysqli_close($connection);
?>
In a table I display several links whose value (user id) is extracted from a database. By clicking on the link appears a modal pop up in which I would like to pass the selected value.
Here is the table:
<table>
<tr>
<td>Username</td>
<td>Id</td>
</tr>
<?php
include ‘db_connection.php’;
$sql = "SELECT * FROM users";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)){
?>
<tr>
<td><?php echo $row[userID]?></td>
<td>
<div id='basic-modal'>
<a href="?id=<?php echo $row[userID]?>" class='basic'>Show</a>
</div>
</td>
</tr>
<?php } ?>
</table>
If I click on the link Show appears the modal pop up:
<div id="basic-modal-content">
<?php
if(isset($_GET[‘userID’])){
$userID = $_GET[‘userID’];
echo ‘UsuerID: ‘ .$userID;
}
?>
</div>
This is the script I used
jQuery(function ($) {
$('#basic-modal .basic').click(function (e) {
$('#basic-modal-content').modal();
return false;
});
});
Since I have little familiarity with the jQuery framework I would like to ask you how can I pass the selected value within the modal and then use it.
jquery allows you to use the .data() attribute
<div id='basic-modal'>
<a href="?id=<?php echo $row[userID]?>" data-mydata="<?php echo $row[userID]?>" class='basic'>Show</a>
</div>
and then u can retrieve data from 'data-mydata' attribute:
jQuery(function ($) {
$('#basic-modal .basic').click(function (e) {
$('#basic-modal-content')
.text($(this).data('mydata'))
.modal();
return false;
});
});
I have this dropdown menu using form_helper in CodeIgniter:
<?php if($materialType): ?>
<?php
$material_options = array();
foreach($materialType as $rows){
$material_options[$rows->id] = $rows->category;
}
echo form_dropdown('materialType',$material_options,'','id="materialType"');
?>
<?php endif; ?>
<div id="materials"></div>
The code above is inside a <form> tag and I have this script:
<script type="text/javascript">
var base_url = "<?php echo base_url(); ?>";
</script>
<script>
$(document).ready(function(){
$(document).on('change','#materialType',function(){
loadthis();
});
function loadthis(){
var ID = $('#materialType').val();
var dataString = 'id='+ ID ;
$.ajax({
type: "POST",
url: base_url + "index.php/admin/get_material",
data: dataString,
cache: false,
success: function(data)
{
$('#materials').html(data);
}
});
}
loadthis();
});
</script>
And here is the code that is being loaded:
<div id="materials">
<?php if($materials): ?>
<table>
<th>Name</th>
<th>Description</th>
<?php foreach($materials as $row): ?>
<tr>
<td><?php echo $row->mname; ?></td>
<td><?php echo $row->mdesc; ?></td>
<td>
<button class="try" value="<?php echo $row->id; ?>">Add</button>
</td>
</tr>
<?php endforeach; ?>
</table>
<?php else: ?>
<div class="alert alert-error" style="width:300px;">No Resource Available!</div>
<?php endif; ?>
$(document).on('click','.try',function(){
alert($(this).val());
return false;
});
And what i want is if the Add button is being click I can get the ID,mname and store it until the form is submitted.
How can I do that using .data() in jquery? or Any ideas on how to store it until the form is being submit.
I didn't thoroughly look at your code, but I noticed when you print your table rows in a loop you have the id="try" assigned to all of the rows. the html id-attribute is a unique identifier so the JS that is alerting the value will only return the value of the first id it will find (at least that's what i think). Try to use a class instread of an id and then use this in your js.
$(document).on('click','.try',function(){
alert($(this).val());
return false;
});