unable to retrieve selected array values [php] - javascript

To generate the stockroom drop down list
function einv_generateStockrmSelectDropdown($Stockrm,$field,$dropdown) {
//connect to database
base_connectDatabase();
echo "<select id=\"stockrm\" name=\"".$field."[]\" multiple=\"multiple\" style=\"align:left\" class=\"form-control\">";
if (isset($Stockrm) && ($Stockrm != "")) {
$stockrmname = einv_getStockrmDetail($Stockrm);
echo "<option value=\"". $Stockrm ."\">". $stockrmname['einv_stockrm_name'] ."</option>";
} else {
$Stockrm = 0;
}
$getStockrmSQL = base_executeSQL("SELECT * FROM einv_stockroom WHERE einv_stockrm_id<>" . $Stockrm . " ORDER BY einv_stockrm_name");
while ($Stockrmdata_row = base_fetch_array($getStockrmSQL)) {
if (base_num_rows($getStockrmSQL)!= 0) {
echo "<option value=\"".$Stockrmdata_row['einv_stockrm_id']."\">".$Stockrmdata_row['einv_stockrm_name']."</option>";
}
}
echo "</select>";
echo "<script src=\"../terms_base/js/jquery.multiple.select.js\"> </script>";
//Input some codes to split the dropdown and make it into the setSelects. By default, the first time = AutoSelectAll
if(isset($dropdown) && ($dropdown != "")) { //dropdown = 1;2;3
$SDDArrays = explode(";", $dropdown);
$countTrap0 = count($SDDArrays);
$drop = "$('#stockrm').multipleSelect(\"setSelects\", [";
$counting = 1;
foreach ($SDDArrays as &$value) {
if ($countTrap0 != $counting) {
$drop .= "'". $value . "',";
} else {
$drop .= "'". $value . "'";
}
$counting++;
}
$drop .= "]);\n";
} elseif (isset($dropdown)) { //dropdown=
$drop = "$('#stockrm').multipleSelect(\"uncheckAll\")";
} else { //
$drop = "$('#stockrm').multipleSelect(\"checkAll\")";
}
echo "<script>\n";
echo "$(function() {\n";
echo "".$drop."";
echo "});\n";
echo "$(\"#stockrm\").multipleSelect({ onClose: function() {
document.getElementById('search').click();
}});\n";
echo "$(\"#stockrm\").multipleSelect();\n";
echo "</script>";
//close the database
base_closeDatabase();
}
//This function is use to add new stock room
//code = stock room code
//name = stock room name
//desc = stock room description
//remark = stock room remark
//cat = stock room category
add stockroom function
function einv_addStockrm($code,$name,$desc,$remark,$cat)
{
//connect to database
base_connectDatabase();
$User = base_getUserDetail($_SESSION['uID']);
base_executeSQL("INSERT INTO einv_stockroom (einv_stockrm_code, einv_stockrm_name, einv_stockrm_desc, einv_stockrm_remark, einv_stockrm_cat)
VALUES ('" . $code . "', '" . $name . "', '" . $desc . "', '" . $remark . "', '" . $cat . "')");
base_addTransactionLog('Manage Stock Room', 'Add',
"
Stock Room Code = " . $code . " ||
Stock Room Name = " . $name . " ||
Stock Room Description = " . $desc . " ||
Stock Room Remark = " . $remark . " ||
Stock Room Category = " . $cat . "
");
//go to stock room page
echo '<script type="text/javascript">' . "\n";
echo 'window.location="../einventory/stockrm_list.php";';
echo '</script>';
//close the database
base_closeDatabase();
}
Edit stockroom
function einv_editStockrm($srid,$code,$name,$desc,$remark,$cat)
{
//connect to database
base_connectDatabase();
$User = base_getUserDetail($_SESSION['uID']);
$Stockroom = einv_getStockrmDetail($srid);
base_executeSQL("UPDATE einv_stockroom
SET einv_stockrm_code='" . $code . "',
einv_stockrm_name='" . $name . "',
einv_stockrm_desc='" . $desc . "',
einv_stockrm_remark='" . $remark . "',
einv_stockrm_cat = '" . $cat . "'
WHERE einv_stockrm_id=" . $srid . "");
base_addTransactionLog('Manage Stock Room', 'Edit',
"
Stock Room Code = " . $code . " ||
Stock Room Name = " . $name . " ||
Stock Room Description = " . $desc . " ||
Stock Room Remark = " . $remark . " ||
Stock Room Category = " . $cat . "
");
//go to stock room page
echo '<script type="text/javascript">' . "\n";
echo 'window.location="../einventory/view_stockrm.php?id='. $srid .'";';
echo '</script>';
//close the database
base_closeDatabase();
}
File name: add_Stockroom.php and edit_stockroom.php
I have a dropdown list named Stockroom where it displays an array of values.
Example:
Stockroom
[A]
[B]
[C]
When user clicks on [A], it will display relevant data fields that [A] possess (appears below stockroom ddl).
And as user clicks on [B], there is an onchange function that will then show [B] data fields (fields in A is deleted and replaced with B).
I am able to add the initial values however, as i want to edit and change the stockroom from [A] to [B] which will result in a whole new data to be stored, i am unable to do so.
Any ideas?
I believe i have to amend my edit stockroom function where i require a set of coding such as
If the array is selected, i have to delete existing data and add new data in accordance to the selected ID.

Related

send variable to another page via hyperlink and select it in <select> tag (HTML, Jquery)

I have 2 pages cpu and mobo. I have a MySQL databse table named cpu, this table is displayed on cpu page, i want the user to click on a cpu table row and a hyperlink to take them to mobo page where the cpu selected is selected in the tag to filter motherboards.
CPU page
Table:
Image
Code:
$sql = "SELECT name, price, id, mark, value, url, socket FROM cpu";
$result = $connection->query($sql);
if ($result->num_rows > 0) {
echo "<table id='myTable'><thead><tr><th>CPU</th><th>Price</th><th>Mark</th><th>Value</th><th>Socket</th><th>Image</th></tr></thead>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tbody><tr><td><a href='https://au.pcpartpicker.com/product/".$row["id"]."' target='_blank'>" . $row["name"]. "</a></td><td>" . $row["price"]."</td><td>" . $row["mark"]."</td><td>" . $row["value"]."</td><td>" . $row["socket"]."</td><td><img src=". $row["url"]." height='42' width='42'></td></tr></tbody>";
}
echo "</table>";
} else {
echo "0 results";
}
Motherboard page
Table:
Image
Code:
$sql = "SELECT name, price, id, socket, ramslots, maxram, chipset FROM motherboard";
$result = $connection->query($sql);
if ($result->num_rows > 0) {
echo "<table id='myTable'><thead><tr><th>Motherboard</th><th>Price</th><th>Socket</th><th>Chipset</th><th>Ram Slots</th><th>Max Ram</th></tr></thead>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tbody><tr data-socket='". $row['socket'] . "'><td><a href='https://au.pcpartpicker.com/product/" . $row["id"] . "' target='_blank'>" . $row["name"] . "</a></td><td>" . $row["price"] . "</td><td>" . $row["socket"] . "</td><td>" . $row["chipset"] . "</td><td>" . $row["ramslots"] . "</td><td>" . $row["maxram"] . "</td></tr></tbody>";
}
echo "</table>";
} else {
echo "0 results";
}
Select:
Image
Code (PHP):
if ($result->num_rows > 0) {
echo "<select name='CPUmenu'>";
echo "<option value=''>CPU</option>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<option value='". $row["socket"] . "'>".$row["name"]."</option>";
}
echo "</select>";
} else {
echo "0 results";
}
Code (Jquery):
$( document ).ready(function() {
$(function() {
$('select[name="CPUmenu"]').change(function(e) {
let socket = $(this).val();
$('tbody tr[data-socket]').show();
if (socket.length) {
$('tbody tr[data-socket!="' + socket + '"]').hide();
}
});
});
});
Expected result:
I need to change the hyperlink of each cpu row to link to mobo.php and send the cpu name along with it in url. On mobo i need the sent url to be selected from the group automatically
If you need any more details please ask.
Thanks
I solved my problem with the following code:
echo "<tbody><tr><td><a href='mobo.php?cpu_name=".$row["name"]."' target='_blank'>" . $row["name"]. "</a></td><td>" . $row["price"]."</td><td>" . $row["mark"]."</td><td>" . $row["value"]."</td><td>" . $row["socket"]."</td><td><img src=". $row["url"]." height='42' width='42'></td></tr></tbody>";
And
if(isset($_GET['cpu_name'])){
$namehref = $_GET['cpu_name']; //some_value
}
And
while($row = $result->fetch_assoc()) {
if ($row["name"] == $namehref) {
echo "<option value='". $row["socket"] . "' selected>".$row["name"]."</option>";
} else {
echo "<option value='". $row["socket"] . "'>".$row["name"]."</option>";
}
}

Phpmyadmin - stored routine is meant to return multiply rows in the javascript function but instead returns a single row

i have a stored routine called collection_get_category_suggestions which has the following sql
select *
from album
where category=InCategory;
This should return a list of multiple records based on a category the user chooses. When run in sql tab the result of the routine returns multiple values however when executed in the routine tab and JavaScript it will only return the first record. Here is my JavaScript function which handles sql.
function getCategorySuggestions(catid)
{
var categoryid = catid;
console.log(categoryid);
selectedcategory = categoryid;
$("#suggestionsTab").empty();
var url = "categories_xml.php?category=" + selectedcategory;
$.ajax({
type: "GET",
url: url,
dataType: "xml",
success: function(xml){
var album_title = $(xml).find('album_title').text();
console.log(album_title);
var artist = $(xml).find('artist').text();
var year = $(xml).find('year').text();
var imageurl = $(xml).find('imageurl').text();
var categoryinfo = "<h3>" + album_title + "</h3><p>" + artist + " (" + year + ")</p>";
//categoryinfo += "<img src='" + imageurl + "' alt='" + album_title + " Album Cover' height='200' width='200' />";
console.log(categoryinfo);
$('#suggestionsTab').append(categoryinfo);
},
error: function() {
alert("An error occurred while processing XML file.");
}
});
}
the console.log returns one record. Why is this? Thanks very much for any help
EDIT:
php script
<?php
// Include utility files
require_once 'include/config.php';
// Load the database handler
require_once BUSINESS_DIR . 'database_handler.php';
// Load Business Tier
require_once BUSINESS_DIR . 'collection.php';
header("Content-type: text/xml");
$response='<?xml version = "1.0" ?><albums>';
if (isset($_GET['category']))
{
$obj = Collection::GetCategorySuggestions($_GET['category']);
$album_title=$obj['album_title'];
$artist=$obj['artist'];
$category=$obj['category'];
$year=$obj['release_date'];
$imageurl="./images/" . $obj['image'];
$response .= '<album><album_title>' . htmlentities($album_title, ENT_QUOTES) . '</album_title>';
$response .= '<artist>' . htmlentities($artist, ENT_QUOTES) . '</artist>';
$response .= '<category>' . htmlentities($category, ENT_QUOTES) . '</category>';
$response .= '<year>' . $year . '</year>';
$response .= '<imageurl>' . htmlentities($imageurl, ENT_QUOTES) . '</imageurl></album>';
}
$response .= '</albums>';
echo $response;
?>
i should add that the collection.php function is
public static function GetCategorySuggestions($category)
{
// Build SQL query
$sql = 'CALL collection_get_category_suggestions (:category)';
// Build the parameters array
$params = array (':category' => $category);
// Execute the query and return the results
return DatabaseHandler::GetRow($sql, $params);
}
foreach loop
foreach($albumsarray as $album)
{
$album_id=$album['album_id'];
$album_title=$album['album_title'];
$artist=$album['artist'];
$response .= '<album><album_id>' . $album_id . '</album_id><album_title>' . htmlentities($album_title, ENT_QUOTES) . '</album_title><artist>' . htmlentities($artist, ENT_QUOTES) . '</artist></album>';
}

PHP Database Query: How to return the results from a while loop to a Javascript Variable?

I have a php query like so:
<?php
$query = "SELECT * FROM " . $usertable . " ORDER BY fname;";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
echo '<option value="' . $row['pkid'] . '">' . $row['fname'] . ' ' . $row['lname'] . '</option>';
}
?>
Within this same .php file I have some javascript. All I would like to do is return $row['fname'] as a a javascript variable.
Is this possible?
If you want to output the PHP variable in a JavaScript variable you could do something like this -
echo '<script>var name+' . $row['pkid'] . ' = ' .$row['fname'] . ';</script>';
This would give you a uniquely named variable for each row.

