Dynamic Invoice Forms fields and posting to a database - javascript

I am building a form to create invoices. At the moment it has the form fields of:
Product Name, QTY.
I have a "add more" button which adds another row of the above form fields.
It then submits as an array to another php page. What i am having problems with is matching each associated form field with each other because when i save it in the database i need the correct Product Name, QTY to be on the same row in the table obviously. Just not sure how to match them.
Currently my code on the form field page is:
<html>
<head>
<title>Invoice Test</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<br />
<br />
<h2 align="center">Invoice Test</h2>
<div class="form-group">
<form name="submit" id="submit" action="name.php" method="POST">
<div class="table-responsive">
<table class="table table-bordered" id="dynamic_field">
<tr>
<td><input type="text" name="product_name[]" placeholder="Product Name" class="form-control name_list" /></td>
<td><input type="text" name="qty[]" placeholder="QTY" class="form-control name_list" /></td>
<td><button type="button" name="add" id="add" class="btn btn-success">Add More</button></td>
</tr>
</table>
<input type="submit" name="submit" id="submit" class="btn btn-info" value="Submit" />
</div>
</form>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
var i=1;
$('#add').click(function(){
i++;
$('#dynamic_field').append('<tr id="row'+i+'"><td><input type="text" name="product_name[]" placeholder="Product Name" class="form-control name_list" /></td><td><input type="text" name="qty[]" placeholder="QTY" class="form-control name_list" /></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');
});
$(document).on('click', '.btn_remove', function(){
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});
});
</script>
On the name.php page where the form submits to. What is the best way to get each product and associated qty from the array and put them into the database row. Keeping in mind this is dynamic.
On name.php when i print out $_POST i currently have this array structure:
Array
(
[product_name] => Array
(
[0] => test1
[1] => test2
[2] => test3
[3] => test4
)
[qty] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
[submit] => Submit
)
Im guessing I need to count the keys and then match them in the other dimension of the array. Just not sure if that is the best way or even how to do that.

You could use this
$productName = $_POST['productName'];
$qty = $_POST['qty']
foreach($productName as $key => $productName) {
$productQty = $qty[$key];
//Use your ORM (or whatever) to inster into DB
//$productName and $productQty
}
EDIT
Or, even better, you could user PHP's array_combine:
$productName = $_POST['productName'];
$qty = $_POST['qty']
$arryWithTotals = array_combine($productName, $qty);
foreach($arrayWithTotals as $productName => $productQty) {
//insert into DB
}

If you wish you can use like these way.
<html>
<head>
<title>Invoice Test</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<br />
<br />
<h2 align="center">Invoice Test</h2>
<div class="form-group">
<form name="submit" id="submit" action="name.php" method="POST">
<div class="table-responsive">
<table class="table table-bordered" id="dynamic_field">
<tr>
<td><?php
session_start();
if (isset($_SESSION["message"]) && !empty($_SESSION["message"])) {
echo $_SESSION["message"];
unset($_SESSION["message"]);
}
?></td>
<td><input type="text" name="product_name[]" placeholder="Product Name" class="form-control name_list" /></td>
<td><input type="text" name="qty[]" placeholder="QTY" class="form-control name_list" /></td>
<td><button type="button" name="add" id="add" class="btn btn-success">Add More</button></td>
</tr>
</table>
<input type="submit" name="submit" id="submit" class="btn btn-info" value="Submit" />
</div>
</form>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
var i=1;
$('#add').click(function(){
i++;
$('#dynamic_field').append('<tr id="row'+i+'"><td><input type="text" name="product_name[]" placeholder="Product Name" class="form-control name_list" /></td><td><input type="text" name="qty[]" placeholder="QTY" class="form-control name_list" /></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');
});
$(document).on('click', '.btn_remove', function(){
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});
});
</script>
PHP
====
$data = $_POST['product_name'];
$data2 = $_POST['qty'];
$product_name = "'" . implode("','", array_values($data)) . "'";
$qty = "'" . implode("','", array_values($data2)) . "'";
$conn = mysql_connect("localhost", "root", "") or die("unable to connect Mysql");
mysql_select_db("Your DB Name called here") or die("unable to connect DB");
$query = "INSERT INTO `Your DB Name called here`.`Your Table Name called here` (`id`, `product_name`,`qty` ) VALUES (NULL, '$product_name', '$qty')";
if (mysql_query($query)) {
$_SESSION["message"] = "Successfully submitted";
}
header("location:your page name.php");

