dynamic dropdown menu not working - php

i'm trying to make a notification tab work but do not seem to get it right. The dropdown is working fine but the ajax call is not working right, when viewed with firebug there are results but not seen in the dropdown.Quite confusing. (note the dropdown menu is located in header and can only be displayed if the session is initialised) here is the ajax used in jquery:
function load_notifications(view=''){
$.ajax({
url: "notification/new_friends.php",
method: "POST",
data:{view:"view"},
dataType:"json",
success: function(data){
$(".dropdown-menu").html(data.notification);
if(data.unseen_notification>0){
$(".badge1").html(data.unseen_notification);
}
}
});
//$(".dynamic-notification").load("notification/pm_n.php");
// $(".dynamic-notification-f").load("notification/new_friends.php");
};
load_notifications();
$(document).on("click",".count_friend", function(){
load_notifications('yes');
});
//loads every 2 seconds for chat
setInterval(function(){load_notifications();},2000);
here is the new_friends.php content:
<?php
include '../includes/dbconfig.inc.php';
if (isset($_POST['view'])) {
if($_POST['view'] !=''){
$update="update friends set count='1' where friend_one=:session and count='0'";
$stmt=$conn->prepare($update);
$stmt->bindValue(":session", $_SESSION['uname']);
$stmt->execute();
}
$sql123="select id from friends where friend_two=:sess_uname and count='0'";
$stmt123=$conn->prepare($sql123);
$stmt123->bindValue(":sess_uname", $_SESSION['uname']);
$stmt123->execute();
$request_count=$stmt123->fetchColumn();
//$count_friend=$stmt123->rowCount();
/*$sql_f_count="select *from user where user_id=:session_id and activated='1' limit 1";
$stmt_f_count=$conn->prepare($sql_f_count);
$stmt_f_count->bindValue(":session_id", $_SESSION['id']);
$stmt_f_count->execute();
$user_details=$stmt_f_count->fetchAll();
$friend_badge=$user_details[0]['friend_count_badge'];*/
require "notification/friend_request_notification.php";
// $new_friends="<span class='dropdown'><a href='#' data-placement='bottom' class='btn dropdown-toggle' data-toggle='dropdown' title='Friend Requests' data-html='true'><span class='count_friend' style=' height:33px; width:30px;'><span class='badge1 label label-pill'>".$count."</span><img src='img/logo/group-button-white.png' style='height:25px; width:27px;' alt='new_friends_alert'></span></a><ul class='dropdown-menu'></ul></span>";
//if($request_count[0]>0){
//$new_friends="<a href='#' data-placement='bottom' class='btn' data-trigger='focus' title='Friend Requests' data-toggle='popover' data-html='true' data-content='".$friend_requests."'><span class='count_friend' style=' height:33px; width:30px;'><img src='img/logo/group-button-white.png' style='height:25px; width:27px;' alt='new_friends_alert'></span><span class='badge'>".$friend_badge."</span></a>";
/*}else{
$new_friends="<a href='all_notifications.php'><img src='img/logo/group-button-black.png' style='height:25px; width:27px;' alt='new_friends_alert'></a>";
}*/
//echo $new_friends;
//}
$data=array(
'notification'=>$friend_requests,
'unseen_notification' =>$request_count[0][0]
);
and the code for friend requests output:
<?php
//error_reporting(0);
require_once 'includes/dbconfig.inc.php';
$sql = "select * from friends where friend_two=:session and accepted='0' order by friends_date_made asc";
$stmt = $conn->prepare($sql);
$stmt->bindparam(":session", $_SESSION['uname']);
$stmt->execute();
$numrows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$friend_requests="";
if ($numrows < 1) {
$friend_requests = "You do not have any friend requests";
echo "$friend_requests";
exit();
} else {
foreach ($numrows as $i=>$row1 ) {
$reqid = $row1['friend_id'];
$user1 = $row1['friend_one'];
$datemade = $row1['friends_date_made'];
$datemade1 = strftime("%B %d, %y", strtotime($datemade));
$sql = "SELECT * FROM user WHERE uname=:user1 LIMIT 1";
$stmt = $conn->prepare($sql);
$stmt->bindparam(":user1", $user1);
$stmt->execute();
$thumbrow = $stmt->fetchAll(PDO::FETCH_ASSOC);
$user1avatar = $thumbrow[$i]['avatar'];
$user1id=$thumbrow[$i]['user_id'];
if ($user1avatar =="") {
$user1pic = '<img src="img/avatardefault.png" height="50" style="float:left;" width="50" alt="'.$user1.'" class="user_pic">';
} else {
$user1pic = '<img src="../user/user/'.$user1id.'/'.$user1avatar.'" height="50" style="float:left;" width="50" alt="'.$user1.'" class="user_pic">';
}
$friend_requests .= '<li><div id="'.$reqid.'" float="right" class="friendrequests">
'. $user1pic .'
<div class="user_info '.$reqid.'" id="'.$reqid.'"><small>' . $datemade1 . '</small>
'.$user1.' is requesting your friendship<br /><br />
<button id="'.$reqid.'" name="'.$_SESSION['uname'].'" sess="'.$_SESSION['id'].'" class="accept_btn btn btn-warning">Accept</button><span class="show-spinner"></span> or
<button id="'.$reqid.'" name="'.$_SESSION['uname'].'" sess="'.$_SESSION['id'].'" class="reject_btn btn btn-warning">Reject</button>
</div>
</div><hr></li>';
}
}

Here is drop down populate, if can you help:
<?php
// Assume $db is a PDO object
$dbh = new PDO('mysql:host=localhost;dbname=populatedropdown', "root", "");
$query = $dbh->query("select * from position"); // Run your query
echo '<form action="populate.php" method="get">';
echo '<select name="populate">'; // Open your drop down box
// Loop through the query results, outputing the options one by one
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
echo '<option value="'.$row['id'].'">'.$row['name'].'</option>';
}
echo '</select>';// Close your drop down box
echo '<input type="submit" name="edit" value="Edit">';
echo '</form>';
?>

