Add items to shopping cart - javascript

I am new to php so please bear my lack of knowledge.
I am developing a simple shopping cart. I have the screen divided in three framset. The left one is a imagemap where the user can click the desired item. The topRight is a php page that retrieve and displays in a table the details of the item clicked in theleftFrame. The last cell of this table has a textfield and a button to submit the order.
The goal of bottomRight frame is to display the shopping cart, showing the user how many products are already chosen.
My problem is that so far I can display only the current order submitted. In other words I display only the details of the last item "ordered" from the topRigt frame.
How can I keep on adding a second item, instead of replacing it?
Here is the code for topLeft
<html>
<head>
<title>Top Right</title>
<style type="text/css">
<!--
#import url("style.css");
-->
</style>
</head>
<body bgcolor = "#E0E6F8">
<h2>ITEMS</h2>
<?php
session_start();
// get the id from the left frame
$id = $_GET['var'];
// variable to connect to db
$user_name = "name";
$password = "password";
$server = "server";
$link = new mysqli($server,$user_name,$password,'poti');
if(!$link)
die("Could not connect to databse");
$result = $link->query("SELECT * FROM products WHERE product_id = '$id';");
while($row = $result->fetch_array())
{
$id = $row['product_id'];
$name = $row['product_name'];
$unit_price = $row['unit_price'];
$unit_quantity = $row['unit_quantity'];
$in_stock = $row['in_stock'];
$arrayName = array('id' => $id, 'name' => $name);
// store values in session
$_SESSION['cart'] = $arrayName;
// display details in a table (code needs to be refactored)
if(!empty($row)){
print "";
print "<form method='post' name='add' id='add' action='' target=''>";
print "<table id='hor-minimalist-a' border = '0' width = '100%'>";
print "<thead>
<tr>
<th scope='col'>ID</th>
<th scope='col'>Name</th>
<th scope='col'>Price</th>
<th scope='col'>QTY</th>
<th scope='col'>In Stock</th>
<th scope='col'>Order</th>
</tr>
</thead>";
print "<tr>\n";
print "<td>";
print($id);
print "</td>";
print "<td>";
print($name);
print "</td>";
print "<td>";
print($unit_price);
print "</td>";
print "<td>";
print($unit_quantity);
print "</td>";
print "<td>";
print($in_stock);
print "</td>";
print "<td>
<input type='text' name='qty_ordered' size='4'><input type='submit' name='submit' value='Submit' onclick='checkQty()'>
</td>";
print "</tr>";
}
print"</table>";
print "</form>";
}
?>
<script type="text/javascript">
function checkQty()
{
if(document.add.qty_ordered.value > 0 && document.add.qty_ordered.value <= 20)
{
document.add.action = "bottomRight.php";
document.add.target = "BottomRight";
document.add.submit();
}
else
{
//document.add.action = "topRight.php";
//document.add.target = "TopRight";
alert("Quantity must be between 1 and 20, please enter a value between 1 to 20");
//document.add.submit();
}
}
</script>
</body>
</html>
and for bottomRight:
<html>
<head>
<title>Bottom Right</title>
<style type="text/css">
<!--
#import url("style.css");
-->
</style>
</head>
<body>
<h2>Shopping Cart</h2>
<?php
session_start();
// doing this I keep on displaying only the last item "ordered"
if (isset($_POST['submit'])===true) {
if(isset($_SESSION['cart'])===true) {
$array = array($_SESSION['cart']);
print_r($array);
// not working
/*foreach($array as $a)
{
echo "<table><tr>";
echo "<td width='150px'><span style='color:white'>" . $a['id'] ."</span></td>";
echo "</tr></table>";}*/
}
}
?>
</body>
</html>

Check out the video tutorial given by Adam Khoury on youtube. He has used mysql_* (I know its deprecated) functions but you can use your own code and get your problem solved out. The video is just for your reference.
Here's the youtube playlist link: https://www.youtube.com/playlist?list=PL442E340A42191003
Here's the specific video link to solve your query: https://www.youtube.com/watch?v=WXqbQy9fOp8
Hope this helps you.

Related

How can i display data from selected row in textarea