Related

Jquery autocomplete with dynamic input fields not working

I have created multiple dynamic input fields but I want to add jquery autocomplete with all the input fields but problem is this is only working with only first input field not with every dynamically added input fields. I have tried many SO answers but none of them are working for me or May be I could not understand.
Someone will help me with this problem.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Dynamic add/remove input fields in PHP Jquery AJAX</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link href="https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
</head>
<body>
<div class="card text-center" style="margin-bottom:50px;">
<h1>Dynamic Add/Remove input fields in PHP Jquery AJAX</h1>
</div>
<div class="container">
<div class="row">
<div class="col-md-1"></div>
<div class="col-md-10">
<div class="form-group">
<form name="add_name" id="add_name">
<table class="table table-bordered table-hover" id="dynamic_field">
<tr>
<td>
<div class="ui-widget">
<td><input type="text" name="uname" placeholder="Enter your Name" class="form-control name_list" /></td>
</div>
<td><input type="text" name="name[]" id="automplete-2" placeholder="Enter your Name" class="form-control name_list" /></td>
<td><input type="text" name="email[]" placeholder="Enter your Email" class="form-control name_email"/></td>
<td><button type="button" name="add" id="add" class="btn btn-primary">Add More</button></td>
</tr>
</table>
<input type="submit" class="btn btn-success" name="submit" id="submit" value="Submit">
</form>
</div>
</div>
<div class="col-md-1"></div>
</div>
</div>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</body>
</html>
<script type="text/javascript">
$(document).ready(function(){
<?php
$js_array = json_encode($name);
echo "var availableTutorials = ". $js_array . ";\n";
?>
$("#automplete-2").autocomplete({
source: availableTutorials,
autoFocus: true
});
var i = 1;
$("#add").click(function(){
i++;
$('#dynamic_field').append('<tr id="row'+i+'"><td><input type="text" id="automplete-2" name="name[]" placeholder="Enter your Name" class="form-control name_list"/></td><td><input type="text" name="email[]" placeholder="Enter your Email" class="form-control name_email"/></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');
});
$(document).on('click', '.btn_remove', function(){
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});
$("#submit").on('click',function(){
var formdata = $("#add_name").serialize();
$.ajax({
url :"action.php",
type :"POST",
data :formdata,
cache :false,
success:function(result){
alert(result);
$("#add_name")[0].reset();
}
});
});
});
</script>
So finally I read the code again and i find this solution and it's working now.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Dynamic add/remove input fields in PHP Jquery AJAX</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link href="https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
</head>
<body>
<div class="card text-center" style="margin-bottom:50px;">
<h1>Dynamic Add/Remove input fields in PHP Jquery AJAX</h1>
</div>
<div class="container">
<div class="row">
<div class="col-md-1"></div>
<div class="col-md-10">
<div class="form-group">
<form name="add_name" id="add_name">
<table class="table table-bordered table-hover" id="dynamic_field">
<tr>
<td>
<div class="ui-widget">
<td><input type="text" name="uname" placeholder="Enter your Name" class="form-control name_list" /></td>
</div>
<td><input type="text" name="name[]" id="automplete-2" placeholder="Enter your Name" class="form-control name_list" /></td>
<td><input type="text" name="email[]" placeholder="Enter your Email" class="form-control name_email"/></td>
<td><button type="button" name="add" id="add" class="btn btn-primary">Add More</button></td>
</tr>
</table>
<input type="submit" class="btn btn-success" name="submit" id="submit" value="Submit">
</form>
</div>
</div>
<div class="col-md-1"></div>
</div>
</div>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</body>
</html>
<script type="text/javascript">
$(document).ready(function(){
var i = 1;
$("#add").click(function(){
i++;
$('#dynamic_field').append('<tr id="row'+i+'"><td><input type="text" id="automplete-2" name="name[]" placeholder="Enter your Name" class="form-control name_list"/></td><td><input type="text" name="email[]" placeholder="Enter your Email" class="form-control name_email"/></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');
$('#dynamic_field').find('input[name^="name"]').autocomplete({
source: availableTutorials
});
});
$(document).on('click', '.btn_remove', function(){
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});
$("#submit").on('click',function(){
var formdata = $("#add_name").serialize();
$.ajax({
url :"action.php",
type :"POST",
data :formdata,
cache :false,
success:function(result){
alert(result);
$("#add_name")[0].reset();
}
});
});
<?php
$js_array = json_encode($name);
echo "var availableTutorials = ". $js_array . ";\n";
?>
// $("#dynamic_field").autocomplete({
// source: availableTutorials,
// autoFocus: true
// });
$("input[name^='name']").autocomplete({
source: availableTutorials
});
});
</script>

