I'm using bootstrap modal and currently i'm stuck with displaying the values to modal.
here is the html when the user will click view
<a data-toggle="modal" data-id="<?php echo $row33['bicycle_id']; ?>" href="#myModal" class="Buto" >view</a>
then i used jquery-ajax to pass the value of data-id to execute a query in php
$(document).on("click",".Buto", function () {
var dataID = $(this).data('id');
$.ajax({
url: 'getId.php?id=' + dataID,
type:'GET',
dataType: 'json',
context: this,
success: function(values)
{
values = $.parseJSON(values);
$('.table-responsive #pname').html(values.name);
$('.table-responsive #pprice').html(values.price);
$('.table-responsive #pdescription').html(values.description);
}
});
});
here is the getId.php file
<?php
include 'includes/connection.php';
$modalDataId = $_GET['id'];
$resu = mysqli_query($conn,"SELECT * FROM bicycle WHERE bicycle_id = $modalDataId");
while ($row7 = mysqli_fetch_assoc($resu)){
$values['name'] = $row7['name'];
$values['price'] = $row7['price'];
$values['description'] = $row7['description'];
}
echo json_encode($values);
?>
then the modal where the values should be displayed
<div class="modal-body">
<div class="table-responsive" id = "div1" style = " width: 100%; margin-right: 10%; background-color: white;">
<table id = "" align = "center" class="table table-hover table-striped demo2" style = "table-layout:fixed;"> <thead style = "">
<tr style = "background-color: #428bca; color: white;">
<th class="col-sm-3">BIKE NAME</th>
<th class="col-sm-3" >SRP</th>
<th class="col-sm-3" >DETAILS</th>
</tr>
</thead>
<tbody id="myTable">
<tr style = "text-align: center;" data-toggle="modal" data-id="" data-target="#orderModal">
<td id="pname"></td>
<td id="pprice"></td>
<td id="pdescription"></td>
</tr>
</tbody>
</table>
</div>
</div>
Ok. Let me break your problem up for you:
The first question you should ask is: Is my ajax-success-callback function being called? And how can you verify that your code is executed? Simple: create some output to debug your code. For logging simple variables an alert(...) should be fine. If you want to debug the content of an array you are much better off if you log it to the console.
So what I would try is:
$.ajax({
url: 'getId.php?id=' + dataID,
type:'GET',
dataType: 'json',
context: this,
success: function(values)
{
// not sure about alerts in ajax callbacks but you can try it:
alert('inside success callback');
values = $.parseJSON(values);
// alert a value:
alert('values.name is: '+values.name);
$('.table-responsive #pname').html(values.name);
$('.table-responsive #pprice').html(values.price);
$('.table-responsive #pdescription').html(values.description);
// log all values to the javascript console in your browser
console.log(values);
}
});
Try that and look at the output.
a. You don't see any alert window. This means your success callback function is never executed or you have an javascript error. Look at your javascript console in your browser to see if console.log(values) created an output. More about console.log(...) here: What is console.log and how do I use it?
b. You get to see alert windows. But the second alert goes something like: 'values.name is undefined'. --> Your php is not working as expected.
Without being able to actually debug your code this is how I would improve it:
<?php
include 'includes/connection.php';
$modalDataId = $_GET['id'];
$resu = mysqli_query($conn,"SELECT * FROM bicycle WHERE bicycle_id = $modalDataId");
// You expect one row to be returned then you need no while loop:
$row7 = mysqli_fetch_assoc($resu);
// Initialize values array
$values = array();
if ($row7) {
$values['name'] = $row7['name'];
$values['price'] = $row7['price'];
$values['description'] = $row7['description'];
}
echo json_encode($values);
?>
Try that and come back with your results.
here is the answer thanks to walfish3d. i revised the code he provided.
The jquery-ajax:
$(".Buto").on("click",function () {
var dataID = $(this).data('id');
$.ajax({
url: 'getId.php?id=' + dataID,
type:'GET',
dataType: 'json',
context: this,
success: function(values)
{
$('.table-responsive #pname').html(values.name);
$('.table-responsive #pprice').html(values.price);
$('.table-responsive #pdescription').html(values.description);
// log all values to the javascript console in your browser
console.log(values);
}
});
});
getId.php file:
<?php
include 'includes/connection.php';
$modalDataId = $_GET['id'];
$resu = mysqli_query($conn,"SELECT * FROM bicycle WHERE bicycle_id = $modalDataId");
// You expect one row to be returned then you need no while loop:
$row7 = mysqli_fetch_assoc($resu);
// Initialize values array
$values = array();
if ($row7) {
$values['name'] = $row7['name'];
$values['price'] = $row7['price'];
$values['description'] = $row7['description'];
}
echo json_encode($values);
?>
Related
I'm trying to get the UID from an anchor tag which is the value of ID attribute of the anchor tag from a foreach loop PHP in ajax. But it only work once a time, when I click the anchor tag again then all the UIDs are grabbed in the ajax!
When I click on anchor tag then 1st I'm displaying a bootstrap 4 modal and in modal a textarea tag is present with a button and when I click button then I've to send uid and message again to the action.php page
This is my action.php code
if(isset($_POST['action']) && $_POST['action'] == 'fetchAllFeedback'){
$feedback = $admin->fetchFeedback();
$output = '';
if($feedback){
$output .= '<table class="table table-striped table-bordered text-center">
<thead>
<tr>
<th>FID</th>
<th>UID</th>
<th>User Name</th>
<th>User E-Mail</th>
<th>Subject</th>
<th>Feedback</th>
<th>Sent On</th>
<th>Action</th>
</tr>
</thead>
<tbody>';
foreach ($feedback as $row) {
$output .= '<tr>
<td>'.$row['id'].'</td>
<td>'.$row['uid'].'</td>
<td>'.$row['name'].'</td>
<td>'.$row['email'].'</td>
<td>'.$row['subject'].'</td>
<td>'.$row['feedback'].'</td>
<td>'.$row['created_at'].'</td>
<td>
<i class="fas fa-reply fa-lg"></i>
</td>
</tr>';
}
$output .= '</tbody>
</table>';
echo $output;
}
else{
echo '<h3 class="text-center text-secondary">:( No any feedback written yet!</h3>';
}
}
This is feedback.php ajax code
$("body").on("click", ".feedbackReplyIcon", function(e){
let uid = $(this).attr('id');
$("#feedback-reply-btn").click(function(e){
if($("#feedback-reply-form")[0].checkValidity()){
let message = $("#message").val();
e.preventDefault();
$("#feedback-reply-btn").val('Please Wait...');
$.ajax({
url: 'assets/php/admin-action.php',
method: 'post',
data: {uid:uid,message:message},
success:function(response){
console.log(response);
$("#feedback-reply-btn").val('Send Reply');
$("#showReplyModal").modal('hide');
$("#feedback-reply-form")[0].reset();
}
});
}
});
});
Here is what I believe happens: Since you declare a click method inside another click method, the uid variable turns empty after the first use. It's generally a bad practice to stack events like this inside one another. Try changing your javascript to this:
var uid;
$("body").on("click", ".feedbackReplyIcon", function(e){
uid = $(this).attr('id');
});
$("#feedback-reply-btn").click(function(e){
if($("#feedback-reply-form")[0].checkValidity()){
let message = $("#message").val();
e.preventDefault();
$("#feedback-reply-btn").val('Please Wait...');
$.ajax({
url: 'assets/php/admin-action.php',
method: 'post',
data: {uid:uid,message:message},
success:function(response){
console.log(response);
$("#feedback-reply-btn").val('Send Reply');
$("#showReplyModal").modal('hide');
$("#feedback-reply-form")[0].reset();
}
});
}
});
This might still be less than optimal, I'm a bit unclear on how your elements are laid out, and I can't really test it out. Let me know on what happens - if it still doesn't work, try dumping out the variables in admin-action.php , and see what's in there.
I have a table with each row has link of tag "click here", I want to use a modal box to pop up when a user click on the link and display all row information and allow user to make edit and update.
I am using AJAX with JQuery to pass row id, which is used at backend with PHP to execute SQL Query.
But i don't want to use Bootstrap Modal Box. Please help in making a modal box pop up or something other so that user can make edits on each row of displayed table when a user click on <td><p><a href='' id='%d' value='%d'>Click here</a></p></td>.
I am not clear with how to use Modal Box for each row. may be that could be easier using Jquery.
Below is code of <section> tag of my Dashboard.html which has table.
Here focus on <td><p><a href='' id='%d' value='%d'>Click here</a></p></td>. which include button to call modal box.
<!-- View All Added Campaign and Lead information -->
<section class="operation" id="view_all_lead_Campaign" style="width: 100%;margin: 0 auto; display: none;">
<!-- Main Tables Campaign and Lead Table -->
<div class="row">
<!-- MAIN TABLE-->
<div class="col" >
<button class="viewMainTable" name='viewMainTable' onclick='viewMainTable();' id='viewMainTableButton' >Lead Table</button>
<button class="viewCampaignTable" name='viewCampaignTable' onclick='viewCampaignTable();' id='viewCampaignTableButton' >View Campaign Table</button>
<div class="row">
<div class="col span-4-of-4">
<div style="overflow-x:auto;">
<table class="display_table" id='main_lead_table' style="display: none;">
<thead>
<th>#</th>
<th>Lead Id</th>
<th>Name</th>
<th>Website</th>
<th>Linkedin</th>
<th>Lead Description</th>
<th>Owner Notes</th>
<th>Last Contact Date</th>
<th>Next Contact Date</th>
<th>Lead Status</th>
<th>Details</th>
</thead>
<tbody id='leadTable'>
<?php
function getLeadAddedByName($id){
include('./server/connection.php');
$selectSQL = "SELECT UserName FROM `tbl_user_signup_info` WHERE User_Id = '$id' ";
$result = $conn -> query ($selectSQL);
$name = "";
while($row = mysqli_fetch_array($result)){
$name = $row['UserName'];
}
return $name;
}
include('./server/connection.php');
$selectSQL = "SELECT * FROM `tbl_main_lead_info` ORDER BY Lead_Id";
$result = $conn -> query ($selectSQL);
$i = 1;
while ($row = mysqli_fetch_array($result)) {
printf( "<tr class='content'>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td><p><a href='' id='%d' value='%d'>Click here</a></p></td>
</tr>",
$i,
$row['Lead_Id'],
$row['FirstName']." ".$row['LastName'],
$row['Website'],
$row['Linkedin'],
$row['LeadDescription'],
$row['OwnerNotes'],
$row['AdminNotes'],
getLeadAddedByName($row['LeadAddedBy'])."<br>Date/Time: ".$row['LeadAddedOn'],
date('d-m-Y', strtotime($row['LastContactDate'])),
date('d-m-Y', strtotime($row['NextContactDate'])),
$row['LeadStatus'],
$row['Lead_Id'],
$row['Lead_Id'],
);
$i = $i+1;
}
?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</section>
Modal.js file to get the click here id and correspoding that PHP at backend execute to fetch record and populate in Modal Box Pop up.
$(document).ready(function() {
$('[name="leadidclick"]').click(function(e){
e.preventDefault();
var leadid = $('[name="leadidclick"]').val();
$.ajax({
type: "POST",
url: './server/modal.php',
data: {
'leadid': leadid
},
success: function(data){
var result = $.parseJSON(data);
console.log(result);
//Modal Box to POP UP HERE
}
});
});
});
My Modal.php file for backend
<?php
// send a JSON encoded array to client
include('./server/connection.php');
/* check connection */
if ($conn->connect_errno) {
printf("Connect failed: %s\n", $conn->connect_error);
exit();
}
if( $_POST['campaignid'] != "" ) {
// echo "Modal.php file is executed";
$id = $_POST['campaignid'];
$selectSQL = "SELECT * FROM `tbl_main_lead_info` WHERE Lead_Id = '$id' ";
$result_array = array();
$result = $conn -> query ($selectSQL);
// If there are results from database push to result array
if(mysqli_num_rows($result) > 0){
while ($row = mysqli_fetch_array($result)) {
array_push($result_array, $row);
}
}
echo json_encode($result_array);
}else{
echo $conn->error;
}
Step 1:
Add a Modal in the page.
Step 2:
Upon click of the anchor element pass the id to ajax function and fetch record
Step 3:
create the form at either php or jquery side.
and show modal with the final response.
At PHP
response from server will have form ready with data, you just need to add the response to modal-body div.
$.ajax({
url :: 'your url',
type : 'post',
data : {id: row id},
success: function(response){
$('.modal-body').html(response);
$('#your-modal-id').modal('show');
}
});
At Jquery side
$.ajax({
url :: 'your url',
type : 'post',
data : {id: row id},
dataType: "JSON",
success: function(response){
//here inside json variable you've the json returned by your PHP
for(var i=0;i<json.length;i++){
$('#form-element').val(json[i].item_name);
.
.
.
}
$('#your-modal-id').modal('show');
}
});
Please note: there are many ways to do it, if you find it complex, feel free to write, I will try to give you exact solution. :)
i have a table where i print out all of the users for the program. now i would like to have a toggle Bootstrap button for Activate and Incative. I would like to store 1 and 0 into my database. how do i save the value for the specific User ID the value and then update it when the button pressed. Also how to then when it has been pressed to then update the page? is it possible to not refresh the page?
<div class="table-responsive-sm">
<table class="table table-bordered table-condensed table-striped text-center table-dark">
<tr>
<th> First Name</th>
<th>Last Name</th>
<th>E-mail</th>
<th>Username</th>
<th>Accreditation</th>
<th>Instructor ID</th>
<th>Time Registered</th>
<th>Account State</th>
<th>Activate</th>
<th>SET Inactive</th>
</tr>
<?php
$sql = ("SELECT * FROM instructors GROUP BY ID ORDER BY ID DESC ");
$result=mysqli_query($mysqli,$sql);
while ($row=mysqli_fetch_array($result)){
$accred = $row['role'];
if($accred == '0'){
$test = 'Admin';
} else if ($accred == '1') {
$test = 'Bookkeper';
} else if ($accred == '2') {
$test = 'Coordinator';
} else if ($accred == '3') {
$test = 'Instructor';
}
$LoginState = $row['LoginState'];
if($LoginState == '0'){
$LogState = '<td style="color: White; background-color: orangered"><b>Inactive</b></td>';
} else if ($LoginState == '1') {
$LogState = '<td style="color: black; background-color: lightgreen"><b>Active</b></td>';
}
$ID = $row['ID' ];
echo "
<form method=\"POST\">
<tr>
<td>".$row['Fname']."</td>
<td>".$row['Lname']."</td>
<td>".$row['Email']."</td>
<td>".$row['username']."</td>
<td>".$test ."</td>
<td>".$row['ID' ] ."</td>
<td>".$row['RegisteredTime']."</td>
$LogState
<td><button name=\"LoginState\" type=\"button\" class=\"btn btn-success\" role=\"button\" value\"1\">Activate</button</td>
<td><button name=\"LoginState\" type=\"button\" class=\"btn btn-warning\" role=\"button\" value\"0\">SET Inactive</button</td>
</tr></form>";
}
if (isset($_POST['LoginState'])){
$sql1 = "INSERT into instructors (LoginState) VALUES ($logstats) WHERE ID = $ID";
if ($mysqli->query($sql1) === TRUE) {
echo "New record created successfully";
echo "<br/>";
} else {
echo "Error: " . $sql1 . "<br>" . $mysqli->error;
}}
Here is the html code to show toggle button
<td data-title="Status">
<label class="switch">
<input type="checkbox" id="toggle<?php echo $id; ?>" name="status_<?php echo $id; ?>" <?php if($status == 'on'){echo "checked"; }?> >
<div class="toggle round"></div>
</label>
</td>
$id is dynamic id which you get from db.you need proper CSS these classes to make it toggle button.
AJAX call to update records in db onChange of checkbox value
<script type="text/javascript">
$(document).ready(function(){
$('#toggle<?php echo $id; ?>').click(function(){
var id = <?php echo $id; ?>;
if($(this).prop("checked") == true){
var stat = 'on';
}
else if($(this).prop("checked") == false){
var stat = 'off';
}
$.ajax({
type: "POST",
url : "example.php",
data : { id : id,stat :stat },
success: function(data) {
//update value in page acc to new updated value from db
}
});
});
});
</script>
$id is same as above. You need to do update then select query in example.php to update content in page, without refreshing the page
Mark, as others said, if you want to refresh part of your page without reloading the whole page, you need to use AJAX.
One of the most popular and simple way to use AJAX is including the jQuery.js library. If you already use javascript, you will find a bit easy to include jQuery in your page. (you can find and copy the jquery.js file anywhere on internet, just type "download jquery file" in google)
in example, you can put this code in your html (in fact, you can put it almost in any place of your page)
<script type="text/javascript" src="jquery.min.js"></script>
Then you can use the softech's example...
<script type="text/javascript">
$(document).ready(function(){
...
$.ajax({
type: "POST",
url : "PageThatOnlyReturnsData.php",
data : { id:id, stat:stat },
success: function(data) {
//update value in page acc to new updated value from db
}
});
...
});
</script>
It's strongly recommended thay you create another php page to place de mySQL code and returns data (I named in example "PageThatOnlyReturnsData.php"), so this php page will print out the result data from your query.
So, the front php (the first page with HTML) calls the second php (the data php) through the $.ajax() function, and you can process the received data within the "success" function.
success: function(data) {
//here "data" is what you receive from the second php
//do what you want here with javascript using the new variable "data" as in the softech's example
}
I want to delete row in database without reloading the page. I have written following codes. It does delete row in page but not in database. which means connection not going to ajax. pls help.
<?php
$advances_result= mysqli_query($conn, "SELECT * FROM advances") or die("error");
?>
<table border>
<caption>ADVANCES</caption>
<tr>
<th>Date</th>
<th>EmpName</th>
<th>EmpCode</th>
<th>Amount</th>
<th>Comment</th>
<th>Action</th>
</tr>
<?php
while($row = mysqli_fetch_array($advances_result)){
?>
<tr>
<td><?php echo $row['date'];?></td>
<td><?php echo $row['empname'];?></td>
<td><?php echo $row['empcode'];?></td>
<td style='text-align:right'><?php echo $row['amount'];?></td>
<td><?php echo $row['comment'];?></td>
<td><button class="delete" id="<?php echo $row['id']; ?>" > Delete</button></td>
</tr>
<?php
}
?>
</table>
'jquery part'
<script>
$(document).ready(function(){
$(".delete").click(function() {
if (confirm("Do you want to delete this row?"))
{
var row = $(this).parents('tr');
var id = row.attr("id");
var data = 'id=' + id ;
$.post({
type: "post",
url: "deleteadvances.php",
data: data,
cache: false,
success: function(){
row.slideUp('slow', function() {$(row).remove();});
}
});
}
return false;
});
});
</script>
'deleteadvances.php' page:
<?php
include("connection.php");
$id = $_POST['id'];
mysqli_query($conn,"INSERT INTO advancehistory SELECT * FROM advances WHERE ID='".$id."'");
mysqli_query($conn,"DELETE FROM advances WHERE ID='".$id."'");
?>
You need to test the output of mysqli_query in deleteadvances.php, if all good, it shows JSON Ok message that is easy parsable with $.post on the jQuery side.
e.g: {"deleted":"id"} on success or {"error":404} on error not found.
I think the id that you're passing from javascript to ajax is incorrect.
var data = 'id=' + id;
is appending the id with string 'id=' and now it finally becomes a string. When it is being passed to ajax, there is just a value and not a [key, value] pair. So, when you are accessing it in php you will get wrong id or Null value.
Try:
$.post({
type: "post",
url: "deleteadvances.php",
datatype : 'json',
data: {
id : id
},
cache: false,
contentType : 'application/x-www-form-urlencoded; charset=utf-8'
});
Change 'deleteadvances.php' page:
<?php
include ('connection.php');
$id=$_POST['id'];
$delete = "DELETE FROM table_name WHERE id=$id";
$result = mysqli_query($db,$delete) or die("Bad SQL: $delete");
?>
I am have a page where i have the table row id defined by 'lesson_id' and i have a delete function for jquery that deletes that row without having to change page.
It is almost all working but when it posts the information to delete_row.php it is not deleting the record.
but delete_row.php is working because i've manually done delete_row.php?id=4 and it deleted that record succesfully.
Any pointers and explanations would be great as i'm still learning.
lessons.php
<table id="lessons" class="table-hover">
<thead>
<tr>
<th>Lesson ID</th>
<th>Lesson Name</th>
<th></th>
</tr>
</thead>
<tbody>
<?php
while($row=mysqli_fetch_array($result)){
echo '<tr id="'. $row['lesson_id'].'">';
echo '<td>'. $row['lesson_id'] .'</td>';
echo '<td>'. $row['name'] .'</td>';
echo '<td><a class="delete">Delete</a></td>';
echo '</tr>';
}
?>
</tbody>
<div id="error"></div>
<script>
$(document).ready(function()
{
$('table#lessons td a.delete').click(function()
{
if (confirm("Are you sure you want to delete this row?"))
{
var id = $(this).parent().parent().attr('id');
var data = 'id=' + id ;
var parent = $(this).parent().parent();
//$('#error').html(data);
$.ajax(
{
type: "POST",
url: "delete_row.php",
data: data,
cache: false,
success: function()
{
parent.fadeOut('slow', function() {$(this).remove();});
}
});
}
});
});
</script>
delete_row.php
<?php
include ('../../../config.php');
$con = mysqli_connect ($dbhost,$dbuser,$dbpass,$dbname);
if (!$con){
die('could not connect: '. mysqli_error($con));
}
$error = "";
$success = "";
if($_GET['id'])
{
$id = $_GET['id'];
mysqli_query($con,"DELETE FROM module_lessons WHERE lesson_id='$id'");
}
?>
as its obvious ... this has no sql injection protection on it.
Change $_GET['id']; to $_POST['id'];
Here, you're doing a POST request:
type: "POST",
url: "delete_row.php",
... but in your PHP script you're checking for GET.
Also, as marc b noted, you're currently vulnerable to SQL injection. Look into using mysqli_real_escape_string, or bind_param.