Related

PHP Script running without redirection

I have a database with two tables: accounts and recipes(each have their own ID column).
I have a page that displays all the recipes. I want to enable users to add recipes to their favourites in accounts table. Once user is logged in, $_SESSION['user_id'] is set.
I have script that will add the recipe id to the favourites in accounts table, but I don't know how to run it without redirecting from the page that displays all recipes.
Here is what i have so far:
_view.php
<?php
$result = $mysqli->query("SELECT * FROM recipes");
if ( $result->num_rows == 0 ){
$_SESSION['message'] = "Error!";
echo "<div class='error-mess'>" . $_SESSION['message'] . "</div>";
}
else {
while ($row = mysqli_fetch_array($result)) {
$slug = $row['slug'];
$ingr = json_decode($row['ingr']);
$ingr_count= count($ingr);
$id = $row['id'];
echo '<div class="container recipe mb-2">';
echo '<img class="" src="/images/recipes/';
echo $row['img'];
echo '"/>';
echo '<div class="title-cats"><a href = "/recipe_preview.php?slug=' . $slug . '">';
echo $row['title'];
echo '</a></div>';
echo '<h4>Ingredients:</h4><br>';
for($i = 0; $i<$ingr_count;$i++){
$num = $i + 1;
echo $num . '. ';
$ingrs = json_decode($ingr[$i],true);
print_r($ingrs[0]);
echo '<br>';
}
echo '<br><button type="submit" class="btn" name="add">Read More</button>';
//favourites link
echo '<span class="fa fa-heart ml-3"></span>';
echo '</div><hr>';
}
}
_favourite.php
<?php
//relationship
require 'db.php';
$user_id = $_SESSION['user_id'];
//$favourite_id = $_POST['fav'];
$favourite_id = $_GET["id"];
echo $favourite_id;
echo $user_id;
$result = $mysqli->query("SELECT favourites FROM accounts WHERE id ='$user_id'");
if ( $result === null) {//doesnt work
$favs = array();
array_push($favs,$favourite_id);
$new_favs = json_encode($favs);
echo 'null';
}
else{
$favs = array();
$result = json_decode($result,true);
array_push($favs, $result);
array_push($favs,$favourite_id);
$new_favs = json_encode($favs);
}
$sql = "UPDATE accounts SET favourites ='$new_favs' WHERE id = '$user_id'";
if ( $mysqli->query($sql)){
echo '<div class="error-mess">Recipe sucessfully saved!</div>';
}
else{
echo '<div class="error-mess">NOT</div>';
}
.js -jquery library is there
$(document).ready(function() {
$('#favourite').click(function(e) {
e.preventDefault(); // prevents the default behaviour of following the link
$.ajax({
type: 'GET',
url: $(this).attr('href'),
data: {
id: $(this).data('id'),
},
dataType: 'text',
success: function(data) {
// do whatever here
if(data === 'success') {
alert('Updated succeeded');
} else {
alert(data); // perhaps an error message?
}
}
});
});
});