Column cannot be null by using Auth

I'm inserting multiple data into the database. There is an error for my column report_by which is SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'report_by' cannot be null (SQL: insert into 'complaints' ('defect_id', 'image', 'description', 'report_by') values (1, C:\wamp64\tmp\php8E2E.tmp, leak, ?)) Inside column report_by should be the id of the user by using Auth. It's to tell that the complaint made by which users.
users table
id
role
email
typable_id
typable_type
complaints table
id
defect_id
image
description
report_by
ComplaintController.php
<?php
namespace App\Http\Controllers;
use Auth;
use App\Complaint;
use Illuminate\Http\Request;
class ComplaintController extends Controller
{
public function index()
{
return view('buyers.complaint');
}
public function create(Request $request)
{
if (count($request->defect_id) > 0) {
foreach($request->defect_id as $item=>$v) {
$data = array(
'defect_id' => $request->defect_id[$item],
'image' => $request->image[$item],
'description' => $request->description[$item],
'report_by' => $request->user_id,
);
Complaint::insert($data);
}
}
return redirect('/report-form')->with('success','Your report is submitted!');
}
}
complaint.blade.php
<div class="panel-heading">
<h3 class="panel-title"><strong>Make New Report</strong></h3>
</div>
<div class="panel-body">
<div>
<div class="panel">
<table class="table table-bordered">
<thead>
<tr>
<th><center>Type of Defect</center></th>
<th><center>Image</center></th>
<th><center>Description</center></th>
<th><center>Action</center></th>
</tr>
</thead>
<tbody>
<tr>
<td width="20%">
<form action="/report-create" method="post" enctype="multipart/form-data">
{{ csrf_field() }}
<input type="text" class="hidden" id="user_id" value="{{Auth::user()->id}}">
<select class="form-control" name="defect_id[]">
<option value="" selected>Choose Defect</option>
#foreach(App\Defect::all() as $defect)
<option value="{{$defect->id}}">{{$defect->name}}</option>
#endforeach
</form>
</td>
<td width="15%">
<input type="file" class="form-control-file" name="image[]">
</td>
<td width="45%">
<input type="text" class="form-control" name="description[]">
</td>
<td width="10%">
<button type="button" class="btn btn-info btn-sm" id="add-btn"><i class="glyphicon glyphicon-plus"></i></button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<center><button type="submit" class="btn btn-primary">Submit</button></center>
</div>
Here my javascript inside the blade
#section('footer')
<script>
$(document).ready(function () {
$('#add-btn').on('click',function () {
var html = '';
html += '<tr>';
html += ' <td><input type="text" class="hidden" id="user_id" value="{{Auth::user()->id}}"><select class="form-control" name="defect_id[]"><option value="" selected>Choose Defect</option>#foreach(App\Defect::all() as $defect)<option value="{{$defect->id}}">{{$defect->name}}</option>#endforeach</td>';
html += ' <td><input type="file" class="form-control-file" name="image[]"></td>';
html += ' <td><input type="text" class="form-control" name="description[]"></td>';
html += ' <td><button type="button" class="btn btn-danger btn-sm" id="remove-btn"><i class="glyphicon glyphicon-minus"></i></button></td>';
html += '</tr>';
$('tbody').append(html);
})
});
$(document).on('click','#remove-btn',function () {
$(this).closest('tr').remove();
});
</script>
#stop

