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(); ?>
Related
I have two tables in a SQLite DB. The second table contains information about the first.
The first table is loaded in a modal table with buttons to a second modal table in which I would like to load information from the second SQlite table based on the rowID from the first.
I have attempted several things but none of them worked, I assume because JS only gets executed when loading the page, but I can't figure out a way to work around this.
I left comments about the things I tried in the code.
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
</head>
<body>
<button type="button" class="btn btn-info" data-toggle="modal" data-target="#modal1">View</button>
<!-- begin modal1 -->
<div class="modal" id="modal1">
<div class="modal-dialog">
<div class="modal-content">
<table class="table table-bordered table-striped">
<thead>
<tr class="btn-primary">
<th>id.</th>
<th>text1</th>
</tr>
</thead>
<tbody>
<?php
$db = new PDO('sqlite:db.sqlite'); // I know this is unsafe, but it works and it's for a local page.
$qry1 = $db->prepare("SELECT * FROM table1");
$qry1->execute();
$i = 1;
while ($row = $qry1->fetch(PDO::FETCH_ASSOC)) {
$Query1ID[$i] = $row['id']; //If I know what row I'm selecting I could use it to find the correct variable in the next query, but I can only find this with JS and don't know how to combine these.
?>
<tr>
<td onclick="clicked(<?php echo $i; ?>)"><button type="button" class="btn btn-primary mybutton" data-toggle="modal" data-target="#modal2" data-row-val="<?php echo $row['id']; ?>"><?php echo $row['id']; ?></button></td>
<!-- with onclick I can find out what row I clicked and in combination with $Query1ID[$i] I should be able to get the correct variable in the new query. But I don't know how to combine them. -->
<td><?php echo $row['table1_text']; ?></td>
<?php
$i++;
}
?>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<!-- end modal1 -->
<!-- begin modal2 -->
<div class="modal" id="modal2">
<div class="modal-dialog">
<div class="modal-content">
<table class="table table-bordered table-striped">
<thead>
<tr class="btn-primary">
<th>id.</th>
<th>Entries for <span id="rowvarfromJS">empty</span></th> <!-- I can call the variable but can not use it in the query. -->
</tr>
</thead>
<tbody>
<?php
$db = new PDO('sqlite:db.sqlite');
//function if clicked = 3 newID = $Query1ID[3] //something like this would solve my problem
$newID="$Query1ID[10]";
echo $newID;
echo "<script>var javascriptVar = '199';</script>";
echo "<script>if (nr == 2){alert('execute php?')}</script>";
$phpVar = "<script>document.writeln(javascriptVar);</script>";
echo "phpvar=$phpVar";
//$qry2 = $db->prepare("SELECT * FROM table2 WHERE fortable1ID = $newID"); //This works, if only I could use the JS var from the clicked function to find the correct variable.
//$qry2 = $db->prepare("SELECT * FROM table2 WHERE fortable1ID = $phpVar"); //This does not work even though $phphvar contains the correct value.
$qry2 = $db->prepare("SELECT * FROM table2 WHERE fortable1ID = '199'");
// I need this static 199 to be $row['id']; from the previous query.
// I have attempted using rowvarfromJS for that but that doesn't work.
// I can use AJAX and complete the query on another page, but I do not know how to use JS reply to generate a new table.
$qry2->execute();
$i2 = 1;
while ($row = $qry2->fetch(PDO::FETCH_ASSOC)) {
?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['table2text']; ?></td>
<td><?php echo "$Query1ID[4]"; ?></td> <!-- I can use this variable in a query, but I do not know how to select the correct one.-->
</tr>
<?php
$i2++;
}
?>
</tbody>
</table>
</div>
</div>
</div>
<!-- end modal2 -->
<!-- javascript -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script type="text/javascript">
//This was an attempt to get the rowID with JS. It works, but I can't use the variable in the query.
$(function () {
$(".mybutton").click(function () {
var my_row_value = $(this).attr('data-row-val');
$("#modal2").attr('data-row-value',my_row_value );
alert('My Row Value '+my_row_value ); //If I could only use this value in the query.
let rowvarfromJS = my_row_value;
document.getElementById("rowvarfromJS").innerHTML = rowvarfromJS;
})
});
//Gets clicked row number. If I know the clicked row number then I should be able to find the correct php variable for the next query, but I don't know how to do this.
function clicked (nr) {
let rcfromJS = nr;
console.log('Clicked from row: ' + rcfromJS);
}
//I have also attempted using AJAX to pass the JS variable to another PHP and get the result back, which works, but the result is in JS and I don't know how to create a table from that.
</script>
</body>
</html>
Most attempts are written as comments in the code. Aside from those I also tried using Ajax, but the problem with that is that I am using a JS variable to get a JS variable and I don't know how to use that to populate the modal table.
var data = {
'var1': "199",
'var2': "test."
};
$.ajax({
type: 'post',
url: 'executesecondquery.php',
data: data,
timeout: 50000
}).done(function(response) {
console.log(response); //can I use this response to populate the second table?
}).fail(function(error) {
// uh-oh.
});
executesecondquery.php
<?php
$db = new PDO('sqlite:db.sqlite');
$qry2 = $db->prepare("SELECT table2text FROM table2 WHERE fortable1ID = '$var1'");
$qry2->execute();
$i2 = 1;
while ($row = $qry2->fetch(PDO::FETCH_ASSOC)) {
echo $row['table2text'];
$i2++;
}
?>
I have a modal in bootstrap 5 that i'm trying to populate with custom data from a mysql database depending on the option i'm selecting.
So I have a table that is populated with some data using PHP and MYSQL. The last column of the table is a button called "Actions" and I want to have a modal opened when I press this button that is filled with the information from the row where I pressed the button (every row contains this button as the last column).
As you can see in the below code, I have the exact same code as I found out in the sollution in this question: Pass PHP variable to bootstrap modal
Here is my code:
In the main index file:
...
...
<tbody>
<?php $categories = Category::find_all();
foreach ($categories as $category) { ?>
<tr>
<th scope="row"><?php echo $category->id; ?></th>
<td><?php echo $category->cat_name; ?></td>
<td><?php echo $category->cat_creation_date; ?></td>
<td><?php echo $category->cat_created_by; ?></td>
<td><a type="button" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#bsMyModal" data-id="<?php echo $category->id; ?>">Actions</a></td>
</tr>
<?php } ?>
</tbody>
...
...
Modal code (in the same file as the above table):
<div class="modal fade" id="bsMyModal" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Edit Data</h4>
</div>
<div class="modal-body">
<div class="fetched-data"></div> //Here Will show the Data
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-bs-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
JS code (just below the end of body in the same file)
</body>
<script>
$(document).ready(function(){
$('#bsMyModal').on('show.bs.modal', function (e) {
var rowid = $(e.relatedTarget).data('id');
$.ajax({
type : 'post',
url : 'fetch_record.php', //Here you will fetch records
data : 'rowid='+ rowid, //Pass $id
success : function(data){
$('.fetched-data').html(data);//Show fetched data from database
}
});
});
});
</script>
Also the fetch_record.php file which is a basic file just to have this working:
<?php
require_once "backend/init.php";
if($_POST['rowid']) {
$id = $_POST['rowid']; //escape string
echo $id;
}
?>
Now the problem.. nothing happens
The modal openes when I press the Actions button, but I don't get any information (in this specific case I should be getting the category id printed out before the "//Here Will show the Data" text in the modal code.
I looked at the console and I've seen this message:
ajax:681 Uncaught ReferenceError: $ is not defined
at ajax:681:1
(anonymous) # ajax:681
If i click the link at # ajax:681, it points me to this:
enter image description here
What am I doing wrong?...
Thank you!
Stupid mistake...
I tought about searching for the console error and come upon this:
Uncaught ReferenceError: $ is not defined?
And yes.. I was using the script before referencing the jQuery.. I moved it after the jQuery include and now it works.
Dumb
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 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
}
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;
});
});