Ajax success function trigger data

i have problem with my code. Lets say i have PHP site in background and this site do something. Lets say in this site i have $status = "1"; and in my ajax code i have:
$.ajax({
url: 'src/single.php',
type: 'POST',
data: {single:1, id:id},
success: function(data){
$('#live_data').val('');
$('#live_data').html(data);
}
});
and i want to know if it si possible to trigger $status from my php page. Something like
success: function(data){
if (data.status == '1') {
$('#live_data').val('');
$('#live_data').html(data);
} if (data.status == '2') {
$('#search_result').val('');
$('#search_result').html(data);
}
Thank you for help if you can :)
EDIT:
So here is my code:
first is for fetch data from db,
and second is for search data from db,
And third is for fetch single data from db.
It work good but problem is that when i click on row it display results 2times first from show and second from search
But in search it is correct.
This $('#live_data') is for show.php data and $('#search_result') is for search data. And when i click on row from show.php it will display result 2times. First from show.php and second from search.php but when i click on row from search.php it display correctly (only one result). I know it is cuz i have
$('#live_data').val('');
$('#live_data').html(data);
but when i want to hide duplicated result from show.php i do $('#search_result').val(''); but then i hide my single data from search.php
This is why i want to controll it with if statement
I attach images below
ajax for single data fetch:
//jeden zaznam
$(document).on('click', '.clickable-row', function(){
var id = $(this).data("id2");
$.ajax({
url: 'src/single.php',
type: 'POST',
data: {single:1, id:id},
success: function(data){
$('#live_data').val('');
$('#live_data').html(data);
$('#search_result').html(data);
}
});
});
First:
<?php
include("db.php");
$output = "";
$sql = "SELECT * FROM otk";
$result = mysqli_query($conn, $sql);
$output .= "<table class='table table-hover'>
<thead>
<tr>
<th>Číslo zákazky</th>
<th>Pozícia</th>
<th>Stav</th>
<th>Dátum</th>
<th>Operátor</th>
</tr>
</thead>";
while ($row = mysqli_fetch_array($result))
{
$output .= "<tr class = 'clickable-row' data-id2 ='".$row['id_otk']."'>
<td>".$row['kod_otk']."</td>
<td>".$row['poz_otk']."</td>
<td>".$row['stav_otk']."</td>
<td>".$row['datum_otk']."</td>
<td>".$row['op_otk']."</td>
</tr>";
}
$output .= "</table>";
echo $output;
?>
Second:
<?php
if (isset($_POST['search']))
{
include("db.php");
$search_text = mysqli_real_escape_string($conn, $_POST['search_text']);
$search = htmlspecialchars($search_text);
$output = "";
$output .= "
<table class='table table-hover'>
<thead>
<tr>
<th>Číslo zákazky</th>
<th>Pozícia</th>
<th>Stav</th>
<th>Dátum</th>
<th>Operátor</th>
</tr>
</thead>";
$sql = "SELECT * FROM otk WHERE kod_otk LIKE '%".$search."%'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
$output .= "
<tr class = 'clickable-row' data-id2 ='".$row['id_otk']."'>
<td>".$row['kod_otk']."</td>
<td>".$row['poz_otk']."</td>
<td>".$row['stav_otk']."</td>
<td>".$row['datum_otk']."</td>
<td>".$row['op_otk']."</td>
</tr>";
}
$output .= "</table>
<div class='d-flex justify-content-center'>
<button class='btn btn-primary' onclick='history.go();'>Späť</button>
</div>";
echo $output;
} else {
echo "Žiadny záznam";
}
}
?>
Third:
<?php
if (isset($_POST['single']))
{
include("db.php");
$id = mysqli_real_escape_string($conn, $_POST['id']);
echo "id je: ".$id;
$sql = "SELECT * FROM otk WHERE id_otk = '".$id."'";
$result = mysqli_query($conn, $sql);
$output = "<table class='table table-hovrt'>
<thead>
<tr>
<th>Číslo zákazky</th>
<th>Pozícia</th>
<th>Stav</th>
<th>Poradové číslo</th>
<th>Technológia</th>
<th>Dokument</th>
<th>Zariadenie</th>
<th>Operátor</th>
<th>Dátum</th>
</tr>
</thead>";
if (mysqli_num_rows($result) > 0)
{
while ($row = mysqli_fetch_array($result))
{
$output .= "
<tr>
<td>".$row['kod_otk']."</td>
<td>".$row['poz_otk']."</td>
<td>".$row['stav_otk']."</td>
<td>".$row['cislo_otk']."</td>
<td>".$row['tech_otk']."</td>
<td>".$row['dok_otk']."</td>
<td>".$row['zar_otk']."</td>
<td>".$row['op_otk']."</td>
<td>".$row['datum_otk']."</td>
</tr>";
}
$output .= "</table>
<div class='d-flex justify-content-center'>
<button class='btn btn-primary' onclick='history.go(-2);'>Späť</button>
</div>";
echo $output;
} else {
echo "Error: " . mysqli_error($sql);
}
}
?>
Image01:
Image02:
You must get the single and id vars with:
<?php
$single = $_POST['single'];
$id = $_POST['id'];
// do your logic and set it's status
echo json_encode(['status' => $status]);
Then you'll be able to retrieve the status param in your success data.
Your best bet would be to use json_encode()
example:
$result = array();
$result = array('status' => '1');
echo json_encode(result);
With the above, you'll be able to access the status key via jquery.

