Passing DB values to modal using jquery - javascript

I created a viewing module where users could view values from the database and I added an edit button, when you click the button, the modal should pop up with values based on the id.
Currently, this is what I'm getting when I click the edit button:
Now I'm still lacking one thing and it's the JavaScript which I already created:
<script>
$('#exampleModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget) // Button that triggered the modal
var recipient = button.data('whatever') // Extract info from data-* attributes
var modal = $(this);
var dataString = 'id=' + recipient;
$.ajax({
type: "GET",
url: "editdata.php",
data: dataString,
cache: false,
success: function (data) {
console.log(data);
modal.find('.dash').html(data);
},
error: function(err) {
console.log(err);
}
});
})
</script>
My fetch.php is purely PHP and I'm not sure how I would add the JS into it. Here's my fetch.php:
<?php
$connect = mysqli_connect("localhost", "root", "", "seatrequest");
$output = '';
$colors = array();
$colors["Ongoing"] = "red";
$colors["Closed"] = "#00FF00";
if(isset($_POST["query"]))
{
$search = mysqli_real_escape_string($connect, $_POST["query"]);
$query = "
SELECT * FROM request
WHERE req_date LIKE '%".$search."%'
OR reqname LIKE '%".$search."%'
OR natureofreq LIKE '%".$search."%'
OR postitle LIKE '%".$search."%'
OR critlevel LIKE '%".$search."%'
OR deadline LIKE '%".$search."%'
OR account LIKE '%".$search."%'
OR newaccname LIKE '%".$search."%'
OR lob LIKE '%".$search."%'
OR site LIKE '%".$search."%'
OR status LIKE '%".$search."%'
";
}
else
{
$query = "
SELECT * FROM request ORDER BY reqnumber";
}
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0)
{
$output .= '<div class="table-responsive">
<table class="table table bordered">
<tr>
<th style="background-color: #e6ecff;">Date Requested</th>
<th style="background-color: #e6ecff;">Requested By</th>
<th style="background-color: #e6ecff;">Nature of Request</th>
<th style="background-color: #e6ecff;">Position Title</th>
<th style="background-color: #e6ecff;">Critical Level</th>
<th style="background-color: #e6ecff;">Deadline</th>
<th style="background-color: #e6ecff;">Account</th>
<th style="background-color: #e6ecff;">Name of Account (For New Seat)</th>
<th style="background-color: #e6ecff;">LOB</th>
<th style="background-color: #e6ecff;">Site</th>
<th style="background-color: #e6ecff;">Status</th>
<th style="background-color: #e6ecff;">Action</th>
<th style="background-color: #e6ecff;">Edit</th>
</tr>';
while($row = mysqli_fetch_array($result))
{
$output .= '<tr>
<td>'.$row["req_date"].'</td>
<td>'.$row["reqname"].'</td>
<td>'.$row["natureofreq"].'</td>
<td>'.$row["postitle"].'</td>
<td>'.$row["critlevel"].'</td>
<td>'.$row["deadline"].'</td>
<td>'.$row["account"].'</td>
<td>'.$row["newaccname"].'</td>
<td>'.$row["lob"].'</td>
<td>'.$row["site"].'</td>
<td style="color:' . $colors[$row["status"]] . ';">' .$row["status"] . '</td>
<td>
<form method="post" action="update-work-status.php">
<input type="hidden" name="reqnumber" value="'.$row['reqnumber'].'" />
<button class="fa fa-check" style="color: green" type="submit" name="approve" value=""></button><button class="fa fa-close" style="color: red" type="submit" name="decline" value=""></button>
</form>
</td>
<td><a class="btn btn-small btn-primary" data-toggle="modal" data-target="#exampleModal" data-whatever="'.$row['reqnumber'].' ">Edit</a></td>
</tr>
';
}
echo $output;
}
else
{
echo 'Data Not Found';
}
?>
I guess my question is how would I incorporate that JS inside fetch.php? I'm not really sure if it's gonna work after adding the JS but I'll find out.
Edit Modal

To pass data to your fetch.php from JS I'd create a data array and use the POST method like the following:
var dataString = {
id: recipient,
other: 'string'
}
$.ajax({
type: "POST",
url: "fetch.php",
data: dataString,
cache: false,
success: function (data) {
console.log(data);
modal.find('.dash').html(data);
},
error: function(err) {
console.log(err);
}
});
and in your php:
$id = $_POST['id'];
$other = $_POST['other'];
//Do something with your data
Let me know if that helps.

