Adding Multiple Items in Cart (add to cart) using multiple different buttons - javascript

I am a beginner. I am developing an e-commerce website. My problem is that I can't seem to add multiple items in my cart. If I clicked an item it will be added to the cart but when I clicked another item it will just replaced the first item that I picked. Any suggestions on how I can fixed that? Thank you
<!-- This is my index.html. You can browse my products here. This is just a sample of my code. It's too long. Sry. -->
<form method = "GET" action = "php/addtocartprocess.php">
<p>Price: 9,199 Php<br><input class = "btn btn-success"type = "submit" name = "add_to_cart1" value = "Add to Cart"><span class = "glyphicon glyphicon-shopping-cart"></span></p>
<p>Price: 28,890 Php<br><input class = "btn btn-success"type = "submit" name = "add_to_cart2" value = "Add to Cart"><span class = "glyphicon glyphicon-shopping-cart"></span></p>
<p>Price: 46,995 Php<br><input class = "btn btn-success"type = "submit" name = "add_to_cart3" value = "Add to Cart"><span class = "glyphicon glyphicon-shopping-cart"></span></p></form>
<?php
// this is my php code. I don't know if it right or not
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
$connection = mysql_connect("localhost", "root", "");
if(isset($_GET['add_to_cart1'])){
$_SESSION['prod_id'] = 1;
header("location: ../android.php");
}
if(isset($_GET['add_to_cart2'])){
$_SESSION['prod_id'] = 2;
header("location: ../android.php");
}
if(isset($_GET['add_to_cart3'])){
$_SESSION['prod_id'] = 3;
header("location: ../android.php");
}
if(isset($_GET['add_to_cart4'])){
$_SESSION['prod_id'] = 4;
header("location: ../android.php");
}
if(isset($_GET['add_to_cart5'])){
$_SESSION['prod_id'] = 5;
header("location: ../android.php");
}
if(isset($_GET['add_to_cart6'])){
$_SESSION['prod_id'] = 6;
header("location: ../android.php");
}
if(isset($_GET['add_to_cart7'])){
$_SESSION['prod_id'] = 7;
header("location: ../android.php");
}
if(isset($_GET['add_to_cart8'])){
$_SESSION['prod_id'] = 8;
header("location: ../android.php");
}
if(isset($_GET['add_to_cart9'])){
$_SESSION['prod_id'] = 9;
header("location: ../android.php");
}
if(isset($_GET['add_to_cart10'])){
$_SESSION['prod_id'] = 10;
header("location: ../iphone.php");
}
if(isset($_GET['add_to_cart11'])){
$_SESSION['prod_id'] = 53;
header("location: ../iphone.php");
}
if(isset($_GET['add_to_cart12'])){
$_SESSION['prod_id'] = 54;
header("location: ../iphone.php");
}
if(isset($_GET['add_to_cart13'])){
$_SESSION['prod_id'] = 55;
header("location: ../windows.php");
}
if(isset($_GET['add_to_cart14'])){
$_SESSION['prod_id'] = 56;
header("location: ../windows.php");
}
if(isset($_GET['add_to_cart15'])){
$_SESSION['prod_id'] = 57;
header("location: ../windows.php");
}
if(isset($_GET['add_to_cart16'])){
$_SESSION['prod_id'] = 58;
header("location: ../smartwatch.php");
}
if(isset($_GET['add_to_cart17'])){
$_SESSION['prod_id'] = 59;
header("location: ../smartwatch.php");
}
if(isset($_GET['add_to_cart18'])){
$_SESSION['prod_id'] = 60;
header("location: ../smartwatch.php");
}
if(isset($_GET['add_to_cart19'])){
$_SESSION['prod_id'] = 61;
header("location: ../computer.php");
}
if(isset($_GET['add_to_cart20'])){
$_SESSION['prod_id'] = 62;
header("location: ../computer.php");
}
if(isset($_GET['add_to_cart21'])){
$_SESSION['prod_id'] = 64;
header("location: ../computer.php");
}
$gadgets = $_SESSION['prod_id'];
mysql_close($connection);
?>
<!-- This is my cart.php code -->
<?php
include('php/userloginprocess.php'); // Includes Login Script
include('php/addtocartprocess.php');
/*$id = $_SESSION['prod_id'];*/
$gadgets = $_SESSION['prod_id'];
if($_SESSION['login'] == FALSE){
header("location: login.php");
}
if($_SESSION['login'] == TRUE)
?>
<?php
//connection
mysql_connect("localhost","root", "") or die(mysql_error());
//database connection
mysql_select_db("marketech_db") or die(mysql_error());
//sql query
$sql = "SELECT * FROM user_tbl";
$records=mysql_query($sql);
?>
<html>
<head>
<title> Marketech | Buy Genuine Gadgets Online </title>
<script src="js/jquery.js"></script>
<script src="js/bootstrap.js"></script>
<link rel="stylesheet" href="css/bootstrap.css">
<link rel="shortcut icon" href="images/marketechlogo.ico" />
</head>
<body>
<!-- First Navigation Bar -->
<nav class="navbar navbar-default navbar-fixed-top">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Marketech</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<form class="navbar-form navbar-left">
<div class="form-group">
<input type="text" class="form-control" placeholder="Search">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
<ul class="nav navbar-nav navbar-right">
<li><span class = "glyphicon glyphicon-shopping-cart"></span> Cart</li>
<li class="dropdown">
<?php echo $_SESSION ['fname']; ?><span class="caret"></span>
<ul class="dropdown-menu">
<li>Account Settings</li>
<li>Logout</li>
</ul>
</li>
</ul>
</div>
</div>
</nav>
<!-- Second Navigation Bar -->
<br><br><br>
<div class = "container-fluid">
<nav class="navbar navbar-inverse navbar-lower">
<div class="container-fluid">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-2" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-2">
<ul class="nav navbar-nav col-lg-12">
<li class="col-md-2">Android Phone</li>
<li class="col-md-2">iPhone</li>
<li class="col-md-2">Windows Phone</li>
<li class="col-md-2">Smart Watch</li>
<li class="col-md-2">Computers</li>
<li class="dropdown col-md-2">Popular Brands <span class="caret"></span>
<ul class="dropdown-menu col-xs-2">
<li>Samsung</li>
<li>Apple</li>
<li>Microsoft</li>
<li>Sony</li>
<li>Asus</li>
</ul>
</li>
</ul>
</div>
</div>
</div>
</nav>
<!-- Marketechs Third Navigation (with glyphicons) -->
<div class="container">
<ul class="list-unstyled">
<li class = "col-md-3"><span class="glyphicon glyphicon-transfer"></span> 30 days Free Returns</li>
<li class = "col-md-3"><span class="glyphicon glyphicon-plane"></span> Free Delivery Above 999 php</li>
<li class = "col-md-3"><span class="glyphicon glyphicon-usd"></span> Cash on Delivery</li>
<li class = "col-md-3"><span class="glyphicon glyphicon-earphone"></span> Call (049) 557 2681</li>
</ul>
</div>
</div>
<!-- Cart -->
<div class = "container-fluid">
<form method = "GET" action = "deletecartproduct.php">
<div class = "col-md-9">
<table class = "table table-responsive table-hover">
<tr>
<th>Delete</th>
<th>Item Name</th>
<th>Item Price</th>
<th>Image</th>
</tr>
<?php
//connection
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("marketech_db") or die (mysql_error());
$sql = "SELECT * FROM product_tbl WHERE prod_id='$gadgets'";
$prod_records = mysql_query($sql);
while($products=mysql_fetch_assoc($prod_records)){
echo "<tr>";
echo "<td>" .'<input type="checkbox" name="products[]" value='.$products['prod_id'].'>'."</td>";
echo "<td>".$products['item_name']."</td>";
echo "<td>".$products['item_price']."</td>";
echo "<td>".$products['item_image']."</td>";
echo "</tr>";
}
?>
</table>
<input type ="submit" class = "btn btn-danger" name = "delete_cart_item" value = "Delete"></form>
</div>
</div>
<br><br><br><br><br>
<!-- Footer Navigation -->
<nav class="navbar navbar-default">
<div class="container">
<ul class ="list-unstyled">
<li class = "col-md-2"><h5><b>Call Us: (049) 557 2681</b></h5></li>
<li class = "col-md-2"><h5><b><font color = "black">About Us </b></h5></font></li>
<li class = "col-md-2"><h5><b><font color = "black">Contact Us</b></h5></font></li>
<li class = "col-md-2"><h5><b><font color = "black">Privacy</b></h5></font></li>
<li class = "col-md-2"><h5><b><font color = "black">Terms of Service</b></h5></font></li>
<li class = "col-md-2"><h5><b>Copyright (c) 2016<h5></li>
</ul>
</div>
</nav>
<!--
Members:
Marlon Mendoza
-->
</body>
</html>