i want make no.of inputs equal in codeigniter

Here i repeated the table dynamically in this project.what i want to make is no.of passenger must be equal to no.of passenger details.Now even if i enter details of 5 passengers bt no.tickets can be any number.this should not happen.how can i solve it?
<script>
$(document).ready(function(){
var i=1;
$('#add').click(function(){
i++;
$('#a').append('<tr id="row'+i+'"><th><input type="text" name="pname[]" placeholder="Name" class="form-control name_list" /></th><th ><input type="number" name="age[]" placeholder="Age" class="form-control name_list" min="5" max="130" /></th><th scope=""><select class="form-control" id="gender[]" name="gender[]" placeholder="gender" width=""> <option>Male</option> <option>Female</option></select></th><th><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></th></tr>');
});
$(document).on('click', '.btn_remove', function(){
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});
});
</script>
<div class="form-group">
<label for="No.of adults">No.of Passengers</label>
<?php echo form_input(['type'=>'number','name'=>'pass_no','class'=>'form-control','id'=>'passenger','min'=>1,'max'=>9,'onkeyup'=>"sum();",'placeholder'=>'Enter No.of Adults','value'=>set_value('pass_no')]); ?>
<?php echo form_error('pass_no'); ?>
</div>
<label for="No.of Children">Passenger Details</label><button type="button" class="btn btn-primary btn-sm" id="add" style="margin-left:170px">Add Passenger</button>
<table class="table table-secondary" id="a" name="a">
<thead>
<tr class="table-default">
<th scope="col-lg-15">
<? if(isset($pname)): // Name set? ?>
<? foreach($pname as $item): // Loop through all previous posted items ?>
<?php echo form_input(['type'=>'text','name'=>'pname[]','value'=>'','class'=>'form-control','id'=>'pname','placeholder'=>'Name','value'=>set_value('pname[]')]); ?>
<?php echo form_error('pname[]'); ?>
<? endforeach; ?>
<? else: ?>
<? endif; ?>
</th>
<th scope="col-lg-15">
<? if(isset($age)): // Name set? ?>
<? foreach($age as $item): ?>
<?php echo form_input(['type'=>'number','name'=>'age[]','class'=>'form-control','id'=>'age','min'=>5,'max'=>130,'placeholder'=>'Age','value'=>set_value('age[]')]); ?>
<?php echo form_error('age[]'); ?>
<? endforeach; ?>
<? else: ?>
<? endif; ?>
</th>
<th scope="col-lg-15">
<? if(isset($gender)): // Name set? ?>
<? foreach($gender as $item): // Loop through all previous posted items ?>
<select class="form-control" id="gender[]" name="gender[]" placeholder="Gender" >
<option>Male</option>
<option>Female</option>
</select>
<? endforeach; ?>
<? else: ?>
<? endif; ?>
</th>
</tr>
</thead>
</table>
Ok #suraj shetty, I've created a demo from your code(removing the php code) which will not allow the passenger details to be greater than total passengers.
But keep in mind, this will not prevent the user from submitting the
form with fewer details, ie 2 passengers and only 1 detail(You can prevent
this but it's annoying and should be avoided). So, you should validate
this on form submit. Also, the user can first add details of 2 passengers and then change the total number to 1. This should also be checked on submit.
So, I added a class(passenger_detail) to the tr and every time, the user adds detail I match total passengers with total elements of the class, the same class is included when on new tr element when added.
I would advise you to use clone() instead of appending a whole(same) row. It's bad practice. You can add id after cloning(if that was the reason behind using append).
$(document).ready(function(){
var i=1;
$('#add').click(function(){
let total_passenger = $('#passenger').val(); // get total passengers
let total_details = $('.passenger_detail').length; // get total rows with class total_details
if(total_details < total_passenger){ // check the condition
i++;
$('#a').append('<tr class="passenger_detail" id="row'+i+'"><th><input type="text" name="pname[]" placeholder="Name" class="form-control name_list" /></th><th ><input type="number" name="age[]" placeholder="Age" class="form-control name_list" min="5" max="130" /></th><th scope=""><select class="form-control" id="gender[]" name="gender[]" placeholder="gender" width=""> <option>Male</option> <option>Female</option></select></th><th><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></th></tr>'); // use clone() here, then add id
}else{ // you can remove this if you don't want to show any message
alert('Passenger details cannot be greater than no. of passengers'); // your custom message
}
});
$(document).on('click', '.btn_remove', function(){ // you can also check the condition on remove but should avoid doing that. Check on submit instead.
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});
});
function sum(){} // just to avoid error, because you're calling sum() onkeyup. Your logic here.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
<label for="No.of adults">No.of Passengers</label>
<input type='number' name='pass_no' class='form-control' id='passenger' min='1' max='9' onkeyup="sum();" placeholder='Enter No.of Adults' value='1'>
</div>
<label for="Passenger Details">Passenger Details</label><button type="button" class="btn btn-primary btn-sm" id="add" style="margin-left:170px">Add Passenger</button>
<table class="table table-secondary" id="a" name="a">
<thead>
<tr class="table-default passenger_detail">
<th scope="col-lg-15">
<input type='text' name='pname[]' class='form-control' id='pname' placeholder='Name' value='Sauhard' />
</th>
<th scope="col-lg-15">
<input type='number ' name='age[] ' class='form-control' id='age' min='5 ' max='130' placeholder='Age ' value='23' />
</th>
<th scope="col-lg-15">
<select class="form-control" id="gender[]" name="gender[]" placeholder="Gender">
<option>Male</option>
<option>Female</option>
</select>
</th>
</tr>
</thead>
</table>
Hope it helps you. :)