I'm trying to learn php with html and I decided to create a project.
Right now, I'm stuck at this point where I want to display data on a textarea.
I created a database named 'company' with the table 'login' and the columns 'id','password' and 'username'.
When I select an option in the select option menu, the data from the column 'id','password' and 'username' is displayed in a table. What I want to achieve is when I click on a row, that the data from the column "problem" is displayed on the textarea which describes the situation with explanation.
I don't know how to write this but the syntax should be something like: Select 'problem' from login WHERE id='selected row id' I created on my php a select case witch works fine. The only problem that I have is I don't know how to select the id when I click on a specific row to display the data on the textarea.
Here's my code so far:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Formulaire</title>
<link rel="stylesheet" type="text/css" href="formulaire.css"/>
<!--<script type="text/javascript" src="select1.js"></script>-->
<!--<script src="http://code.jquery.com/jquery-latest.js"></script>-->
<style>
table tr:not(:first-child){
cursor: pointer;transition: all .25s ease-in-out;
}
table tr:not(:first-child):hover{background-color: #ddd;}
</style>
</head>
<body>
<div id="form">
<form action="#" method="post">
<label>Veuillez choisir une option :</label>
<select id="choix" name="choixtest">
<option value="tous">tous</option>
<option value="id">id</option>
<option value="username">username</option>
<option value="password">password</option>
</select>
<input type="submit" name="submit" value="Get Selected Values" />
<table id="table">
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "company");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt select query execution
$sql = "SELECT * FROM login";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo "<table>";
echo "<tr>";
echo "<th>id</th>";
echo "<th>username</th>";
echo "<th>password</th>";
echo "</tr>";
if(isset($_POST['submit'])){
$selected_val = $_POST['choixtest']; // Storing Selected Value In Variable
while($row = mysqli_fetch_array($result)){
switch($_POST['choixtest']){
case 'tous':
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['username'] . "</td>";
echo "<td>" . $row['password'] . "</td>";
echo "</tr>";
break;
case 'id':
echo "<tr>";
echo "<td>" . $row[$selected_val] . "</td>";
echo "<td>" . "</td>";
echo "<td>" . "</td>";
echo "</tr>";
break;
case 'username':
echo "<tr>";
echo "<td>" . "</td>";
echo "<td>" . $row[$selected_val] . "</td>";
echo "<td>" . "</td>";
echo "</tr>";
break;
case 'password':
echo "<tr>";
echo "<td>" . "</td>";
echo "<td>" . "</td>";
echo "<td>" . $row[$selected_val] . "</td>";
echo "</tr>";
break;
default:
// Something went wrong or form has been tampered.
}
}
}
echo "</table>";
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
</table>
<textarea id="erreur" rows="20" cols="100"></textarea>
</form>
</div>
</body>
</html>
For a table with <table id="myTable">to get the first column value into a textbox which is defined as
<input type="text" placeholder="Customer Name" id="cus_name">
You can add the following js code.
<script>
var table = document.getElementById('myTable');
for(var i = 1; i < table.rows.length; i++)
{
table.rows[i].onclick = function()
{
document.getElementById("cus_name").value = this.cells[0].innerHTML;
};
}
</script>
Here the cus_name is the id of the text field while in the this.cells[0], the value 0 represents the first column. You can change it accordingly and also can add more columns with the code document.getElementById("cus_name").value = this.cells[0].innerHTML; by only changing the cell value and the textbox id.
Every row in your html table must correspond to an id in the login table.
you have to place somewhere in the row the id corresponding to that row. You can achieve this in many ways.
one way to do it is using a data-something attribute to put the id, for instance
<tr data-id="<?php echo $current_row['id']; ?>">
<td>column1</td>
<td>column2</td>
<td>etcetera</td>
</tr>
Once you have the data-id atttribute set you can access it via Javascript everytime a user clicks on the row. For this you need to capture the click event on the row. I'll show you an example using jQuery:
$('.myTable tr').click(function(){
let id = $('this').data('id');
console.log('id of selected row: ' + id);
});
Now the 'id' variable contains the id of the row the user selected (check console output to make sure the id is the one you expect). The next step would be to use that id to make a request to the server, via Ajax or via regular http request. If this works successfully i suggest you to research, or make another post to find out how to reload the page with the content with the data you want. Since the more specific a question is the higher is the chance that it will be answered