You are using primitive session variable: $_SESSION['prod_id'], instead it should be an array.
Initialise it like this:
$_SESSION['prod_ids'] = [];
Then when a product is added/removed to cart, update $_SESSION['prod_ids']
array_push($_SESSION['prod_ids'],/*product_id*/)

You should consider doing the following:
Add a hidden field to your HTML containing the product ID if the current product.
<p>Price: 9,199 Php<br>
<input class="btn btn-success" type="submit" name="action" value="add_to_cart">
<input type="hidden" name="product_id" value="1">
<span class="glyphicon glyphicon-shopping-cart"></span>
</p>
Then you can refactor your PHP to this
<?php
if (session_status() == PHP_SESSION_NONE) {
session_start();
$_SESSION['cart'] = array();
}
$connection = mysql_connect("localhost", "root", "");
if(isset($_GET['add_to_cart'])){
array_push($_SESSION['cart'], $_GET['product_id'];
header("location: ../" . $_GET['product_id'] . ".php");
}
mysql_close($connection);
Notice how you can initialize $_SESSION['cart'] as an array, when creating the session object. Instead of assigning the product ID to $_SESSION['cart'], you can push it into the array.
Refactor the name of the php file which you set in your header, or add an additional hidden field containing the name of the file.

If you have 1000 items to add to cart you can not write 1000 if else statement.Better use loops.I created a sample code for what you want take reference from that and use your own logic to create what you want.happy coding.
check https://jsfiddle.net/qun3ajL9/

Related

script button in while loop,all the script buttons are printed in the same card,need to be printed in each cards

I have a javascript button and i have passed that button to div tag id="buttons" that is also in the while loop,when i run that all the buttons(named 'like') is printed in the same card(div class=" card"refer the image to understand), i want each button named like in each card aside of the heart.im new to scripts and php.Need help..
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {?>
<script>
k=k+1;
cars[k]=<?php echo $row["id"];?>
</script>
<div class="container">
<div class="card">
<?php echo '<span class="phpcss">'.$row["student"].'</span>'."<br>".$row["date"]. "<br><br>" . $row["post"] . "<br>"?>
<button class="like" onclick=likess();>
<div id="buttonss"></div>
<script>
var buttonss = document.getElementById("buttonss");
var button = document.createElement("button");
button.innerText = "like";
(function(k){
button.addEventListener("click", function() {
likes(cars[k]);
})
})(k)
buttonss.appendChild(button);
</script>
<i class="fa fa-heart" style="font-size:15px;color:red"></i>
</button>
<a href="?page= reply "><p> reply</p>
</div>
</div>
<?php }} ?>