how to run a php function in javascript [duplicate]

This question already has answers here:
How can I call PHP functions by JavaScript?
(13 answers)
Closed 8 years ago.
<?php
session_start();
function printTable() {
$server = "XXXXXXXX";
$user = "XXXXXXXXX";
$password = "XXXXXXXX";
$database = "XXXXXXXX";
$conn = mysql_connect($server, $user, $password);
mysql_selectdb($database, $conn);
$query = "SELECT Image, ISBN, Name, Vol, Release_date, publisher, price FROM products p";
$resultset = mysql_query($query, $conn); // retrieve data from database
if ($resultset == null || $resultset == 1) {
echo mysql_error(); // print SQL error
die(); // exit PHP program
}
$numFields = mysql_num_fields($resultset);
echo "<table border=2 align=center><tr>";
echo "</tr>";
for ($i=0; $i<(mysql_num_rows($resultset)); $i++) { // print records
$fields = mysql_fetch_row($resultset);
echo "<tr>";
echo "<tr class=$color><td><img width=100px src=$fields[0]></td>";
echo "<td> Name: " . $fields[2] . " (vol.". $fields[3] . ")</br>";
echo "<br> ISBN: " . $fields[1] . "</br>";
echo "<br> Publisher: " . $fields[5] . "</br>";
echo "<br> Release Date: " . $fields[4] . "</br>";
echo "<br> Price: HK$ " . $fields[6] . "</td>";
echo "<td><input type=\"submit\" value=\"Add to Cart\" onclick=\"combine($fields[1], '$fields[2]', $fields[3]);\"/></td>";
$fields = mysql_fetch_row($resultset);
if ($fields == null) break;
echo "<td><img width=100px src=$fields[0]></td>";
echo "<td> Name: " . $fields[2] . " (vol.". $fields[3] . ")</br>";
echo "<br> ISBN: " . $fields[1] . "</br>";
echo "<br> Publisher: " . $fields[5] . "</br>";
echo "<br> Release Date: " . $fields[4] . "</br>";
echo "<br> Price: HK$ " . $fields[6] . "</td>";
echo "<td><input type=\"submit\" value=\"Add to Cart\" onclick=\"combine($fields[1], '$fields[2]', $fields[3]);\"/></td>";
echo "</tr>";
}
echo "</table>";
}
mysql_close();
?>
<html>
<head>
<script>
function combine(value1, value2, value3) {
alert (value1 + value2 + value3);
//setcookie(value1);
}
</script>
</head>
<title>
Product Page
</title>
<body>
<body style="background:#A2A2AE">
<h1> <center> Product Page </center> </h1>
<p><center>-----------------------------------------------------------------------------------------------------------------------------------------------------------</center></p>
<?php printTable(); ?>
</body></html>
how I can run the function addcookies() to save value 1 as the cookies... Thank you!
function addcookies(value) {
$pid = $_POST['pid'];
$expiry = time() + 60 * 60 * 24 * 30;
// Update the number of items
if(isset($_COOKIE['count']))
$count = $_COOKIE['count'];
else
$count = 0;
// Put the item into shopping cart
$key = "item: ".$count;
setcookie($key, $pid, $expiry);
setcookie("count", $count+1, $expiry);
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
First of all, your html code isn't correct. You oppened body tag 2 times and your title tag is out of the head tag, it's not even in the body.
As Biffen said in the comment, you cannot run the php after the page has loaded. Instead, you can use ajax. Ajax Documentation
You have to create a file with your php code inside it, and then execute it with ajax without reloading the page. And as I see you have written in a comment: "Put the item into shopping cart". Do not store shopping cart items in, neither, browser cookies nor session. Use your database instead because data stored in either cookies or session will be vulnerable.

Popup inside the window

Right now I have a grid and each grid part/bit contains an image, the name of the item and different buttons that can delete the item from the mysql database and update the price. What I want to do know is that when a user say clicks on the image a window would pop up where extra information would be displayed. However it is not a pop up in a usual sense that it would create another window but rather a pop up within the current window/tab. E.g. When you press on a photo in Facebook it creates almost like a popup on which you can comment or change to the next photo. Does anyone have any idea on how to do this or at least what is the whole thing/process called?
Sorry if I can't give a proper name but I don't know it myself :/
Here is the code to what I have now. I would prefer an actual code solution but if you can lead me to where I should look for it I would also be happy. I tried looking online however everything I get is window pop ups.
<div class="boxes">
<?php
$ID = $_SESSION['SESS_MEMBER_ID'];
$con = mysql_connect("", "", "");
if (!$con){
die("Cannot connect: " . mysql_error());
}
mysql_select_db("test", $con);
$sql = "SELECT * FROM items WHERE member_id = $ID";
$myData = mysql_query($sql, $con);
$dir = 'Images';
$symbol = '\\';
$end = 'r.jpg';
$currency = '£';
while($record = mysql_fetch_array($myData)) {
$real_name = str_replace('_', ' ', $record['Name']);
$result = $dir . $symbol . $record['Name'] . $end;
$value = $currency . $record['price_now'];
$link = $record['url'];
echo "<div class = frame>";
echo "<div class = bit-3>";
echo "<div class = box>" . "<img src=" . $result . " alt=some_text>";
echo "<br />";
echo "<br />";
echo $real_name;
echo "<br />";
echo "<br />";
echo "Price now: " . $value;
echo "<form action = member-profile-page.php method = post>";
echo "Desired price: ";
echo "<td>" . "<input type = text name = desired_price value = " . $record['desired_price'] . " </td>";
echo "<td>" . "<input type = hidden name = hidden value = " . $record['Id'] . " </td>";
echo " ";
echo "<td>" . "<input type = submit name = update value = Update" . " </td>";
echo "<br />";
echo "<br />";
echo "<td>" . "<input type = submit name = delete value = Delete" . " </td>";
echo "<br />";
echo "<br />";
echo "<td>" . "<input type = submit name = buy value = Buy" . " </td>";
echo "</form>";
echo "</div>";
echo "</div>";
echo "</div>";
}
if (isset($_POST['buy'])){
$query = "select url from items where Id = '$_POST[hidden]'";
if ($result = mysql_query($query)) {
$row = mysql_fetch_assoc($result);
$code = $row['url'];
echo "$code";
header("Location: $code");
}
};
if (isset($_POST['update'])){
$UpdateQuery = "UPDATE items SET desired_price = '$_POST[desired_price]' WHERE Id = '$_POST[hidden]'";
mysql_query($UpdateQuery, $con);
};
if (isset($_POST['delete'])){
$DeleteQuery = "DELETE FROM items WHERE Id = '$_POST[hidden]'";
mysql_query($DeleteQuery, $con);
};
mysql_close($con);
?>
</div>
Sounds like you're looking for an overlay:
http://jquerytools.org/demos/overlay/index.html
or a modal:
https://jqueryui.com/dialog/
These are by no means the only examples; there are hundreds of such solutions. These will get you started, though. Good luck!
What you think about is just a layer in the current browser viewport, having some controls to let the user handle it like a "desktop window".
There are quite a lot of JS frameworks offering handy solutions for this, i.e. jQuery UI. Within there, look for "dialog"

Categories

Resources