pdo button delete row

when specific user login it will display what he has books.. and inside each book delete button .. i want delete row when i clicked on delete button ... but when i clicked on delete button it reload the page please i need help
this getbooks function
public function getBooks($start = 0, $limit = 2)
{
$sql_start = $start * $limit;
$sql_limit = $limit;
//SELECT loginUser.username, Library.nameOfBook FROM loginUser JOIN userBook JOIN Library ON userBook.user_id = loginUser.id AND userBook.book_id = Library.id WHERE loginUser.username="loay";
$query = "SELECT Library.nameOfBook FROM loginUser JOIN userBook JOIN Library ON userBook.user_id = loginUser.id AND userBook.book_id = Library.id WHERE loginUser.username=:username LIMIT $sql_start, $sql_limit";
$statment = $this->db->prepare($query);
$statment->execute([
':username' => $this->username
//,':start' => $start, ':limit' => $limit
]);
$result = $statment->fetchAll();
echo "<table border='1'>
<form method='POST'>
<tr>
<th>Books</th>
<th>Action</th>
</tr>";
foreach($result as $row){
echo "<tr>";
echo "<td>" . $row['nameOfBook'] . "</td>";
echo "<td>" ."<input type='submit' name='delete' value='Delete' method='post' >" . "</td>";
echo "</tr>";
}
echo "</table>";
echo "</form";
if(isset($_POST['delete'])){
die("SS");
}
}
I made the delete functionality using jquery and ajax.
Above your form code add:
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
function deleteBook(b) {
$(document).ready(function() {
var book = $(b).parent('td').prev('td').html();
if(confirm("Are you sure you want to delete book - "+book+"?") == false){
return;
}
var ids = $(b).attr('id').substr(6).split('-');
var book_id_to_delete = ids[0];
var user_id = ids[1];
//alert("book_id is " + book_id_to_delete + ", user_id is " + user_id);
$.ajax({
type: "POST",
url: "" + "deletebook.php",
data: {
'book_id': book_id_to_delete,
'user_id': user_id,
submit: 'submit',
},
success: function(res) {
if (res == "deleted") {
$(b).closest('tr').remove();
} else {
alert(res);
}
}
});
});
}
</script>
In getBooks() function, I added id attribute (containing book and user ids) in delete button so our js code will know which books of a user should be deleted.
Replace your getBooks() function with:
<?php
public function getBooks($start = 0, $limit = 2)
{
$sql_start = $start * $limit;
$sql_limit = $limit;
$query = "SELECT Library.nameOfBook, userBook.book_id, userBook.user_id FROM loginUser JOIN userBook JOIN Library ON userBook.user_id = loginUser.id AND userBook.book_id = Library.id WHERE loginUser.username=:username LIMIT $sql_start, $sql_limit";
$statment = $this->db->prepare($query);
$statment->execute([
':username' => $this->username
]);
$result = $statment->fetchAll();
echo "<table border='1'>
<tr>
<th>Books</th>
<th>Action</th>
</tr>";
foreach($result as $row){
echo "<tr>";
echo "<td>" . $row['nameOfBook'] . "</td>";
echo "<td>" ."<input type='submit' id='delete".$row['book_id']."-".$row['user_id']."' onclick='deleteBook(this)' name='delete' value='Delete'>" . "</td>";
echo "</tr>";
}
echo "</table>";
echo "";
if(isset($_POST['delete'])){
die("SS");
}
}
?>
Create a class function that handles user's book deletion.
In your User class in User.php, add the following function:
public function deleteBook($book_id, $user_id)
{
$stmt = $this->db->prepare("DELETE FROM userBook WHERE book_id = :book_id AND user_id = :user_id");
$stmt->bindValue(":book_id", $book_id);
$stmt->bindValue(":user_id", $user_id);
return $stmt->execute();
}
The below code will be executed by via ajax so that the chosen book will be deleted from database.
Create a file named - deletebook.php
And add this code:
<?php
include_once('User.php');
if(isset($_POST['submit'])){
$object = new User();
if($object->deleteBook($_POST['book_id'], $_POST['user_id'])){
die('deleted');
}
else {
die("fail");
}
}
?>