How to redirect in php with "headers already sent" common error (gCaptcha + redirection)

When running my script, I am getting errors like this when i call header().
I know that there are already answers(How to fix "Headers already sent" error in PHP) BUT i dont understand and after trying all solutions
only the java solution works and it's a very bad solution. Without the gCaptcha part (with only the form) my code is working and without the form (with only gCaptcha) my code is working too BUT if combined the code doesnt work...
My errors are like this for each header() call :
"Warning: Cannot modify header information - headers already sent by (output started at C:\wamp64\www\Travail\WebApp1\login.php:126) in C:\wamp64\www\Travail\WebApp1\login.php on line 251"
What do i need to change ?
Honestly i have read all questions about this issue and after 8 hours i am still unable to fix the problem with a real solution.
My whole code:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
session_start();
require_once "config.php";
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
<title>Login</title>
</head>
<body>
<nav class="navbar navbar-dark bg-primary">
<div class="container-fluid">
<a class="navbar-brand" href="index.php">My Web App</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="signup.php">Sign Up</a>
</li>
<li class="nav-item">
<a class="nav-link" href="login.php">Login</a>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Admin</a>
</li>
</ul>
</div>
</div>
</nav>
<div class="login-form">
<?php
if(isset($_GET['login_err']))
{
$err = htmlspecialchars($_GET['login_err']);
switch($err)
{
case 'password':
?>
<div class="alert alert-danger">
<strong>Error</strong> wrong password
</div>
<?php
break;
case 'email':
?>
<div class="alert alert-danger">
<strong>Error</strong> invalid email
</div>
<?php
break;
case 'already':
?>
<div class="alert alert-danger">
<strong>Error</strong>Please enter valide information
</div>
<?php
}
}
?>
<form method="post" id="demo-form">
<h2 class="text-center">Login</h2>
<input type="hidden" id="g-token" name="g-token" />
<div class="form-group">
<input type="email" name="email" class="form-control" placeholder="Email" required="required" autocomplete="on">
</div>
<div class="form-group">
<input type="password" name="password" class="form-control" placeholder="password" required="required" autocomplete="off">
</div>
<div class="form-group">
<button type="submit" name="btnSubmit" class=" btn btn-primary btn-block" style=" margin-left: 35% ;" >Login</button>
</div>
<div class="form-group">
Forgot password ?
</div>
</form>
</div>
<style>
.login-form {
width: 340px;
margin: 50px auto;
}
.login-form form {
margin-bottom: 15px;
background: #f7f7f7;
box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);
padding: 30px;
}
.form-group {
margin-top: 1em;;
}
.login-form h2 {
margin: 0 0 15px;
}
.form-control, .btn {
min-height: 38px;
border-radius: 2px;
}
.btn {
font-size: 15px;
font-weight: bold;
}
</style>
<!-- Google Captcha Scripts -->
<script src="https://www.google.com/recaptcha/api.js?render=6LcOd1cbAAAAAOiqthb4pwaH0vfrVDyB89D6q4V8"></script>
<script>
grecaptcha.ready(function() {
grecaptcha.execute('6LcOd1cbAAAAAOiqthb4pwaH0vfrVDyB89D6q4V8', {action: 'homepage'}).then(function(token) {
console.log(token);
document.getElementById("g-token").value = token;
});
});
</script>
<!-- Optional JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script>
</body>
</html>
<?php
if(!empty($_POST["g-token"]) && !empty($_POST['email']) && !empty($_POST['password']))
{
$secretKey = '6LcOd1cbAAAAALaDm52utDpT2bt6DNtMNNivW-9s';
$token = $_POST["g-token"];
$ip = $_SERVER['REMOTE_ADDR'];
/* ======================= POST METHOD =====================*/
$url = "https://www.google.com/recaptcha/api/siteverify?";
$data = array('secret' => $secretKey, 'response' => $token, 'remoteip'=> $ip);
// use key 'http' even if you send the request to https://...
$options = array('http' => array(
'method' => 'POST',
'content' => http_build_query($data),
'header' => 'Content-Type: application/x-www-form-urlencoded'
));
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
$response = json_decode($result);
if($response->success)
{
echo '<center><h1>Validation Success!</h1></center>';
}
else
{
echo '<center><h1>Captcha Validation Failed..!</h1></center>';
}
//Avoid XSS
$email = htmlspecialchars($_POST['email']);
$password = htmlspecialchars(($_POST['password']));
$email = strtolower($email);
echo $email;
echo $password;
$check = $bdd->prepare('SELECT * FROM users WHERE email = ?');
$check->execute(array($email));
$data = $check->fetch();
$row = $check->rowCount();
echo $row;
if($row > 0)
{
if(filter_var($email, FILTER_VALIDATE_EMAIL))
{
if(password_verify($password, $data['password']))
{
$_SESSION['user'] = $data['token'];
//echo "<script type='text/javascript'>window.top.location='app.php';</script>"; exit;
header('Location: index.php');
die();
}else{echo "<script type='text/javascript'>window.top.location='login.php?login_err=password';</script>"; exit;
//header('Location: login.php?login_err=password'); die();
}
}else{echo "<script type='text/javascript'>window.top.location='login.php?login_err=email';</script>"; exit; }
}else{ echo "<script type='text/javascript'>window.top.location='login.php?login_err=already';</script>"; exit; }
}
else{ die();}
?>
If I replace "header('Location: index.php');" BY "echo "window.top.location='app.php';"; exit;" it works BUT it's not a real solution.
And by the way are my first 3 lines of code correct in order to show errors ? (I am using localhost wamp to run the code)
The header() function must be called before any other output is sent to the page. So in your case you would want to move the form processing block of PHP code at the bottom of your page to the top before you output the HTML. Note that this means you will also want to assign those validation response strings to variables and echo them further down in your page where appropriate.