Related

Getting Data from row which button is clicked

I have the following ajax that needs to pass the userID to a PHP script.
document.getElementById("delete").addEventListener("click", function(){
if (confirm("Are you sure you want to delete this user's account?")) {
$.ajax({
url: 'deleteUser.php?id='+<?php echo $userID ?>,
success: function(data) {
toastr.danger("User successfully deleted!");
}
});
} else {
}
});
I'm unsure how to actually get the row data from the button used since they're posted in the TD of each row as it goes through each record in the set. How would one accomplish this?
<table class="table table-bordered">
<thead class="thead-dark">
<tr>
<th scope="col">First Name</th>
<th scope="col">Last Name</th>
<th scope="col">Email</th>
<th scope="col">Username</th>
<th scope="col">Account Type</th>
<th scope="col">Actions</th>
</tr>
</thead>
<tbody>
<?php
$query = $pdo->query("SELECT * FROM accounts WHERE company ='".$res['company']."' ")->fetchall();
foreach($query as $row){
echo ' <tr>';
echo ' <td>'.$row['fname'].'</td>' ;
echo ' <td>'.$row['lname'].'</td>' ;
echo ' <td>'.$row['email'].'</td>' ;
echo ' <td>'.$row['account_name'].'</td>' ;
echo ' <td>'.$row['user_type'].'</td>' ;
echo ' <td><button id="delete" type="button" class="btn btn-danger"><i class="far fa-trash-alt"></i></button>';
echo ' <button id="edit" type="button" class="btn btn-info"><i class="fas fa-user-edit"></i></button> </td>';
echo ' </tr>';
}
?>
</tbody>
</table>
You can do it this way:
php:
foreach($query as $row){
echo ' <tr>';
echo ' <td>'.$row['fname'].'</td>' ;
echo ' <td>'.$row['lname'].'</td>' ;
echo ' <td>'.$row['email'].'</td>' ;
echo ' <td>'.$row['account_name'].'</td>' ;
echo ' <td>'.$row['user_type'].'</td>' ;
echo ' <td><button data-id="' . $row['id'] . '" type="button" class="btn btn-danger delete"><i class="far fa-trash-alt"></i></button>';
echo ' <button type="button" class="btn btn-info edit"><i class="fas fa-user-edit"></i></button> </td>';
echo ' </tr>';
}
Jquery:
$("button.delete").each(function(){
$(this).on('click', function(e){
if (confirm("Are you sure you want to delete this user's account?")) {
$.ajax({
url: 'deleteUser.php?id='+$(this).data('id'),
success: function(data) {
toastr.danger("User successfully deleted!");
}
});
} else {
//do something else
}
});
});
HTML 4.01 specification says ID must be document-wide unique.
HTML 5 specification says the same thing but in other words. It says that ID must be unique in its home subtree, which is basically the document if we read the definition of it.
I'd fix that first: <button id="delete" needs to be unique
Next - I'd add an onClick to your delete button so you have <button onclick="deleteUser(2);"
Then, I'd rewrite your listener registration to just be a function:
function deleteUser(id){
if (confirm("Are you sure you want to delete this user's account?")) {
$.ajax({
url: 'deleteUser.php?id='+<?php echo $userID ?>,
success: function(data) {
toastr.danger("User successfully deleted!");
}
}

how do i make my table output appear only when i click on the search button

how do i make my table output appear only when i click on the search button
<?php
require_once 'includes/header.php';
if ($_POST) {
$list = $_POST['categoryList'];
if ( $list != "") {
$sql = "SELECT product.product_name, product.product_image, product.category_id, product.active, category.category_name FROm product
INNER JOIN category on product.category_id = category.category_id
WHERE product.category_id = '".$_POST['categoryList']."' AND product.active = 1";
$result = $connect ->query($sql);
}
/*else{
$msg = echo 'Select category';
}*/
}
?>
HERE i am running a php script to pull data from the database table product
<div class="row">
<div class="col-md-12">
<div class="card mt-5" style="width: 30rem; margin-left: 25%" >
<div class="card-header bg-dark text-light"><span class="glyphicon glyphicon-th-list"></span> Categories </div>
<div class="card-body">
<form action="" method="post" enctype="multipart/form-data">
<div class="form-group row mt-5 ml-5">
<label for="categoryList" class="col-sm-8 col-form-label">Category Name</label>
<div class="col-sm-8">
<select class="form-control" id="categoryList" name="categoryList">
<option value="">--Select--</option>
<?php
$sql= "SELECT category_id, category_name FROM category where category_status = 1 AND category_status = 1";
$result =$connect->query($sql);
while ($row = $result->fetch_array()) {
echo '<option value="'.$row[0].'">'.$row[1].'</option>';
}
?>
</select>
</div>
</div>
<div class="col">
<button type="submit" onclick="myFunction()" class="btn btn-dark" id="searchButton" style="margin-left: 100px">Search </button>
</div>
</form>
</div>
This is the part where i select the categories pulled from the database
</div>
</div>
</div>
<div id="myDiv">
<table class="table" id="myTable">
<thead class="thead thead-dark">
<th>Photo</th>
<th>Name</th>
<th>Category</th>
</thead>
<tbody>
<?php
#$sql = "SELECT product.product_name, product.product_image, product.category_id, product.active, category.category_name FROM product
INNER JOIN category on product.category_id = category.category_id
WHERE product.category_id = '".$_POST['categoryList']."' AND product.active = 1";
$result = $connect ->query($sql);
while($row = $result->fetch_assoc())
{
$imageUrl = substr($row['product_image'], 3);
$name = $row['product_name'];
$category = $row['category_name'];
?>
<tr>
<td><?php echo '<img class="img-round" src='.$imageUrl.' style="height:30px; width:50px;">'?></td>
<td><?php echo $name?></td>
<td><?php echo $category?></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
THIS IS THE TABLE THAT DISPLAYS THE PRODUCTS ON IN THE SELECTED CATEGORY ABOVE
<script>
$("#navDashboard").addClass('active');
$("#myTable").DataTable();
</script>
THIS IS THE SCRIPT RESPONSIBLE FOR DATATABLE AND ACTIVE NAVBAR
generally what I am doing is using ajax. give your form an id . for example en ajax call after submitting button
$(document).on('submit', '#show_table', function () {
event.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
type: 'POST',
url: 'your_file.php',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: (
function (formData) {
$(".result").html(formData)
}
)
});
});
in the URL pass the name of the file where the call will be made (create a new file). the value from the search input will pass in POST TYPE and then run your query . as you can see the result will display in a div with a class of result. so in the search page create a div
and the table will appear there .
the page will not be refreshed based on the event.preventDefault();
hope this give you any help :)

submit a form without page reload

I have a scenario where on page load, a div is on display: none; and when i press button-A it toggles the div. This div acts as a search div window where end users can do search against database. But since the div is on display: none; when i submit a form on the search div window, it reloads the page and goes back to default where search div window is on display: none;
So, the data call actually executes and returns the rows i need. But I need to press the button-A again just to show the div that contains the results.
is there a workaround for this? i've read a little about ajax but i haven't really found a working solution for my case.
i have something like this. (sorry for not knowing good format on posting. its my first time to post here.)
<button id="hideshow" class="hideshow" type="submit">search</button>
<div class="search_div_wrapper" style="display: none;">
<form action="" method="POST">
<input type="text" name="search_field">
<button name="search" id="submit">search</button>
</form>
<?php
// some codes are here to query and display rows from search_field input
?>
</div>
<script>
jQuery(document).ready(function(){
jQuery('.hideshow').on('click', function(event) {
jQuery('#search_div_window').toggle('show');
});
});
</script>
$(function(){
$(".search").keyup(function()
{
var searchid = $(this).val();
var dataString = \'search=\'+ searchid;
if(searchid!=\'\')
{
$.ajax({
type: "POST",
url: "search.php",
data: dataString,
cache: false,
success: function(html)
{
$("#result").html(html).show();
}
});
}return false;
});
jQuery("#result").on("click",function(e){
var $clicked = $(e.target);
var $name = $clicked.find(\'.name\').html();
var decoded = $("<div/>").html($name).text();
$(\'#searchid\').val(decoded);
});
jQuery(document).live("click", function(e) {
var $clicked = $(e.target);
if (! $clicked.hasClass("search")){
jQuery("#result").fadeOut();
}
});
$(\'#searchid\').click(function(){
jQuery("#result").fadeIn();
});
});
<div class="form-group">
<input type="text" placeholder="search by name" name="search_text" class="form-control search" id="search_text"></div>
<div id="result"></div>
<!-- search.php--->
<?php
$conn = mysqli_connect("localhost", "root", "", "insert");
$output = "";
$sql = "SELECT * FROM inserdata WHERE name LIKE '%".$_POST['search']."%'";
$result = mysqli_query($conn,$sql);
if(mysqli_num_rows($result) > 0)
{
$output .= '<h4 align="center">Search Result</h4>';
$output .= '<div class="table-responsive">
<table class="table table-bordered">
<tr>
<th>Name</th>
<th>Email</th>
<th>Phone Number</th>
<th>Address</th>
<th>Gender</th>
<th>Desc</th>
</tr>';
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td>'.$row["name"].'</td>
<td>'.$row["email"].'</td>
<td>'.$row["phn"].'</td>
<td>'.$row["address"].'</td>
<td>'.$row["gender"].'</td>
<td>'.$row["desc"].'</td>
</tr>
';
}
echo $output;
}
else {
echo "data not found";
}
?>
you can check if there is any result after loading. and show the search_div_wrapper if there is any
var $ = jQuery;
$(window).load(function(){
if($('.result_div_wrapper').html().trim().length > 0) {
console.log($('.result_div_wrapper').html().trim().length)
$('.result_div_wrapper').toggleClass('active');
}
});
and add this to your css
.active{
display: block !important;
}
.result_div_wrapper{
display: none;
}

Update Database Record with Ajax in Codeigniter

I am trying to update database records using ajax from the ajax response, getting success message but the actual database records are not updated at all. But it wonder how the ajax response should throw the success message while the query is not updating the database.
VIEW:
// AJAX code to update the database
// update marks when form is submitted
$('#updateMarks').on('submit',function(event) {
event.preventDefault();
var practical_mark = $("#mark_written").val();
var written_mark = $("#mark_practical").val();
var comment = $("#comment").val();
var mark_id = $("#mark_id").val();
$.ajax({
type: "POST",
url: "<?php echo site_url('admin/exam_marks_update'); ?>",
data: { practical_mark : practical_mark,
written_mark: written_mark,
comment : comment,
mark_id : mark_id
},
success: function(response)
{
alert("success");
},
error: function(){
alert("Error");
},
});
});
<?php foreach($marks as $row2): ?>
<form method="post" role="form" id="updateMarks">
<tr>
<td class="text-center"><?php echo $student['name']; ?></td>
<td>
<!-- create two col table for marks category -->
<table class="table table-bordered table-hover toggle-circle">
<thead>
<tr>
<th data-toggle="true" class="text-center"><?php echo get_phrase('written_exam'); ?></th>
<th data-toggle="true" class="text-center"><?php echo get_phrase('practical_exam'); echo get_phrase('_(out_of_100)'); ?></th>
</tr>
</thead>
<tbody>
<tr>
<td class="text-center"><input type="number" value="<?php echo $row2['written_mark_obtained'];?>" id="mark_written" name="mark_written" class="form-control" /></td>
<td class="text-center"><input type="number" value="<?php echo $row2['practical_mark_obtained'];?>" id="mark_practical" name="mark_practical" class="form-control"/></td>
</tr>
</tbody>
</table>
<!-- end create two col table for marks category -->
</td>
<td class="text-center"><textarea class="form_control" id="comment" name="comment" rows="4" > <?php echo $row2['comment'] ?> </textarea></td>
<td class="text-center">
<input type="hidden" id="mark_id" name="mark_id" value="<?php echo $row2['mark_id'];?>" />
<button type="submit" class="btn btn-block btn-success btn-md"><i class="icon pe-pen" aria-hidden="true"></i><?php echo get_phrase('update'); ?></button>
</td>
</tr>
</form>
<?php endforeach; ?>
Controller:
function exam_marks_update(){
$data['written_mark_obtained'] = $this->input->post('written_mark');
$data['practical_mark_obtained'] = $this->input->post('practical_mark');
$data['comment'] = $this->input->post('comment');
$this->crud_model->update_student_marks($data, $this->input->post('mark_id'));
}
MODEL
function update_student_marks($data, $mark_id){
$this->db->where('mark_id', $mark_id);
$this->db->update('mark', $data);
}
Jquery ajax success callback function is always called if the request to server succeeds. You need to return response data from server to verify when database operation was successful or not. I have edited your code , this might work for you.
MODEL
function update_student_marks($data, $mark_id){
.....
return $this->db->update('mark', $data);
}
Controller::
function exam_marks_update(){
.....
if($this->crud_model->update_student_marks($data, $this->input->post('mark_id'))){
echo json_encode(array('success' => true));
exit;
} else {
echo json_encode(array('success' => false));
exit;
}
}
View
$.ajax({
type: "POST",
url: "<?php echo site_url('admin/exam_marks_update'); ?>",
dataType :'json',
data: { practical_mark : practical_mark,
written_mark: written_mark,
comment : comment,
mark_id : mark_id
},
success: function(response)
{
if (response.success === true){
alert("success");
} else {
alert('failed');
}
},
error: function(){
alert("Error");
},
});
Your Controller retrieving inputs which doesn't exists... you need to pass your name, id as inputs and not the value which you echo... see as Controller:
function exam_marks_update(){
$data = array(
'written_mark_obtained' => $this->input->post('written_mark'),
'practical_mark_obtained' => $this->input->post('practical_mark'),
'comment' => $this->input->post('comment')
);
$this->db->where('mark_id', $this->input->post('mark_id'));
$this->db->update('mark', $data);
}
and change this:
var comment = $("#comment").val();
to
var comment = $("#comment").html();
As comment is textarea...

populating multiple fields based on value selected with ajax

I'm trying to make two fields auto-fill after an item that generated from database been "selected". I'm not sure where did I made the mistake. I also used firebug but it doesn't show any error message. It just won't populate after I selected an item from dropdown menu. Please help me out and let me know where I did wrong.
Here is the script:
<script type="text/javascript" language="javascript">
$(function () {
$('#description').bind('input', function () {
$(this).val() // get value
$.ajax({
type: 'POST',
url: 'orderAuto.php',
data: {
url: $('#description').val()
},
dataType: 'json',
success: function (data) //on recieve of reply
{
var skuId = data[0];
var unitPrice = data[1];
$('#sku_1').val(skuId);
$('#uPrice_1').val(unitPrice);
}
});
});
});
</script>
Here is my form with fields and section from database:
<form name="form" method="get">
<table width="70%" border="5" align="center"><tr>
<th scope="row">Item Name</th>
<th scope="row">Item SKU</th>
<th scope="row">Quantity</th>
<th scope="row">Special Note</th>
<th scope="row">Unit Price</th>
<th scope="row">Total Price</th>
</tr>
<tr>
<th scope="row">
<?php
include('connect.php');
$result = mysqli_query("SELECT description FROM products")
or die(mysqli_error());
print '<select name="description" id="description" value="description">';
print '<option value="" disabled selected>Please Select A Product</option>';
while ($info = mysqli_fetch_array($result))
{
$p = $info["description"];
$p = htmlspecialchars($p);
printf('<option value="%s">%s</option>', $p, $p);
}
print '</select>';
?>
</th>
<th scope="row"><input name="sku_1" id="sku_1" readonly /></th>
<th scope="row"><input name="qty_1" /></th>
<th scope="row"><input name="note_1" /></th>
<th scope="row"><input name="uPrice_1" id="uPrice_1" readonly /></th>
<th scope="row"><input name="tPrice_1" readonly /></th>
</tr>
</table>
<input type="submit"/>
</form>
And here is orderAuto.php:
<?php
include('connect.php');
$p = $_POST['description'];
$result = mysqli_query("SELECT sku_id, unit_price FROM products WHERE description= '".$p."'");
$array = mysqli_fetch_array($result);
echo json_encode($array);
?>
Updates
<script type="text/javascript" language="javascript">
$(function () {
$('#description').change(function () {
$.ajax({
type: 'POST',
url: 'orderAuto.php',
data: {
description: $(this).val()
},
dataType: 'json',
success: function (data) //on recieve of reply
{
var skuId = data[0];
var unitPrice = data[1];
$('#sku_1').val(skuId);
$('#uPrice_1').val(unitPrice);
}
});
});
});
</script>
and
<?php
include('connect.php');
$p = mysqli_real_escape_string($_POST['description']); // should be doing this
$result = mysqli_query("SELECT sku_id, unit_price FROM products WHERE description= '".$p."'");
$array = mysqli_fetch_array($result);
echo json_encode($array);
?>

Categories

Resources