Uncaught syntax error: invalid token while executing javascript snippet

i am trying to build dynamic input fields using javascript and codeigniter. while executing the snippet, there is an error of Uncaught SyntaxError: Invalid or unexpected token.
i have created table where i am fetching data from database. All of my tables data is is working fine with the javascript snipped except one where i have a drop down list.
This is my table where i am fetching data.
<td><input class="typeahead form-control" type="text" placeholder="Enter Parameter"></td>
<td> <?php echo form_dropdown('id',$unit_name, '', 'class="form-control"');?> </td>
<td> <input type="quantity" class="form-control" id="quantity" placeholder="Enter Quantity"></td>
<td><input type="price" class="form-control" id="price" placeholder="Enter Price"></td>
<td><button type="button" name="add" id="add" class="btn btn-success">Add More</button></td>
This is my javascript snippet where i am making the table dynamic to add more rows of the same input fields.
<script>
$(document).ready(function(){
var i=1;
$('#add').click(function(){
i++;
$('#dynamic_field').append('<tr id="row'+i+'"> <td><input class="typeahead form-control" type="text" placeholder="Enter Parameter"></td>\n\
<td> <input type="quantity" class="form-control" id="quantity" placeholder="Enter Quantity"></td>\n\
<td> <?php echo form_dropdown('id',$unit_name, '', 'class="form-control"');?> </td>\n\
<td><input type="price" class="form-control" id="price" placeholder="Enter Price"></td>\n\
<td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');
});
$(document).on('click', '.btn_remove', function(){
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});
$('#submit').click(function(){
$.ajax({
url:"name.php",
method:"POST",
data:$('#add_name').serialize(),
success:function(data)
{
alert(data);
$('#add_name')[0].reset();
}
});
});
});
</script>
My above javascript function works fine if i remove this line from the function
<td> <?php echo form_dropdown('id',$unit_name, '', 'class="form-control"');?> </td>\n\
But if i add this line i get that described error.
Try this,
<td> <?php echo form_dropdown("id",$unit_name, "", "class="form-control"");?> </td>