Javascript problem in catching data on looping

I try to loop multiple values from a database and every time I click a specific item on the menu, Javascript only catches the first value that comes up in the database even if the function is inside the loop, Even I click the last item, the first item still displays... How to fix? Here is my code. (The display of the result is on top, I didn't include it)
<?php
$res = mysqli_query($db,"select * from menu where Restaurant_id='$id' order by Food_name asc") or die("Error: " . mysqli_error($db));
while($rows = mysqli_fetch_array($res)){
$f_id = $rows['Menu_id'];
$fname = $rows['Food_name'];
$fprice = $rows['Price'];
?>
<div class="col-12 helv menu rounded">
<ul class="nav navbar-nav navbar-expand-md">
<li class="nav-item"><img class="rounded" src="data:image/gif;base64,R0lGODlhAQABAIAAAHd3dwAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==" alt="Generic placeholder image" width="180" height="180"></li>
<li class="nav-item marginleft">
<br>
<input id="foodname" value="<?php echo $fname;?>" style="display: none;"><h5><b><?php echo $fname;?></b></h1></input><br>
<input id="foodprice" value="<?php echo $fprice;?>" style="display: none;"><h5>Php <?php echo $fprice;?>.00</h1></input>
</li>
<li class="nav-item" style="position: absolute; margin-left: 90%">
<button class="fa fa-plus btn btn-danger" onclick="add()"> Add</button>
</li>
</ul>
<br>
</div>
<script>
function add() {
var fdname = document.getElementById("foodname").value;
var fdprice = document.getElementById("foodprice").value;
document.getElementById("display").innerHTML = fdname;
document.getElementById("display1").innerHTML = fdprice;
}
</script>
<?php } ?>
<?php
// As Jeto said, you should use prepared statement
$res = mysqli_query($db,"select * from menu where Restaurant_id='$id' order by Food_name asc") or die("Error: " . mysqli_error($db));
while($rows = mysqli_fetch_array($res)){
$f_id = $rows['Menu_id'];
$fname = $rows['Food_name'];
$fprice = $rows['Price'];
?>
<div class="col-12 helv menu rounded">
<ul class="nav navbar-nav navbar-expand-md">
<li class="nav-item"><img class="rounded" src="data:image/gif;base64,R0lGODlhAQABAIAAAHd3dwAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==" alt="Generic placeholder image" width="180" height="180"></li>
<li class="nav-item marginleft">
<br>
<input class="foodname" value="<?php echo $fname;?>" style="display: none;"><h5><b><?php echo $fname;?></b></h1></input><br>
<input class="foodprice" value="<?php echo $fprice;?>" style="display: none;"><h5>Php <?php echo $fprice;?>.00</h1></input>
</li>
<li class="nav-item" style="position: absolute; margin-left: 90%">
<button class="fa fa-plus btn btn-danger" onclick="add('<?php echo $fname;?>', <?php echo $fprice;?>)"> Add</button>
</li>
</ul>
<br>
</div>
<?php } ?>
<script>
function add(fdname, fdprice) {
document.getElementById("display").innerHTML = fdname;
document.getElementById("display1").innerHTML = fdprice;
}
</script>
First get count of how many items are in there before the while query
$res = mysqli_query($db,"select * from menu where Restaurant_id='$id' order by Food_name asc") or die("Error: " . mysqli_error($db));
$count_of_items = mysqli_num_rows($res);
Then run the while query, then Run a for loop inside the form as per the number of Items
for($x=0;$x<count($count_of_items); $x++){
<input id="foodname" value="<?php echo $fname[$x];?>" style="display: none;"><h5><b><?php echo $fname[$x];?></b></h1></input><br>
<input id="foodprice" value="<?php echo $fprice[$x];?>" style="display: none;"><h5>Php <?php echo $fprice[$x];?>.00</h1></input>
}
There are some more mistakes.
1) IDs are unique
Please check this https://stackoverflow.com/a/12889416/3742228
2) Duplicate JS function
Every loop you make, you create another JS function named "add". If you create 3 functions named "add", which function do you want to call when you code add()? :)
For your code there are more solutions, but it depends on what exactly you want to do. Take a look at this:
<?php
$res = mysqli_query($db,"select * from menu where Restaurant_id='$id' order by Food_name asc") or die("Error: " . mysqli_error($db));
while($rows = mysqli_fetch_array($res)){
$f_id = $rows['Menu_id'];
$fname = $rows['Food_name'];
$fprice = $rows['Price'];
?>
<div class="col-12 helv menu rounded">
<ul class="nav navbar-nav navbar-expand-md">
<li class="nav-item"><img class="rounded" src="data:image/gif;base64,R0lGODlhAQABAIAAAHd3dwAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==" alt="Generic placeholder image" width="180" height="180"></li>
<li class="nav-item marginleft">
something here
</li>
<li class="nav-item" style="position: absolute; margin-left: 90%">
<button class="fa fa-plus btn btn-danger" foodName="<?php echo $fname;?>" foodPrice="<?php echo $fprice;?>" onclick="add(this)"> Add</button>
</li>
</ul>
<br>
</div>
<?php } ?>
<script>
function add(e) {
var fdname = e.getAttribute("foodName");
var fdprice = e.getAttribute("foodPrice");
document.getElementById("display").innerHTML = fdname;
document.getElementById("display1").innerHTML = fdprice;
}
</script>

