how to set varialble - javascript

In my DB i have created a table named "coursePlaces" in which i have 7 columns and a number of rows.
Loading the php-file course.php I connects to the db and selects data from the table "coursePlaces" using it to echo a number of buttons with different id and value each:
<?php
/* CONNECTION TO DB */
require 'includes/dbh.inc.php';
/* ACCESS COURSE AND GRADE VAR FROM URL WITH GET */
$course = $_GET['course'];
$grade = $_GET['grade'];
/* SELECTS DATA FROM TABLE AND ECHOES BUTTONS WITH DIFFERENT ID AND VALUE DEPENDING ON TABLE CONTENT */
$sql = "SELECT * FROM coursePlaces WHERE grade='$grade' AND course='$course'";
$result = mysqli_query($con, $sql);
while ($row = mysqli_fetch_array($result)) {
echo '<input type="submit" id="place-' . $row['placeName'] . '" value="' . $row['placeName'] . '">';
}
/* CONVERTS VAR TO USE IN JQUERY SCRIPT */
echo '<script>';
echo 'var grade = ' . json_encode($grade) . ';';
echo 'var course = ' . json_encode($course) . ';';
echo '</script>';
?>
<script src="includes/global.inc.js"></script>
<!-- DIV TO ECHO OUTPUT FROM PLACE.INC.PHP -->
<div class="selectedPlace" id="selectedPlace"></div>
When clicking one of the buttons the value should be send to the file "global.inc.js" In which i have placed a script used to listen for clicks:
$('input#$row['placeName']').on('click', function() {
var place = $('input#place-$row['placeName']').val();
if (place !='') {
$.post('includes/place.inc.php', {place: place, grade: grade, course: course }, function(data) {
$('div#selectedPlace').text(data);
});
}
});
My problem is, that I don't know what the name of the button id is - since it is created from a varchar in a database table. How do i bring this information over into my .js file, so the script posts individual value from button no matter what button the user presses on the courses.php.

Use jQuery to set your variable with Ajax ( method POST ).

Try to change code as below:
$('input[type="submit"]').on('click', function() {
var place = $(this).val();
if (place !='') {
$.post('includes/place.inc.php', {place: place, grade: grade, course: course }, function(data) {
$('div#selectedPlace').text(data);
});
}
});

set on click attribute when you echo your inputs:
echo sprintf('<input type="submit" id="place-%s" value="%s" onclick="yourfunction("%s", "%s", "%s") >', $row['placeName'], $row['placeName'], $grade, $course);
and separate this yourfunction function:
function yourfunction(place, grade, course){
$.post('includes/place.inc.php', {place: place, grade: grade, course: course }, function(data) {
$('div#selectedPlace').text(data);
});
}