How can a new value be entered into an input field after the initial value has been cleared?

The goal is to clear a field using a ON CLICK event which calls the java script function clear field(this.id)The clear field can then receive a new value. When the UPDATE button is pressed the database is updated with the new value. The clear field function succeeds in clearing the field, how can a new value be entered ?
<html>
<head>
<script src="JavaScript/getVal.js" type="text/javascript"></script>
</head>
<body>
Poll
<?php
$connection = mysqli_connect("localhost", "root", "");
mysqli_select_db($connection, "ukelection2015");
$rs = mysqli_query($connection, "select * from poll");
?>
<hr>
<table border=1 id="myTable">
<tr>
<th>Name</th>
<th>Value</th>
<th>Color</th>
<th></th>
<th> </th>
</tr>
<?php
$id = 0;
while ($row = mysqli_fetch_array($rs)) {
print("<form method= 'post' action= 'updatePoll.php'>");
for ($x = 0; $x <= 2; $x++) {
if ($x == 0) {
print("<tr>");
} else {
print("<td>" . $row['name'] . "</td>" . "<td id= '".$id."' value = '" . $row['value'] . "' onclick = 'clearField(this.id)'>" . $row['value'] . "</td>" . "<td>" . $row['color'] . "</td>" . "<td><a href = ''>Update</a></td>");
$x++;
if ($x == 1) {
print "</tr>";
}
$id++;
}
}
// this hidden field is used in updatePoll.php to get the party name to update (i.e. $name=$_POST['name'];)
/* print("<input type='hidden' name ='name' value={$row['name']}>"); */
print("<tr>");
// name
// value
// color
/* print("<td><input type='submit' value='Update' onclick='alertMsg()'/></td>"); */
print("</tr>");
print("</form>");
}
mysqli_close($connection);
?>
</table>
</body>
</html>
This is the javascript function
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
function clearField(anId) {
document.getElementById(anId).innerHTML = 0;
}
You can pass the new value as a parameter while calling the clearField function. Then rather than setting the innerHTML to 0 in the function definition, you can set the innerHTML to the new value as document.getElementById(anId).innerHTML = newValue
This may be helpful
<script type="text/javascript>
function clearField(anId) {
document.getElementById(anId).innerHTML = 0;
}
</script>
Given that you create a for four each row, you can add the ID of the element that you want to modify as an hidden input and make the field that you want to change an textbox number. When you click update, just submit the form and update In the database.

How to Pass every Php value to javascript URL (only showing 1 same row record)