Jquery code for hierarchal element is not working for a particular value in a loop

I have a sidebar drop-down menu, which is being operated using jquery, but when user clicks on the item the page refreshes and the menu collapses. To solve this,that is to keep it expanded, I decided to compare the REQUEST_URI with menu item URL, if found I will trigger the click event. To accomplish this I used the snipped
$("a[href='<?php echo $citems->url;?>']").parents("li").parents("ul.dropdown-menu").prev(".dropdown-toggle").trigger("click");
Which works for all item except for a particular item which appears at third last position in menu item list. Below is the code I am executing in which I am facing the issue:
<nav class="navbar navbar-default sidebar" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-sidebar-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="collapse navbar-collapse" id="bs-sidebar-navbar-collapse-1">
<ul class="nav navbar-nav asurion-sidebar" >
<?php
$nav_menu_items = wp_get_nav_menu_items( 'left-sidebar' );
$menu_items = wpse170033_nav_menu_object_tree( $nav_menu_items );
$parents = get_post_ancestors( $post->ID );
foreach($menu_items as $items)
{
$parents1 = get_post_ancestors( $items->ID );
if(count($items->children) > 0)
{
?>
<li class="dropdown first-level">
<i class="fa <?php echo $items->classes[0];?>" aria-hidden="true"></i><?php echo $items->post_title;?> <i class="fa fa-angle-down menu-arrow" aria-hidden="true"></i>
<ul class="dropdown-menu forAnimate" role="menu">
<?php
foreach($items->children as $citems)
{
if(count($citems->children) > 0)
{?>
<li class="dropdown thirdlevel ">
<a style="cursor:pointer" class="dropdown-toggle naveen" data-toggle="dropdown-submenu"><i class="fa <?php echo $citems->classes[0];?>" aria-hidden="true"></i><?php echo $citems->post_title;?><i class="fa fa-angle-down menu-arrow" aria-hidden="true"></i></a>
<ul class="dropdown-submenu forAnimate lastlevel" role="menu">
<?php
foreach($citems->children as $ccitems)
{
if(strpos($ccitems->url,'localhost')){
$sea_domain = 'localhost';
}elseif(strpos($ccitems->url,'asurion.com')){
$sea_domain = 'asurion.com';
}
$compareUrl = explode($sea_domain,$ccitems->url) ;
if($_SERVER['REQUEST_URI'] == $compareUrl[1]){
?>
<script>
$(document).ready(function(){
$("a[href='<?php echo $ccitems->url;?>']").parents("li").parents("ul.dropdown-submenu").prev("a[data-toggle='dropdown-submenu']").trigger("click");
});
</script>
<?php }
echo "<li><a target='".$ccitems->target."' href='".$ccitems->url."'>".$ccitems->post_title."</a></li>";
}
?>
</ul>
</li>
<?php
}
else
{
if(strpos($citems->url,'localhost')){
$sea_domain = 'localhost';
}elseif(strpos($citems->url,'asurion.com')){
$sea_domain = 'asurion.com';
}
$compareUrl = explode($sea_domain,$citems->url);
echo "<li><a target='".$citems->target."' href='".$citems->url."'>".$citems->post_title."</a></li>";
if($_SERVER['REQUEST_URI'] == $compareUrl[1]){
?>
<script>
$(document).ready(function(){
$("a[href='<?php echo $citems->url;?>']").parents("li").parents("ul.dropdown-menu").prev(".dropdown-toggle").trigger("click");
});
</script><?php
}
}
}
?>
</ul>
</li>
<?php
}
else
{
if(get_the_title($post->ID)=="Dashboard" && $items->post_title=="Home" && count($parents)==0)
{
echo "<li class='active'><a target='".$items->target."' href='".$items->url."'> <i class='fa ".$items->classes[0]."' aria-hidden='true'></i>".$items->post_title."</a></li>";
}
else
{
echo "<li><a target='".$items->target."' href='".$items->url."'> <i class='fa ".$items->classes[0]."' aria-hidden='true'></i>".$items->post_title."</a></li>";
}
}
}
?>
</ul>
</div>
</div>
</nav>
Any Help would be appreciated.
Here is array being iterated for sidebar menu:Array, Here in the array one of the item for which the jquery snippet is failing is under "Device" > "Phone Simulators"
This is the Extracted HTML code from Source Code (It doesnt contain js code as fiddle doesnt allow js code to be writtent in html section, to find JS code, scroll above)
I can't imagine that why you output
<script>
$(document).ready(function(){
$("a[href='<?php echo $ccitems->url;?>']").parents("li").parents("ul.dropdown-submenu").prev("a[data-toggle='dropdown-submenu']").trigger("click");
});
</script>
in a loop, it will make your HTML code looks messy. and you should not output so many $(document).ready(...) at all.
you can give your <A /> a special className like 'xxx', and output the script code before </body>.
<script>
$(document).ready(function(){
$("a.xxx").parents("li").parents("ul.dropdown-submenu").prev("a[data-toggle='dropdown-submenu']").trigger("click");
});
</script>
it's a little better.
and if you want to keep the menu's status, you should use cookie or localStorage, not by this way.
and jsfiddle want you separate your html, css, js code, but through your way, your html and js can't be separated, it's not good. you can provide some css make the jsfiddle result page looks better, it can helps someone to understand your structure.