You should use a generic click handler instead of the one you are using.
If all button have one common class you can listen to the click of all.
Add class inputBtn to following:
echo '<input type="submit" id="place-' . $row['placeName'] . '" value="' . $row['placeName'] . '" class="inputBtn">';
Change
$('input#$row['placeName']').on('click', function() {
to
$('.inputBtn').on('click', function() {
var btnID = $(this).prop('id');
var spltID = btnID.split('-'); //split from the - & spltID[1] will contain the part that you required.
}
This code is written like just for the sake of clarity. It is possible to make it more optimal like split() function can be called on btnID to reduce code line.

Related

How to incorporate PHP code toegether with HTML code in a javascript script?

I have a form that dynamically adds and removes elements.
I also have a drop down that is populated dynamically.
How can I put the two together?
Here is the code that I use to dynamically add and remove elements:
$(document).ready(function(e) {
var maxRows = 100;
var x = 1;
var phpcode = '<?php $stmt=$author_of_book->read_author_of_section(); $num=$stmt->rowCount(); if($num>0){ echo '<select name="author_of_book[]" id="author_of_book-list">'; echo '<option value="" disabled selected>Select</option>'; while($row = $stmt->fetch(PDO::FETCH_ASSOC)){ extract($row); echo '<option value="' .$row["author_of_book"]. '"data-author_of_book_id="' .$row["author_of_book_id"]. '">' .$row["author_of_book"]. '</option>'; } echo "</select>"; } ?>';
$("#add").click(function(e) {
if (x <= maxRows) {
$("#book_table").append("<tr><td>" + phpcode + "</td><td><select name='book_title[]' id='book_title-list'><option value='0' disabled selected>Select</option></select></td><td><button type='button' id='remove' class='btn btn-danger'>Remove</span></button></td></tr>");
}
});
$("#book_table").on('click', '#remove', function(e) {
$(this).closest('tr').remove();
});
});
The idea is that a user can add as many books as they wish.
When a user selects a particular author the next drop down will list the titles of all of the author's books.
Using this PHP code I dynamically populate a drop down list based on the previous drop down selection:
I have created two class files.
class author_of_book{
// database connection and table name
private $conn;
private $table_name = "author_of_book";
// object properties
public $author_of_book_id;
public $author_of_book;
public function __construct($db){
$this->conn = $db;
}
public function read_author_of_book(){
$query = "SELECT author_of_book_id, author_of_book
FROM " . $this->table_name . "
ORDER BY author_of_book";
// prepare query statement
$stmt = $this->conn->prepare($query);
// execute query
$stmt->execute();
return $stmt;
}
}
Here is the other class file:
class book_title{
// database connection and table name
private $conn;
private $table_name = "book_title";
// object properties
public $book_title_id;
public $author_of_book_id;
public $book_title;
public function __construct($db){
$this->conn = $db;
}
public function read_book_title(){
$query = "SELECT book_title_id, author_of_book_id, book_title
FROM " . $this->table_name . "
WHERE author_of_book_id = :author_of_book_id
ORDER BY book_title";
// prepare query statement
$stmt = $this->conn->prepare($query);
// santize
$this->author_of_book_id=strtoupper(htmlspecialchars(strip_tags($this->author_of_book_id)));
// bind value
$stmt->bindParam(":author_of_book_id", $this->author_of_book_id);
// execute query
$stmt->execute();
return $stmt;
}
}
I also have this php code for json file
// set json headers
header("Access-Control-Allow-Methods: GET");
header('Content-Type: application/json');
$author_of_book_id=isset($_GET['author_of_book_id']) ? $_GET['author_of_book_id'] : die('Author ID not found.');
// include database and object files
include_once 'config/database.php';
include_once 'objects/book_title.php';
// instantiate database and object
$database = new Database();
$db = $database->getConnection();
$book_title = new book_title($db);
$book_title->author_of_book_id = $author_of_book_id;
$stmt = $book_title->book_title();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($results);
Then in the form I use this code to render the drop down list with the help of javascript
// include database and object files
include_once 'config/database.php';
include_once "objects/author_of_book.php";
// instantiate database and objects
$database = new Database();
$db = $database->getConnection();
$qfs_section = new author_of_book($db);
$page_title = "Book Form";
include_once "layout_head.php";
?>
<table id="book_table">
<tr>
<th>Author</th>
<th>Title</th>
<th><button type="button" id="add">Add</button></th>
</tr>
</table>
<?php
include_once "layout_foot.php";
And last is is JavaScript code to make the dynamic drop down work
//Author
$(document).ready(function() {
// detect change of dropdown
$("#author_of_book-list").change(function() {
// get id of selected author
var author_of_book_id = $(this).find(':selected').data('author_of_book_id');
// set json url
var json_url = "book_title_type_json.php?author_of_book_id=" + author_of_book_id;
// get json data
jQuery.getJSON(json_url, function(data) {
// empty contents of book_title dropdown
$("#book_title-list").html("");
$("#book_title-list").append("<option value='0' disabled selected>Select</option>");
// put new dropdown values to book_title dropdown
jQuery.each(data, function(key, val) {
$("#book_title-list").append('<option value="' + val.book_title + '"data-book_title_id="' + val.book_title_id + ' ">' + val.book_title + '</option>')
});
});
});
});
My problem is that every time I incorporate my drop down code into the dynamic add-remove code something goes wrong. I was able to make the first drop down to work but not the second one.
You will need to use AJAX for that. See, what PHP interpreter does is to produce HTML and JavaScript as a string and send it that way to the browser. Therefore, in order for JavaScript to get values stored in PHP, it needs to communicate back with the server. That's what the XMLHttpRequest object is there in Vanilla JavaScript, or the JQuery AJAX is there for.
Or, if you just want the PHP code embedded into JavaScript to be executed before the JavaScript is sent to the browser, you can put it without the quotation marks. Like I've done here:
var highscore=<?php echo "\"".$highscore."\";"; ?>

PHP Query database

I have two containers, the first is a form (select) that contains names of players, the second is for images related to those players.
When a user changes the select value the image also changes to that particular players image.
I have created this in JQuery and everything works wonderful but with the amount of players I decided to look into databases.
To get a better understanding here's a short version of what I have in JQuery.
<select id="clubPlayers" name="clubPlayers"></select>
var PLAYER_NAMES = [
"Player 1",
];
var players = '';
for (var i=0;i<PLAYER_NAMES.length;i++){
players += '<option value="'+ PLAYER_NAMES[i] + '">' + PLAYER_NAMES[i] + '</option>';
PLAYER_NAMES.sort();
}
$('#clubPlayers').append(players);
// Players
$('#clubPlayers').on('change', function() {
$('.player-img>img').remove();
if ( this.value == 'Player 1'){
$(".player-img").append("<img src='players/player_1.png'>");
}
});
Now I want to recreate this but in PHP & Mysql. I have created a database, the database consists of 3 columns, They are "id" "player_name" & "player_image".
(player_image will be input as links to images)
I got as far as being able to query the db and loop the player_name's field as select elements.
<?php
$conn = new mysqli('localhost', 'root', '', 'players')
or die ('Cannot connect to db');
$result = $conn->query("SELECT id, player_name, player_image FROM player_info");
echo "<select id='clubPlayers' name='clubPlayers'>";
while ($row = $result->fetch_assoc()) {
unset($id, $player_name, $player_image);
$id = $row['id'];
$player_name = $row['player_name'];
$player_image = $row['player_image'];
echo '<option value="'.$player_name.'">'.$player_name.'</option>';
}
echo "</select>";
?>
That works great but I still need to get the players image link from the db and create an img tag with the link.
My question is, Can this (JQUERY)
$('#clubPlayers').on('change', function() {
$('.player-img>img').remove();
if ( this.value == 'Player 1'){
$(".player-img").append("<img src='players/player_1.png'>");
}
});
be recreated and added onto my existing PHP above.
You need to store the data of the image on the element.
$player_image = $row['player_image'];
echo '<option value="'.$player_name.'" data-image="'. $player_image .'">'.$player_name.'</option>';
and in your jQuery you access it from the selected option...
$('#clubPlayers').on('change', function() {
var image = $(this).data('image');
$('.player-img>img').remove();
$(".player-img").append("<img src='players/"+ image +"'>");
});
The selected option should be available in $(this) in context. If not, you'll need to add a .find(selectedValue)into the data line.

PHP: How to compare/save different ARRAYS from different WHILE loops and send data to AJAX?

I am working with two different tables that are in different servers.
I am trying to compare the USERNAME field values from table "workstation_userlogged" and
the MEMO_CODE field value (they are usernames) from table "telephony". I get the "memo_code" values with the use of a Stored Procedure as you will see in the code below.
How can I save all the results returned from both tables, loop through them to match all usernames and then save the data so it can be returned with AJAX? This script will only run when an AJAX request button is clicked. So, I need to bring the data back and display it like so:
If matching usernames from both tables:
user: JOE time: 300
If no matching usernames:
user: MARC time: N/A
Some usernames from "workstation_userlogged" do not exist in the other table and vice versa.
I know it has to do with handling arrays and all but I've been stuck for hours and wasn't able to accomplish it.I need to clarify things please ask.
Thanks in advance!
map.php HTML/AJAX: How do I fix this?
<!-- Show the results here-->
<div id="resultdiv" class="resultdiv" style="display:none"> </div>
<div id="aht"><!--aht button-->
<button id="aht_button">AHT</button>
</div><!--aht button-->
<script type="text/javascript">
$(document).ready(function() {
$('#aht').click(function(){
$.ajax({
type:"POST",
url : "show_aht.php",
data: { }, // pass data here
success : function(data){
}//end success
});//end ajax
});//end click
});//end rdy
show_aht.php: when AJAX request is sent
<?php
Stored PRocedure just to show what I did:
//get the StoredProcedure from the "query" field in the overlay table
//and store it as a variable for later use for the AHT button
if($row = mysqli_fetch_assoc($query_overlay_result)){
$sp_value = $row['query'];
}
Table workstation_userlogged:
The results from this WHILE LOOP need to be matched with the results of the StoredProcedure below
//the displayed users values will have to be matched with memo_code
$user_data = array();
while($row = mysqli_fetch_assoc($get_user_result)){
$user_data[] = "user: " .$row['username'];
}
This is where I am trying to compare both usernames and bring the data back
to map.php but had no luck.
/****************************************************
Execute the sp_value query when AHT button is clicked
/****************************************************/
//loop the result set
$memo_data = array();
while ($row = mysqli_fetch_assoc($dbh2_result)){
$memo_data[] = $row['memo_code'] . " " . $row['avg_handle_time'];
}
/*THIS ISNT WORKING*/
foreach($memo_data as $v){
foreach($user_data as $m){
if($v['memo_code'] == $m['username'])
echo " user: " .$m['username']. " time: " . $v['avg_handle_time'] . "<br>";
}
}
?>
So the first mistake is your use of json_encode($user_data) json encode is a function which converts an array into a string in the format of javascript object notation. It's to be used in conjecture with something like echo json_encode($obj); and recieved in javascript obj = JSON.parse(json);
Now since you have 2 arrays what you need to do is loop through both to find the matching names:
I'm not sure what memo_code is but it needs to be a username.
Your query is incorrect change it to something like.
$result = $sql->query("SELECT username FROM `$table1`;");
for ($user_data= array (); $row = $result->fetch_assoc(); $set[] = $row);
$result2 = $sql->query("SELECT memo_code FROM `$table2`;");
for ($memo_data= array (); $row = $result2->fetch_assoc(); $set[] = $row);
Now you can finally use the loop correctly:
foreach($memo_data as $v){
foreach($user_data as $m){
if($v['memo_code'] == $m['username '])
echo " user: " .$m['username ']. " time: " . $v['avg_handle_time'] . "<br>";
}
}
I found the solution basically I wasnt`t comparing arrays properly so here below is the new comparison.
$user_data = array();
while($row = mysqli_fetch_assoc($get_user_result)){
$user_data[] = $row['username'];
}
/****************************************************/
//loop the result set
$memo_data = array();
while ($row = mysqli_fetch_assoc($dbh2_result)){
$memo_data[] = array("memo_code" => $row['memo_code'],
"avg_handle_time" => $row['avg_handle_time']);
}
/**comparing usernames from both arrays*/
foreach($memo_data as $v){
foreach($user_data as $m){
//echo 'mem code is:'.$v['memo_code'].'username is:'.$m['username'];
if($v['memo_code'] == $m){
echo " User: " .$m. " Time: " . $v['avg_handle_time'] . "<br>";
}
elseif( $v['memo_code'] != $m){
echo " User: " . $m . " Time: N/A <br>";
}
}
}

Accessing JSON results from jQuery Ajax

I'm working on a web application to maintain the administration for a restaurant kind of type. The idea is to make new orders, put order items in that, check finance overviews etc...
I've also got a function to see all the orders in a list, when you select one of them, the order data (such as the name, emailadress, location of the customer) shows up in a another element inside the document.
I'm doing that with this function, every tr inside the has been given a custom attribute; the order_id. When selecting that, a class is given, called selectedRow.
function select_order(order) {
var item = $(order);
if (!item.hasClass("selectedRow")) {
if (!selectedOrderInformation.is(":visible")) {
switchScreen(selectedOrderInformation, financeOverview);
}
item.parent().find(".selectedRow").removeClass("selectedRow");
item.addClass("selectedRow");
selectedOrderInformation.html("loading......");
$.ajax({
url: "includes/functions/select-order.php",
type: "get",
data: {order_id: item.attr("data-order-index")},
success: function (data) {
selectedOrderInformation.html(data);
$("#delete-order-btn").prop("disabled", false);
}
});
} else {
console.log("DEBUG: Row is already selected");
}
}
The usage of that function is by doing this:
$("#list tbody tr").click(function () {
select_order(this);
});
At the first place, i was deploying all the HTML data via PHP. This took a pretty long time, it could take from 500ms to about 1 second. In my opinion thats pretty long.
I was doing that like this (select-order.php):
if (!empty($_GET['order_id'])) {
$order_id = $_GET['order_id'];
$order_data = Database::getInstance()->get_all_data_by_order_id($order_id);
$order_items = Database::getInstance()->get_order_items_by_order_id($order_id);
while ($row = mysqli_fetch_array($order_data)) {
echo "<h1>Klant informatie</h1>";
echo "<p>Voornaam: " . $row['first_name'] . "</p>";
echo "<p>Achternaam: " . $row['last_name'] . "</p>";
echo "<p>Emailadres: " . $row['email_adress'] . "</p>";
echo "<p>Klant informatie: " . $row['customer_info'] . "</p>";
echo "<br>";
echo "<h1>Bestellingsinformatie</h1>";
echo "<p>Order informatie: " . $row['order_info'] . "</p>";
echo "<p>Locatie: " . $row['location'] . "</p>";
echo "<p>Gemaakt op: " . $row['created'] . "</p>";
}
echo "<br>";
echo "<table>";
echo "<thead>";
echo "<tr>";
echo "<th>Product naam</th>";
echo "<th>Hoeveelheid</th>";
echo "</tr>";
echo "</thead>";
while ($row = mysqli_fetch_array($order_items)) {
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['quantity'] . "</td>";
echo "</tr>";
}
echo "</table>";
exit;
}
This goes together with the Database class with all the functions:
class Database extends mysqli
{
// single instance of self shared among all instances
private static $instance = null;
private $databaseHost = "";
private $databaseUser = "";
private $databasePassword = "";
private $databaseName = "";
public static function getInstance() {
if (!self::$instance instanceof self) {
self::$instance = new self;
}
return self::$instance;
}
public function __clone() {
trigger_error('Clone is not allowed.', E_USER_ERROR);
}
public function __wakeup() {
trigger_error('Deserializing is not allowed.', E_USER_ERROR);
}
function __construct() {
parent::__construct($this->databaseHost, $this->databaseUser, $this->databasePassword, $this->databaseName);
if (mysqli_connect_error()) {
exit('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
}
parent::set_charset('utf-8');
}
function get_all_data_by_order_id($order_id) {
$query = "SELECT customers.first_name,
customers.last_name,
customers.email_adress,
customers.customer_info,
orders.order_info,
orders.total_price,
orders.location,
orders.created
FROM customers
INNER JOIN orders ON customers.id = orders.customer_id
WHERE orders.id = {$order_id}";
return $this->query($query);
}
function get_order_items_by_order_id($order_id) {
$query = "SELECT `products`.`name`, `orders-items`.`quantity` FROM `orders-items`\n" . "INNER JOIN `products`ON `orders-items`.`products_id` = `products`.`id`\n" . "WHERE order_id=" . $order_id;
return $this->query($query);
}
}
Now someone told me i could better translate the data into json and return that, so i did this:
if (!empty($_GET['order_id'])) {
$order_id = $_GET['order_id'];
$order_data = Database::getInstance()->get_all_data_by_order_id($order_id);
$order_items = Database::getInstance()->get_order_items_by_order_id($order_id);
$rows = array();
while ($row = mysqli_fetch_array($order_data)) {
$rows[] = $row;
}
return json_encode($rows);
exit;
}
But as expected, nothing really happened. So i tried changing the javascript to this (trying it as a array because i'm returning it that way?), to deploy one piece of data:
$.ajax({
url: "includes/functions/select-order.php",
type: "get",
data: {order_id: item.attr("data-order-index")},
success: function (data) {
selectedOrderInformation.html(data['first_name']);
}
});
But that didn't work aswell.
Problems
The previous PHP code was to slow, so i had to find another way.
When trying to deploy HTML into the other screen, it doesnt do anything. It stays on the 'loading...' screen, so the success function was'nt reached.
Question
How can my piece of code be changed so it will actually deploy parts of the data from the mysql database?
In your $.ajax() call you should define what type your response data is expected to be, by adding the following parameter to the call:
dataType: 'json'
Also, you should try echo json_encode($rows); your data instead of returning it.
**Edit: you are receiving an array of arrays, so your original referencing in the success callback won't suffice. Having another look at your MySQL part, If you are only expecting one row to be returned by your query, then you can change your PHP to:
$row = mysqli_fetch_array($order_data);
echo json_encode($row); // instead of $rows
instead of the while loop. That way your selectedOrderInformation.html(data['first_name']); will most likely work.
To clean your query up a bit:
$query = "SELECT p.name, ot.quantity FROM orders-items AS ot
LEFT JOIN products AS p ON ot.products_id = p.id
WHERE ot.order_id = " . $order_id;
You could also switch your INNER JOIN to a LEFT JOIN in your "get order data" function. An inner join is absolutely useless here, as you'll have all your data paired based on the foreign keys anyways.
I would try secluding some of the codebase: try commenting out the Database::getInstance() calls, and supplementing some testdata into the processes. To put it short, fake a returned response, by declaring a $row = array('first_name' => 'Joe', 'order_date' => '2014-08-29 11:11:52', ...); and returning that. If its way faster, then your database server might be the bottleneck. If its still slow, then 500ms - 1000ms is actually argueably code related, it might be other hardware aspects that cause the problem. Or for example, do you have your jQuery library loaded from a CDN, or locally?
**Edit: As #Debflav pointed out (and I've also touched upon the matter), that your queries could benefit from not being executed as simple queries, but transforming them into prepared statements. For the full story you could start checking out PHP.net : Prepared Statements, or to keep it short:
Prepared statements look almost just like your everyday query, however variables are not just concatenated into the query string, rather bindings are used.
You use the database handler's prepare function instead of query - with this method, you are requesting the MySQL server to inspect your query and optimize it for later use (which will come handy if you're doing the same query over and over again, just with a few varying values).
For more detailed insights on the mechanics of prepared statements and how to get the hang of it for efficiently utilizing it in your projects I recommend you research the topic a bit, but as a quick conversion for your example at hand, it would look like this:
function get_all_data_by_order_id($order_id) {
$query = "SELECT c.first_name, c.last_name, c.email_adress, c.customer_info,
o.order_info, o.total_price, o.location, o.created
FROM customers AS c
LEFT JOIN orders AS o ON c.id = o.customer_id
WHERE o.id = :order_id";
$query_params = array(
':order_id' => $order_id
);
$preparedStatement = $this->prepare($query);
return $preparedStatement->execute($query_params);
}
and
function get_order_items_by_order_id($order_id) {
$query = "SELECT p.name, ot.quantity FROM orders-items AS ot
LEFT JOIN products AS p ON ot.products_id = p.id
WHERE ot.order_id = :order_id;";
$query_params = array(
':order_id' => $order_id
);
$preparedStatement = $this->prepare($query);
return $preparedStatement->execute($query_params);
}
And to reflect on how you would build up your JSON response with data including the order headers and the connected order-items would be:
if (!empty($_GET['order_id'])) {
$order_id = $_GET['order_id'];
$order_data = Database::getInstance()->get_all_data_by_order_id($order_id);
$order_items = Database::getInstance()->get_order_items_by_order_id($order_id);
$orderObject = array();
$orderObject['header'] = mysqli_fetch_array($order_data);
$orderObject['items'] = array();
while ($orderedItem = mysqli_fetch_array($order_items)){
$orderObject['items'][] = $orderedItem;
}
echo json_encode($orderObject);
}
This way your jQuery could look something as follows:
....
success: function (data) {
selectedOrderInformation.html('<h3>' + data['header']['first_name'] + '</h3><ul>');
$.each(data['items'], function(i, item) {
selectedOrderInformation.append('<li>' + item['name'] + ' x ' + item['quantity'] + '</li>');
});
selectedOrderInformation.append('</ul>');
}
....

Changing PHP function to Javascript/AJAX validation

I want to use AJAX/Javascript with PHP to carry out this following function and not have it all done by PHP itself. I have created a function which deletes an item from the MySQL database. It gives a validation to the user if they want to remove it by selecting Yes or No.
However, how would i change this so that it does the same function but the validation appears as a popupbox, and when Yes or OK is pressed it deletes the item from the database and reloads the page to show it has been removed.
I have provided the PHP code which relates to this function, but i want to specifically change this to using AJAX/Javascript as well in accordance with PHP.
<?php
// Delete Item Question to Admin, and Delete Product if they choose
if (isset($_GET['deleteid'])) {
echo 'Do you really want to delete product with ID of ' . $_GET['deleteid'] . '? Yes | No';
exit();
}
if (isset($_GET['yesdelete'])) {
// remove item from system and delete its picture
// delete from database
$id_to_delete = $_GET['yesdelete'];
$sql = mysqli_query($link,"DELETE FROM products WHERE id='$id_to_delete' LIMIT 1") or die (mysql_error());
// unlink the image from server
// Remove The Pic -------------------------------------------
$pictodelete = ("../inventory_images/$id_to_delete.jpg");
if (file_exists($pictodelete)) {
unlink($pictodelete);
}
header("location: inventory_list.php");
exit();
}
?>
<?php
// This block grabs the whole list for viewing
$product_list = "";
$sql = mysqli_query($link,"SELECT * FROM products ORDER BY date_added DESC");
$productCount = mysqli_num_rows($sql); // count the output amount
if ($productCount > 0) {
while($row = mysqli_fetch_array($sql)){
$id = $row["id"];
$product_name = $row["product_name"];
$price = $row["price"];
$stock = $row["stock"];
$date_added = strftime("%b %d, %Y", strtotime($row["date_added"]));
$product_list .= "Product ID: $id - <strong>$product_name</strong> - £$price - Stock: $stock - <em>Added $date_added</em> <a href='inventory_edit.php?pid=$id'>edit</a> • <a href='inventory_list.php?deleteid=$id'>delete</a><br />";
}
} else {
$product_list = "You have no products listed in your store yet";
}
?>
Your JS-File
$(document).ready(function() {
$('.delete').click(function() {
event.preventDefault();
var deleteId = $(this).parent().attr('id').val();
$.get('path/to/you/phpfile', {deleteId: deleteid}, function(data) {
var confirm = confirm(data);
if (confirm==true) {
$.get('path/to/you/phpfile', {yesdelete: 1});
}
});
});
});
In your PHP-File you have to remove header('Location: ...') and the block which grabs the list, wrap it in a function or etract it to another php file to call it with the a simliar ajax-command I used above. And you have to change th $product_list in the while-loop.
Product ID: <div id="$id">$id - <strong>$product_name</strong> - £$price - Stock: $stock - <em>Added $date_added</em> <a href='inventory_edit.php?pid=$id'>edit</a> • <div class="delete">Delete</div></div><br />
jQuery get the id-value of his parent-div. It´s actually not the best way, but something like this should work.

Categories