Warning: Cannot modify header information - headers already sent by (output started at /home/cabox/workspace/Project/ShoppingCart

Having difficulty identifying what is throwing the error. Have removed all white space. Using CodeAnywhere as my IDE as it is a requirement for me. Any help would be appreciated.
Full error:
Warning: Cannot modify header information - headers already sent by (output started at /home/cabox/workspace/Project/ShoppingCart.php:134) in /home/cabox/workspace/Project/ShoppingCart.php on line 169
Code:
<?php
session_start();
$connect = mysqli_connect("localhost", "root", "", "lab"); //connect to the db
if(isset($_POST["add_to_cart"])) //if the add to cart value is set
{
if(isset($_SESSION["shopping_cart"])) //if the shopping cart session is set
{
$item_array_id = array_column($_SESSION["shopping_cart"], "item_id");
//if there are values in your shopping cart loop through and display them
if(!in_array($_GET["id"], $item_array_id))
{
$count = count($_SESSION["shopping_cart"]);
$item_array = array(
'item_id' => $_GET["id"],
'item_name' => $_POST["hidden_name"],
'item_price' => $_POST["hidden_price"],
'item_quantity' => $_POST["quantity"]
);
$_SESSION["shopping_cart"][$count] = $item_array;
}
else
{
echo '<script>alert("Item Already Added")</script>';
//restriction on design - can only add one instance of each product, delete if you want to add more
}
}
else
{
$item_array = array(
'item_id' => $_GET["id"],
'item_name' => $_POST["hidden_name"],
'item_price' => $_POST["hidden_price"],
'item_quantity' => $_POST["quantity"]
);
$_SESSION["shopping_cart"][0] = $item_array;
}
}
if(isset($_GET["action"]))
{
if($_GET["action"] == "delete")
//when you select 'Remove', delete the values based on id. Alert box will show on completition
{
foreach($_SESSION["shopping_cart"] as $keys => $values)
{
if($values["item_id"] == $_GET["id"])
{
unset($_SESSION["shopping_cart"][$keys]);
echo '<script>alert("Item has been removed from Shopping Cart")</script>';
echo '<script>window.location="ShoppingCart.php"</script>';
}
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Shopping Cart</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<!-- AJAX is about loading data in the background and display it on the webpage, without reloading the whole page.-->
<link rel="stylesheet" type="text/css" href="thePerfectPair.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script>
// Get the modal
var modal = document.getElementById('id01');
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
</head>
<body>
<nav class="navigationBar">
<!--Establishing the top left hand side of the Navigation Bar-->
<div class="leftTopNavBar">
€ EUR |
<!--The following produces a pop up sign up form that is validated through javascript functions in the following code.
I implemented this pop up form to create a different design element as opposed to just referring users to another page.
All design element are assigned in the css file and it involved calling many different classes in order not to conflict
with other forms and input boxes contained in the website-->
<button onclick="document.getElementById('id01').style.display='block'" style="width:auto;" class="SignUpBtn0">SIGN UP |</button>
<div id="id01" class="modal">
<span onclick="document.getElementById('id01').style.display='none'" class="close" title="Close Modal">×</span>
<form class="modal-content" action="/action_page.php">
<div class="container1">
<h1>Sign Up</h1>
<p>Please fill in this form to create an account with Perfect Pair!</p>
<hr>
<b>Email</b>
<input type="text" placeholder="Enter Email" name="email" required>
<b>Password</b>
<input type="password" placeholder="Enter Password" name="psw" required>
<b>Repeat Password</b>
<input type="password" placeholder="Repeat Password" name="psw-repeat" required>
<label>
<input type="checkbox" checked="checked" name="remember" style="margin-bottom:15px"> Remember me</label>
<p>By creating an account you agree to our Terms & Privacy.</p>
<div class="clearfix">
<button type="button" onclick="document.getElementById('id01').style.display='none'" class="cancelbtn">Cancel</button>
<button type="submit" class="signupbtn">Sign Up</button>
</div>
</div>
</form>
</div>
SAVED ITEMS
</div>
<!--Establishing the right side of the navBar-->
<div class="rightTopNavBar">
<input type="search" placeholder="Search..." name="search">
<button type="submit"><i class="fa fa-search"></i></button>
LOGIN | CART
<i class="fa fa-shopping-cart" style="font-size:20px"></i>
</div>
<!--Establishing the middle of the navBar-->
<div class="middleTopNavBar">
<img src="Images/perfectPairLogo.png" class="logoHeader" alt="logo" width="100" height="100">
</div>
<!--Establishing bottom navBar-->
<div class="bottomNavBar">
<i class="fa fa-home" style="font-size:36px"> </i>
 HEELS 
 SANDALS 
 BOOTS 
 TRAINERS 
 FLATS 
 SHOPPING CART </div></nav>
<div class="container">
<br><?php $query="SELECT*FROM tbl_product1 ORDER BY id ASC"; $result=mysqli_query($connect, $query); if(mysqli_num_rows($result)>0){while($row=mysqli_fetch_array($result)){?><div class="col-md-4">
<form method="post" class="phpForm" action="ShoppingCart.php?action=add&id=<?php echo $row["id"];?>" >
<div class="formStyleDiv" style=" background-color:#f1f1f1; border-radius:1px; padding:16px; width:25%;" align="center">
<img src="Images/<?php echo $row["image"];?>" class="img-responsive" style="height: 200px;" />
<h4 class="text-info"><?php echo $row["name"];?></h4><br />
<h4 class="text-danger">€<?php echo $row["price"];?></h4>
<input type="text" name="quantity" value="1" class="form-control" />
<input type="hidden" name="hidden_name" value="<?php echo $row["name"];?>" />
<input type="hidden" name="hidden_price" value="<?php echo $row["price"];?>" />
<input type="submit" name="add_to_cart" style="margin-top:5px;" class="submitBtn" class="btn btn-success" value="Add to Cart" /></div>
</form>
</div><?php
}
}
?><div style="clear:both"></div>
<br />
<h3>Order Details</h3>
<div class="table-responsive" >
<table>
<tr>
<th width="40%" align="left">Item Name</th>
<th width="10%" align="left">Quantity</th>
<th width="20%" align="left">Price</th>
<th width="15%" align="left">Total</th>
<th width="5%" align="left">Action</th>
</tr><?php if(!empty($_SESSION["shopping_cart"])) { $total = 0; foreach($_SESSION["shopping_cart"] as $keys => $values){?><tr>
<td><?php echo $values["item_name"];?></td>
<td><?php echo $values["item_quantity"];?></td>
<td>€<?php echo $values["item_price"];?></td>
<td>€<?php echo number_format($values["item_quantity"] * $values["item_price"], 2);?></td>
<td><span class="text-danger">Remove</span></td>
</tr><?php $total = $total + ($values["item_quantity"] * $values["item_price"]);}?><tr>
<td colspan="3" align="right">Total</td>
<td align="right">€<?php echo number_format($total, 2); ?></td>
<td></td>
</tr><?php $cookie_name="Total"; setcookie($cookie_name, $total, time()+(86400*30),"/");}?></table></div>
<input type="button" class="submitFormBtn" name="submit" value= "Submit" onclick="window.open ('success.php','_self',false)" /><br />
</div>
</div>
<br />
</body>
</html>

Categories

Resources