Need help on below coding.
However I got few running no, when I press edit button it only show running no '1', other running no like 2 or 3 also showing running no 1 when i press edit on the row 2 and row 3.
I got a problem in index.php file:
<html>
<?php
$rb = $connect->Execute("SELECT * FROM IT_Dept.dbo.testingHeader A LEFT JOIN IT_Dept.dbo.testingDetail B
ON A.invoiceno=B.invoiceno_dt
WHERE A.invoiceno = '".$search."'");
}
$invoiceno = $rb->Fields("invoiceno");
$company = $rb->Fields("company");
$custname = $rb->Fields("custname");
$newadd=str_replace("<br />","\n",$custadd);
//table details
?>
<body>
<?php
echo "<form id= 'form2' method='post'><table id='tabledesc' border=1>
<tr>
<th>Description </th>
<th>Qty</th>
<th >Unit Price(Before GST)</th>
<th>Total(Before GST)</th>
<th >*Total GST</th>
<th >Amount(RM)</th>
<th >Tax input/output</th>
<th >Debit Acc</th>
</tr>";
while(!$rb->EOF) {
$description = $rb->Fields("description");
$invoiceno_dt = $rb->Fields("invoiceno_dt");
$runningno = $rb->Fields("runningno");
$qty = $rb->Fields("qty");
$unitprice = $rb->Fields("unitprice");
$totalb4gst = $rb->Fields("totalb4gst");
$gst = $rb->Fields("gst");
$amount = $rb->Fields("amount");
>Fields("creditacc");
$description = $description->value;
$invoiceno_dt = $invoiceno_dt->value;
$runningno = $runningno->value;
$qty = $qty->value;
$unitprice = $unitprice->value;
$totalb4gst = $totalb4gst->value;
$gst = $gst->value;
$amount = $amount->value;
echo "<tr><td>".$description."</td>";
echo "<td>".$qty."</td>";
echo "<td>".$unitprice."</td>";
echo "<td>".$totalb4gst."</td>";
echo "<td>".$gst."</td>";
echo "<td>".$amount."</td>";
echo "<input type='hidden' name = 'runningno' id='runningno' value = ' $runningno ' >";
echo "<td><button onclick='openedit()'>Edit</button></td>";
invoiceno_dt=".$invoiceno_dt."&runningno=".$runningno."'>Edit</a></td>";
invoiceno_dt=".$invoiceno_dt."&runningno=".$runningno."'>x</a></td><tr>";
echo "<td><button onclick='opendelete()'>Delete</button></td>";
$rb->MoveNext();
}
?>
</table></form></body>
<script type="text/javascript">
var popup;
function openedit() {
var myinvoice = document.getElementById("invoiceno").value;
var no = <?php echo $runningno; ?>;
alert(no);
popup = window.open("edit.php?invoiceno="+myinvoice+'&runningno='+no, "Popup", "width=500,height=600");
popup.focus();
}
popup.focus();
}
</script>
<?php
$rb->close;
$connect->close;
?>
You could add the running number to the page for example by doing this:
<script type="text/javascript">
var no = <?php echo $runningNo; ?>;
</script>
Try this.
echo "<td><button onclick=\"openedit('{$runningno}')\">Edit</button></td>";
Apart from that, you better to remove the spaces in value attribute in input field.
echo "<input type='hidden' name='runningno' id='runningno' value ='$runningno' />";
Use as suggested for template files
<html>
<!-- HTML code is here -->
<input type='hidden' name = 'runningno' id='runningno' value = '<?php print $runningno; ?>'></input>
<!-- Some other html -->
<?php
//your php code here
?>
<!-- HTML again -->
</html>
Same for js inside html
<script type="text/javascript">
var testJsValue = "<?php print $ValueFromPHP; ?>";
</script>
Try this
echo '<td><button onclick="openedit(\''.$runningno.'\')">Edit</button></td>';
I think this code will be work properly.

PHP and HTML table search using javascript

I want to create a search box, that only displays matched entries as search phrases are typed; the same in function as described here:
How to perform a real time search and filter on a HTML table
The difference is, the table I have is created from a PHP loop - and SQL data. But, I am unsure how to adopt the code to work for me.
Personally, I think it could be related to the "// printing table rows" section.
Here is the code:
var $search_rows = $('#table tr');
$('#search').keyup(function() {
var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();
$search_rows.show().filter(function() {
var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
return !~text.indexOf(val);
}).hide();
});
<html>
<script src="./jquery-1.6.4.js"></script>
<script src="./sorttable.js"></script>
<script src="./searchbox.js"></script>
<link rel="stylesheet" href="styles.css">
<head>
<title>Tau Empire Cadre Census</title>
</head>
<body>
<?php
//// //// //// ////
// DATABASE
//// //// //// ////
//database credentials
$db_host="localhost";
$db_user="tau";
$db_pwd="kuhohNg3";
$db="tau_census";
$db_table="cadres";
//make the connection
if (!mysql_connect($db_host, $db_user, $db_pwd))
die("Can't connect to database");
if (!mysql_select_db($db))
die("Can't select database");
// sending query
$result = mysql_query("SELECT * FROM {$db_table}");
if (!$result) {
die("Query to show fields from table failed");
}
//assign a variable the number of returned table fields
$fields_num = mysql_num_fields($result);
//// //// //// ////
// HEADING
//// //// //// ////
echo "<h1>Tau Empire Cadre Census</h1>";
// Search box
echo '<input type="text" id="search" placeholder="Type to search">';
//// //// //// ////
// TABLE
//// //// //// ////
//create the table, and use the JS sortable script
echo '<table id="table" class="sortable"><tr>';
// printing table headers
echo "<td class=headings>Designation</td>";
echo "<td class=headings>Location</td>";
echo "<td class=headings>Founding</td>";
echo "<td class=headings>Commanding Officer</td>";
echo "<td class=headings>Current Status</td>";
echo "<td class=headings>Current Location</td>";
echo "<td class=headings>Mission</td>";
echo "</tr>\n";
// printing table rows
while($row = mysql_fetch_row($result))
{
echo "<tr>";
// For each field print the content
for($i=1; $i<$fields_num; $i++) {
echo "<td>" . $row[$i] . "</td>";
}
echo "</tr>";
}
echo "</table>";
mysql_free_result($result);
?>
</body>
</html>
Running this does not throw up any errors, but nor does it work either. This requires brains greater than mine to work out, please.
I have this working now, thanks for all the assistance. It was a possible combination of the following:
i) Having the following script lines inserted correctly:
<script src="./jquery.min.js"></script>
<script src="./jquery-1.6.4.js"></script>
ii) Wrapping the external JS in $(function(){...});
iii) Incorrectly constructing my table rows and data fields.
Since you think the problem lies in the "printing table rows" section, I will point out that indeed you have formatting issues in that section, fix them like this and it might solve some of the problems:
// printing table rows
while($row = mysql_fetch_row($result))
{
echo "<tr>";
// For each field print the content
for($i=1; $i<$fields_num; $i++) {
echo "<td>" . $row[$i] . "</td>";
}
echo "</tr>";
}