change cell value on button click

I have a table with the following.
Table parts_stock
*--------------------*
| id | sku | stock |
| 1 | 101 | 2 |
| 2 | 102 | 3 |
*--------------------*
This is my code so far, i'm sure there are many ways to achieve this but ideally I want the qty value to change based on which button is clicked on without the page being refreshed (AJAX probably).
<tbody>
<?php
$query = 'SELECT stock_id, sku, in_stock ';
$query .= 'FROM parts_stock';
confirmQuery($query);
$select_skus = mysqli_query($connection, $query);
$num = mysqli_num_rows($select_skus);
if($num>0) {
while($row = mysqli_fetch_assoc($select_skus)) {
$id = $row['stock_id'];
$sku = $row['sku'];
$qty = $row['in_stock'];
echo "<tr>";
echo "<td>".$sku."</td>";
echo "<td>".$qty."</td>";
echo "<td>
<a href='' onclick='rem_qty()' id='minus' name='minus' class='btn btn-warning'><span class='glyphicon glyphicon-minus'></span></a>
<a href='' onclick='add_qty()' id='plus' name='plus' class='btn btn-success'><span class='glyphicon glyphicon-plus'></span></a>
</td>";
</td>";
}
}?>
</tbody>
ajax_search.js
<script>
function rem_qty(){
$.ajax({
type: "POST",
url: "update_qty.php",
data: {id_m: stock_id}
});
}
function add_qty(){
$.ajax({
type: "POST",
url: "update_qty.php",
data: 'id_p: stock_id'
});
}
</script>
update_qty.php file
<?php
if (isset($_POST['id_m'])) {
$r = $_POST['id_m'];
echo $r;
$cur_inv = "SELECT in_stock FROM parts_stock WHERE stock_id = '".$r."'";
$cur_query = mysqli_query($connection, $cur_inv);
while ($row = mysqli_fetch_assoc($cur_query)) {
$rem_stock = $row['in_stock'];
$rem_stock -= 1;
}
$inv_update = "UPDATE parts_stock SET in_stock = '".$rem_stock."' WHERE stock_id = '".$value."'";
$inv_query = mysqli_query($connection, $inv_update);
}
if (isset($_POST['id_p'])) {
$a = $_POST['id_p'];
echo $a;
$cur_inv = "SELECT in_stock FROM parts_stock WHERE stock_id = '".$a."'";
$cur_query = mysqli_query($connection, $cur_inv);
while ($row = mysqli_fetch_assoc($cur_query)) {
$add_stock = $row['in_stock'];
$add_stock -= 1;
}
$inv_update = "UPDATE parts_stock SET in_stock = '".$add_stock."' WHERE stock_id = '".$value."'";
}
?>
A simple and complete solution: just change mysqli_connect config in both page
index.php
<?php
$connection = mysqli_connect("localhost", "root", "", "dbname"); //change dbname
$query = 'SELECT id, sku, stock FROM parts_stock';
//confirmQuery($query);
$select_skus = mysqli_query($connection, $query);
$num = mysqli_num_rows($select_skus);
?>
<table>
<tr>
<th>Sku</th>
<th>Stock</th>
<th>Action</th>
</tr>
<?php if($num>0){
while($row = mysqli_fetch_assoc($select_skus)) {
$id = $row['id'];
$sku = $row['sku'];
$qty = $row['stock'];
echo "<tr>";
echo "<td>".$sku."</td>";
echo "<td class='stock-{$id}'>".$qty."</td>";
echo "<td>
<a class='btn btn-warning' onclick='add_qty({$id})' href='#'><span class='glyphicon glyphicon-minus'>Value Add</span></a>
<a class='btn btn-success' onclick='rem_qty({$id})' href='#'><span class='glyphicon glyphicon-plus'>Value Deduct</span></a>
</td>";
echo "</tr>" ;
}
}?>
</table>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script type="text/javascript">
function add_qty(id){
$.ajax({
type: "POST",
url: 'update_qty.php', //Relative or absolute path to response.php file
data: {id:id, type:'add'},
dataType: "json",
success: function (data) {
console.log(data);
if(data.success){
//successfully added
$(".stock-"+id).html(data.data.stock);
alert(data.msg);
}
}
});
}
function rem_qty(id){
$.ajax({
type: "POST",
url: 'update_qty.php', //Relative or absolute path to response.php file
data: {id:id, type:'rem'},
dataType: "json",
success: function (data) {
console.log(data);
if(data.success){
//successfully added
$(".stock-"+id).html(data.data.stock);
alert(data.msg);
}
}
});
}
</script>
update_qty.php
<?php
$connection = mysqli_connect("localhost", "root", "", "dbname"); ////change dbname
header('Content-Type: application/json');
$success = false; $msg ="";
if (isset($_POST['id'])) {
$id = $_POST['id'];
$cur_inv = "SELECT * FROM parts_stock WHERE id ={$id}";
$cur_query = mysqli_query($connection, $cur_inv);
if(mysqli_num_rows($cur_query)>0){ //if id is exist in database
if($_POST['type']=="add"){
$inv_update = "UPDATE parts_stock SET stock = (stock+1) WHERE id = {$id}"; //increase your stock dynamically
}elseif($_POST['type']=="rem"){
$inv_update = "UPDATE parts_stock SET stock = (stock-1) WHERE id = {$id}"; //increase your stock dynamically
}
$inv_query = mysqli_query($connection, $inv_update);
if($inv_query){ //If sucess
$msg = "Successfully Updated";
$success = true;
}else{ //if failed
$msg = "Failed to Update";
}
}else{
$msg="Id is not found.";
}
$last_inv = "SELECT * FROM parts_stock WHERE id ={$id}";
$last_query = mysqli_query($connection, $last_inv);
$row = mysqli_fetch_assoc($last_query);
echo json_encode(array('success'=>$success, 'msg'=>$msg, 'data'=>$row));
}
?>
No need extra js file just index.php and update_qty.php
Working example
demo.php
<?php
$query = 'SELECT id, sku, stock ';
$query .= 'FROM parts_stock';
confirmQuery($query);
$select_skus = mysqli_query($connection, $query);
$num = mysqli_num_rows($select_skus);
if($num>0) {
while($row = mysqli_fetch_assoc($select_skus)) {
$id = $row['id'];
$sku = $row['sku'];
$qty = $row['stock'];
$data = "";
$data .= "<tr>";
$data .= "<td>{$sku}</td>";
$data .= "<td>{$qty}</td>";
$data .= "<td>
<a class='btn btn-warning' href='inventory.php?source=edit_inventory&id={$id}'><span class='glyphicon glyphicon-minus'></span></a>
<a class='btn btn-success' href='inventory.php?source=edit_inventory&id={$id}'><span class='glyphicon glyphicon-plus'></span></a>
</td>";
echo $a;
exit;
}
}?>
AJAX:
<!DOCTYPE html>
<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script>
<table >
<tr>
<th>Id</th>
<th>Sku</th>
<th>Qty</th>
</tr>
<tbody id="mytable">
</tbody>
</table>
<button id="clickme">Click</button>
<script>
$(document).ready(function(){
$("#clickme").click(function() {
$.ajax({
url:"demo.php",
type:"GET",
beforeSend:function() {
$("#mytable").empty();
},
success:function(response){
$("#mytable").append(response);
}, error:function(err) {
console.log(err);
}
})
});
});
In your HTML Button to have a onClick event like this onclick="buttonSubtract1('<?php if(isset($val['itm_code'])){echo $val['itm_code'];}?>')"(You can fetch the itm_code from your db).Then Write your AJAX for Request and Response. And You need to Pass the itm_code through var x. e.g for like this xmlhttp.open("POST", "ajax/get_items.php?val=" +x, true);
In AJAX file
$item_cat = $_SESSION['item_cat']; // get a category from session
$iname=$_GET['val']; //get the value from main php file
if(!key_exists($item_cat)
{
$_SESSION['main'][$iname] = "1";
}
else
{
$_SESSION['main'][$item_cat][$iname]++;
}
echo "<pre>";
print_r($_SESSION['main']);
echo "</pre>";
EDIT 1
function buttonSubtract1(x)
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.location.assign('items.php');
}
}
xmlhttp.open("POST", "ajax/get_items.php?val=" +x, true);
xmlhttp.send();
}