how to get specific data when i press a button

i have created a search page that gives results based on the entered values.What i want is to get specific details of the ad when the user presses the enroll button. But i am getting the details of all the ads instead of the one the user wants to enroll into.
here is the code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="css/font-awesome/css/font-awesome.min.css">
<link rel="stylesheet" href="css/basic.css">
<script src="js/jQuery/jquery.min.js"></script>
<script src="css/bootstrap/js/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.15.1/jquery.validate.min.js"></script>
<script src="Forms/form-validation.js"></script>
</head>
<body>
<?php
session_start();
require 'connection.php';
//include_once 'utlities.php';
$userEmail=$_SESSION['user'];
$form_string = 'd';
$sqlQuery ='SELECT * FROM `course` WHERE `course_title` LIKE "%'.$form_string.'%" OR `user_teacher` in (SELECT user_teacher FROM teacher where email in (SELECT email from person where fname like "%'.$form_string.'%" OR lname like "%'.$form_string.'%"));';
$queryExe=mysqli_query($connection,$sqlQuery);
$row = mysqli_fetch_assoc($queryExe)
?>
<div class="panel-body">
<?php while($row = mysqli_fetch_assoc($queryExe)) { ?>
<article class="row panel panel-default">
<div class="col-xs-6 col-xs-offset-3 col-sm-3 col-sm-offset-0">
<img src="images/profile-default.jpg" alt="Lorem ipsum" />
</div>
<div class="col-xs-12 col-sm-3">
<ul class="list-group">
<li class="list-group-item">
<i class="glyphicon glyphicon-book"></i>
<span>
<?php
echo " ".$row["description"];
?>
</span>
</li>
<li class="list-group-item">
<i class="glyphicon glyphicon-tags"></i>
<span id="courseid" >
<?php
echo " Course ID ".$row["courseid"];
?>
</span>
</li>
<li class="list-group-item">
<i class="glyphicon glyphicon-tags"></i>
<span>
<?php echo" Rs. ".$row["fees"];
?>
</span>
</li>
</ul>
</div>
<div class="col-xs-12 col-sm-6">
<h3>
<a href="#" title="">
<?php
$sql_profile =
"SELECT `fname`,`lname`,`email`
FROM `person`
WHERE `email`=(
SELECT `email`
FROM `teacher`
WHERE `user_teacher`=".$row["user_teacher"]."
);
";
$result_sql=mysqli_query($connection,$sql_profile);
$tName = mysqli_fetch_assoc($result_sql);
echo $tName["fname"]." ".$tName["lname"];
$_SESSION['temail']= $tName["email"];
?>
</a>
</h3>
<h6><?php echo $tName['email']; ?></h6>
<p class="hidden-xs"><?php echo $row["course_title"]; ?></p>
<span class="plus">
<a href="#" title="Enroll" class="btn btn-success"
<?php
/*if(loggedIn()){
echo 'data-toggle="modal" data-target="#enroll "';
}else{
echo 'data-toggle="modal" data-target="#LOGIN "';
}
/**/
?>>
<i class="glyphicon glyphicon-plus" id="enroll" ></i><span>Enroll</span>
</a>
</span>
</div>
</article>
<?php
}
?>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#enroll').click(function() {
alert($("article").find("#courseid,h6").text());
});
});
</script>
</body>
</html>
Identifiers in HTML must be unique You are generating the element in a loop, which will create duplicate ID hence the generated HTML will be invalid.
Use CSS class with elements then attach event handlers using it. You can associate the arbitrary data using data-* custom attribute which can be fetched using .data().
HTML
<i class="glyphicon glyphicon-plus enroll" data-email="<?php echo $tName['email']; ?>" data-courseid="<?php echo $row['courseid']; ?>"></i><span>Enroll</span>
SCRIPT
$('.enroll').click(function() {
var email = $(this).data('email');
var courseid = $(this).data('courseid');
});
set unique identifier to what you want to show
<?php
echo "<span id=\"courseid-".$row['courseid']." \" >";
echo " Course ID ".$row["courseid"];
?>
and to the enroll button
<?php
echo "<i class=\"glyphicon glyphicon-plus\" id=\"enroll\" data-id=\"courseid-".$row["courseid"]." \">";
?>
and in your script you show the specific text
$('#enroll').click(function() {
courseid = $(this).attr('data-id');
alert($("#"+courseid+",h6").text());
});

Categories

Resources