checking dynamically created textboxes for values

I am creating a form for inserting data which technologies are being used by which customers.
I get data of customer's ID and name and select a customer in an drop-down list, and i get data from technologies id and description and display description in a table + it creates a textbox (ID='box-". $row1['ID_T']."') for every technology entry in a DB.
So now i would like to check this dynamically created textboxes with jquery for value (if empty or filled with data) (getelementbyid) but i can not find a way to check theese DYN textboxes.
The ID_T and ID_C will be loaded into another table containing these two PK's and add string from textbox to value.
i would appreciate your help so much!
<HTML>
<HEAD>
<SCRIPT>
function update_tech(id,description)
{
var x = confirm('Do you want to edit technology '+description);
if (x == true)
{
document.getElementById('update_id').value = id;
//document.getElementById('description').value = description;
//document.form_update.submit();
}
}
</SCRIPT>
</HEAD>
<?php
include "connection.php";
$sql = "SELECT ID_C, Name FROM empresa";
$rs = mysql_query($sql, $conn);
$sql2 = "SELECT ID_T, description FROM technologies";
$rs2 = mysql_query($sql2, $conn);
while($row = mysql_fetch_array($rs2))
{
if (isset($_POST["box-".$row["ID_T"]]))
if ($_POST["box-".$row["ID_T"]] != "")
echo "INSERT ....".$_POST["box-".$row["ID_T"]]."<br>";
}
$rs2 = mysql_query($sql2, $conn);
mysql_close($conn);
?>
<BODY>
<SELECT NAME="customers" ONCHANGE="showCustomer(this.value)">
<?php
if (mysql_num_rows($rs))
{
while($row = mysql_fetch_array($rs))
{
?>
<option value='<?php echo $row['ID_C'] ?>'><?php echo $row['Name']?></option>
<?php
}
}
else {
echo "<option value=\"0\">No customers</option>";
}
?>
</SELECT>
<FORM METHOD="POST">
<?php
echo "<table border='0'>";
while($row1 = mysql_fetch_array($rs2))
{
echo "<tr>";
echo "<td><INPUT TYPE='text' name='box-". $row1['ID_T']."' ID='box-". $row1['ID_T']."'></td>";
echo "<td>" . $row1['description'] . "</td>";
echo "</tr>";
}
echo "</TABLE>";
?>
<INPUT TYPE="SUBMIT">
</FORM>
</BODY>
</HTML>
You can either maintain an array of input box ids or use the jquery partial selector to identify all the input boxes.
jQuery approach is something like:
$('input[id^="box-"]').each(function(e, i) { console.log(e); };

Categories

Resources