php mysql update database on button click

as the title states I am trying to write a code that will update a boolean data in column (I called 'status') for a specific row. I used while loop in table to display the rows of new registered and where the status is NULL, I've put two buttons (accept, reject) each in td so they'll be displayed to each name, What I want is when the accept button clicked, it sets the status of its row in the table to 1, and when reject is clicked, same thing but sets 0 instead of 1.
I've did a lot of research over this but hit a road block after road block, so I really hope your help in this, many thanks!
Here is my code:
<table id="sHold" style="border:none;">
<?php
$conn = mysqli_connect('localhost', 'root', '', 'srs-db') or die('ERROR: Cannot Connect='.mysql_error($conn));
function getStudent () {
global $conn;
$query = "SELECT * FROM student_table WHERE status IS NULL;";
$result = mysqli_query($conn, $query);
$i = 1;
while ($row = mysqli_fetch_array($result)) {
$sId = $row['student_id'];
$sName = $row['student_name'];
echo "<tr id='sNew".$i."'>";
echo "<td>".$i." - </td>";
echo "<td>$sId</td>";
echo "<td>$sName</td>";
echo "<td><button name='sAcc".$i."'>Accept</button></td>";
echo "<td><button name='sRej".$i."'>Reject</button></td>";
echo "</tr>";
$i++;
}
if (isset($_POST['sAcc'.$i])) {
$row['status'] = 1;
}
}
getStudent();
?>
</table>
First of all, you miss <form> element. Your form inputs are useless without it, or without ajax.
Secondly, your $_POST check will only check last item. Since after you exit loop $i is set to last value in the loop. So your example will only work on last item.
<button> will now send $_POST with one of indexes sAcc or sRej. And it's value will be ID of your entry.
<table id="sHold" style="border:none;">
<form method="post" action="">
<?php
$conn = mysqli_connect('localhost', 'root', '', 'srs-db') or die('ERROR: Cannot Connect='.mysql_error($conn));
function getStudent () {
global $conn;
$query = "SELECT * FROM student_table WHERE status IS NULL;";
$result = mysqli_query($conn, $query);
$i = 1;
while ($row = mysqli_fetch_array($result)) {
$sId = $row['student_id'];
$sName = $row['student_name'];
echo "<tr id='sNew".$i."'>";
echo "<td>".$i." - </td>";
echo "<td>{$sId}</td>";
echo "<td>{$sName}</td>";
echo "<td><button type='submit' name='sAcc' value='{$sId}'>Accept</button></td>";
echo "<td><button type='submit' name='sRej' value='{$sId}'>Reject</button></td>";
echo "</tr>";
$i++;
}
}
if (isset($_POST['sAcc']) && intval($_POST['sAcc'])) {
$user_id = (int) $_POST['sAcc'];
// Do the database update code to set Accept
}
if (isset($_POST['sRej']) && intval($_POST['sRej'])) {
$user_id = (int) $_POST['sRej'];
// Do the database update code to set Reject
}
getStudent();
?>
</form>
</table>
Tip: I assume you're beginner. I remade your code. But you dont need to put this code into function. Use functions to handle data retrieval for example. Dont use it to display html.
<table id="sHold" style="border:none;">
<?php
$conn = mysqli_connect('localhost', 'root', '', 'srs-db') or die('ERROR: Cannot Connect='.mysql_error($conn));
function getStudent () {
global $conn;
$query = "SELECT * FROM student_table where status='NULL'";
$result = mysqli_query($conn, $query);
$i = 1;
while ($row = mysqli_fetch_array($result)) {
$sId = $row['student_id'];
$sName = $row['name'];
echo "<tr id='".$sId."'>";
echo "<td>".$i." - </td>";
echo "<td>$sId</td>";
echo "<td>$sName</td>";
echo "<td><button name='sAcc' id='acc-".$sId."' onclick='approveuser(this.id)'>Accept</button></td>";
echo "<td><button name='sRej' id='rec-".$sId."' onclick='approveuser(this.id)'>Reject</button></td>";
echo "</tr>";
$i++;
}
}
getStudent();
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
function approveuser(id){
trid=id.split('-')[1];
//alert(trid);
$.ajax({
url: "update.php",
type:"post",
data:{ val : id },
success: function(result){
//alert(result);
$('table#sHold tr#'+trid).remove();
alert('Updated');
}
});
}
</script>
//The code give below this update.php pge(ajax page)
<?php
$data=$_POST['val'];
$status =explode('-',$data);
$user_id=$status[1];
if($status[0]=='acc'){
$value=1;
}
elseif($status[0]=='rec'){
$value=0;
}
$conn = mysqli_connect('localhost', 'root', '', 'srs-db') or die('ERROR: Cannot Connect='.mysql_error($conn));
mysqli_query($conn,"update student_table set status='$value' where student_id=$user_id");
?>

Categories