Page keeps reload after clicking the Disable/Enable in php - javascript

In our page, there is 1 input that has to be manually enter by user. Upon what he has entered, some records has been shown and there is Disable or Enable beside each results(Example, I input 12345 and results are A,B,C,D, 4 results and beside of those results, there will be disable button side.). Currently, what is happening is when I click Disable or Enable, the page reload automatically and I can't find a way to fix it. Is there anyway to stop reloading? I use window.history.go(-1). it update the database but the page keeps reload every time I disable or enable.
Below is HTML codes.
<body onload="OnLoad()">
<form class="form-horizontal" name="translot" method="post">
<form id="form" method="post">
<div class="col" style="width: 580px; font-weight: bold; border: 1px solid SteelBlue; color: #6699CC; margin-left: 170px;">
<p style="background-color: #6699CC; font-size: 16px; width: 580px; padding: 5px; color: #FFF; font-weight: bold; margin-left: -1px;margin-top: -1px;"></p>
<div class="form-group">
<br>
<label class="control-label col-sm-4" for="productlotid">Lot ID:</label>
<div class="col-sm-4">
<p class="form-control-static" style="margin-top: -6px;">
<input type="text" class="form-control" id="productlotid" name="productlotid" onkeydown="return KeyDown()" onkeyup="this.value=this.value.toUpperCase()" onkeypress="return searchKeyPress(event)" min="1" placeholder="Enter Lot ID" value="<?php echo $productlotid; ?>">
</p>
<?php
include("correlationwafer_result.php");
?>
</div>
<div id="result" style="display: inline-table; margin-left: 150px; margin-top: 22px;"></div>
<!--div id="result" ></div-->
<div class="col-sm-10">
</div>
<br>
</div>
</div>
<br>
<div style="margin-right: 65px;">
<p align="center"><button type="button" class="btn btn-info " name="cmdSubmit" id="cmdSubmit" onclick="Submit()"><b>Go</b></button> <button type="button" class="btn btn-warning" name="cmdReset" onclick="Reset()"><b>Reset</b></button></p>
</div>
</form>
</form>
Below is php code from correlationwafer_result.php.
<?php
// ini_set("memory_limit","512M");
include("_dbconn.php");
include("//sgewsnant21.amk.st.com/ewsweb/wwwroot/library/common7/db_config.inc");
include("//sgewsnant21.amk.st.com/ewsweb/wwwroot/library/common7/standard_defines.inc");
session_start();
$productlotid = isset ($_GET['productlotid'])? $_GET['productlotid']:'';
//$sql1 = "Update * FROM productdb.tbl_correlationwafer WHERE lotid = '$productlotid' ORDER BY lotid and zone_enable='0'";
$sql = "SELECT * FROM productdb.tbl_correlationwafer WHERE lotid = '$productlotid' ORDER BY product asc, zone asc";
$result1 = mysqli_query($conn,$sql);
echo "<table id='corwafer'>";
$arr = array();
while ($row = mysqli_fetch_assoc($result1)) {
$field1name = $row["lotid"];
$field2name = $row["product"];
$field3name = $row["ewsflow"];
$field4name = $row["zone"];
$field5name = $row["zone_enable"];
$key = $field1name + ":" + $field2name + ":" + $field3name;
if (!in_array($key, $arr)){
array_push($arr, $key);
}
?>
<form action='test.php' method='post' enctype='multipart/form-data'>
<?php
echo "<tr>";
echo "<td>";
if($field5name == 1){
echo "<input type='hidden' id='chkzone' name='chkzone' value='$field4name'>";
echo "<input type='hidden' id='pid' name='pid' value='$field1name'>";
echo" <label for='chkzone'> Product - $field2name </label>";
echo" <label for='chkzone'> :: Zone - $field4name </label>";
//echo" <label for='chkzone'> :: Zone - $field4name </label>";
echo "<a class='btn btn-secondary text-light btn-sm' href='test.php?id=$field4name&pid=$field1name'>Disable</a>";
}
else if($field5name == 0){
echo "<input type='hidden' id='chkzone' name='chkzone' value='$field4name'>";
echo "<input type='hidden' id='pid' name='pid' value='$field1name'>";
echo" <label for='chkzone'> Product - $field2name </label>";
echo" <label for='chkzone'> :: Zone - $field4name </label>";
//echo" <label for='chkzone'> :: Zone - $field4name </label>";
echo "<a class='btn btn-secondary text-light btn-sm' href='test_1.php?id=$field4name&pid=$field1name'>Enable</a>";
}
echo "</td>";
echo "</tr>";
?>
</form>
<?php
}
echo "</table>";
flush();
mysqli_close($conn);
?>
Below codes are from test.php page.
<?php
// ini_set("memory_limit","512M");
include("_dbconn.php");
include("//sgewsnant21.amk.st.com/ewsweb/wwwroot/library/common7/db_config.inc");
include("//sgewsnant21.amk.st.com/ewsweb/wwwroot/library/common7/standard_defines.inc");
session_start();
$zone = $_GET['id'];
$pid = $_GET['pid'];
$updateQuery = "UPDATE productdb.tbl_correlationwafer SET zone_enable='0' WHERE zone='$zone' AND lotid='$pid'";
$result = mysqli_query($conn,$updateQuery);
if($result){
echo "<script>window.history.go(-1);</script>";
//echo "<script>return false;</script>";
}else{
echo "<script>window.history.go(-1);</script>";
//echo "<script>return false;</script>";
}
flush();
mysqli_close($conn);
?>
Below is from test_1.php.
<?php
// ini_set("memory_limit","512M");
include("_dbconn.php");
include("//sgewsnant21.amk.st.com/ewsweb/wwwroot/library/common7/db_config.inc");
include("//sgewsnant21.amk.st.com/ewsweb/wwwroot/library/common7/standard_defines.inc");
session_start();
$zone = $_GET['id'];
$pid = $_GET['pid'];
$updateQuery2 = "UPDATE productdb.tbl_correlationwafer SET zone_enable='1' WHERE zone='$zone' AND lotid='$pid'";
$result = mysqli_query($conn,$updateQuery2);
if($result){
echo "<script>window.history.go(-1);</script>";
//echo "<script>return false;</script>";
}else{
echo "<script>window.history.go(-1);</script>";
//echo "<script>return false;</script>";
}
flush();
mysqli_close($conn);
?>

I'm not an expert so, please, correct me if I'm wrong.
As far as I can see, you're passing query parameters through an <a></a>. As it has an URL specified in the href attribute, it will redirect you right there.
I would definitely use Ajax, as suggested by #CBroe. It will allow you to pass whatever parameters you need for updating your database to the server, without reloading the page. You'll be also able to improve the user experience, and refactor some of the code you've shared.
Take a look at this guide, it helped me a lot to understand how it works.
Good luck!

Related

how to implement jquery load on scroll

I have got a page in which I'm getting a users all friends posts now I want to get only 15 post first and then get I wanna add a load more button and then load 15 more posts how should I do that.
This is my code
$query = "SELECT ph.likes, ph.image_url,ph.email,ph.username,ph.uid ,ph.id
FROM photos as ph
inner join followers as fol
on fol.user_id = ph.uid
where fol.uid = '$id'
ORDER BY ph.image_url DESC ";
$fire = mysqli_query($con,$query) or die("can not fetch data from database ".mysqli_error($con));
if (mysqli_num_rows($fire)>0) {
while ($users = mysqli_fetch_assoc($fire)) {
$likes = $users['likes'];
$username = $users['username'];
$uid = $users['uid'];
$pixid = $users['id'];
}
}
?>
<?php
$query = "SELECT ph.ext, ph.likes,ph.desccription, ph.image_url,ph.email,ph.username,ph.uid ,ph.id,ph.avatar_path
FROM photos as ph
inner join followers as fol
on fol.user_id = ph.uid
where fol.uid = '$id'
ORDER BY ph.image_url DESC ";
$fire = mysqli_query($con,$query) or die("can not fetch data from database ".mysqli_error($con));
if (mysqli_num_rows($fire)>0) {
while ($users = mysqli_fetch_assoc($fire)) {
$likes = $users['likes'];
$description = $users['desccription'];
$username = $users['username'];
$uid = $users['uid'];
$pixid = $users['id'];
$avatar_path5 = $users['avatar_path'];
?>
<div class="all" >
<div class="card" >
<div class="float" >
<div class="avatar" >
<img src="<?php echo $avatar_path5; ?>" width="100%" class="avatar">
</div>
<div class="username" style="font-weight: 600; size: 14px; text-decoration: none; color: black !important; ">
<p style="color: black !important;"><?php echo "<div><a href='users?id=".$users['uid']."' style='color: black !important; '>
<h3>".$users['username']."</h3>
</div></a>"; ?></p>
</div>
</div>
<?php
if ($users['ext']=='mp4') {
?>
<video class="videos" controlsList="nofullscreen nodownload" style="width: 100%; height:100%;" controls autoplay="true" muted>
<source src="<?php echo $users['image_url']?>" type="video/mp4">
</video>
<?php
}else{
?>
<img src="<?php echo $users['image_url']?>" alt="Avatar" style="width:100%;">
<?php }
?>
<div class="container">
<h4><b><?php echo "<div><a href='users?id=".$users['uid']."'>
</div></a>";?></b></h4>
</div>
<div style="padding: 2px; margin-top: 5px;">
<?php
if (isset($_POST['liked'])) {
$postid = $_POST['postid'];
$result = mysqli_query($con, "SELECT * FROM photos WHERE id=$postid")or die(mysqli_error($con));
$row = mysqli_fetch_array($result)
or die(mysqli_error($con));
$n = $row['likes'];
mysqli_query($con, "INSERT INTO likes (user_id,username, post_id,avatar_path) VALUES ($id, '$fullname', $postid,'$activeavatar')")or die(mysqli_error($con));
mysqli_query($con, "UPDATE photos SET likes=$n+1 WHERE id=$postid")or die(mysqli_error($con));
echo $n+1;
exit();
}
if (isset($_POST['unliked'])) {
$postid = $_POST['postid'];
$result = mysqli_query($con, "SELECT * FROM photos WHERE id=$postid")or die(mysqli_error($con));
$row = mysqli_fetch_array($result)or die(mysqli_error($con));
$n = $row['likes'];
mysqli_query($con, "DELETE FROM likes WHERE post_id=$postid AND user_id=$id")or die(mysqli_error($con));
mysqli_query($con, "UPDATE photos SET likes=$n-1 WHERE id=$postid")or die(mysqli_error($con));
echo $n-1;
exit();
}
?>
</div>
<script type="text/javascript">
$('video').each(function(){
if ($(this).is(":in-viewport")) {
$(this)[0].play();
} else {
$(this)[0].pause();
}
})
</script>
<div>
<?php
// determine if user has already liked this post
$results = mysqli_query($con, "SELECT * FROM likes WHERE user_id=$id AND post_id=".$users['id']."")or die(mysqli_error($con));
if (mysqli_num_rows($results) == 1 ): ?>
<!-- user already likes post -->
<span class="unlike fas fa-heart " data-id="<?php echo $users['id']; ?>"></span>
<span class="like hide far fa-heart" onclick="PlaySound()" data-id="<?php echo $users['id']; ?>"></span>
<?php else: ?>
<!-- user has not yet liked post -->
<span class="like far fa-heart" onclick="PlaySound()" data-id="<?php echo $users['id']; ?>"></span>
<span class="unlike hide fas fa-heart " data-id="<?php echo $users['id']; ?>"></span>
<?php endif ?>
<a class="com" style="color: #929292 !important; " href="show?post_id=<?php echo $users['id'];?>" style=""> <span class="glyphicon glyphicon-comment trigger" ></span>comments</a>
<div class="wink" style=" color: black;
width: 30px;
height: 30px;
margin-top: -20px;
margin-left: 209px;
" > <?php
?></div>
<div class="float2">
<div class="react2" id="react2" data-rowid="<?php echo $pixid?>"><?php
$query2 = "SELECT * FROM gormint where post_id = $pixid and user_id= $id3";
$fire2 = mysqli_query($con,$query2) or die("can not fetch data from database ".mysqli_error($con));
$query3 = "SELECT * FROM bhai where post_id = $pixid and user_id= $id3";
$fire3 = mysqli_query($con,$query3) or die("can not fetch data from database ".mysqli_error($con));
$query4 = "SELECT * FROM famer where post_id = $pixid and user_id= $id3";
$fire4 = mysqli_query($con,$query4) or die("can not fetch data from database ".mysqli_error($con));
$query5 = "SELECT * FROM muskan where post_id = $pixid and user_id= $id3";
$fire5 = mysqli_query($con,$query5) or die("can not fetch data from database ".mysqli_error($con));
if (mysqli_num_rows($fire2)>0) {
echo "<img src='gormint.jpg' class='gormint2' style='width:30px; height:30px;' >";
}elseif (mysqli_num_rows($fire3)>0) {
echo "<img src='bhai.jpg' class='bhai2' style='width:30px; height:30px;'>";
}elseif (mysqli_num_rows($fire4)>0) {
echo "<img src='famer.jpg' class='bhai2' style='width:30px; height:30px;'>";
}elseif (mysqli_num_rows($fire5)>0) {
echo "<img src='bancho.jpg' class='bhai2' style='width:30px; height:30px;'>";
} else{
echo "<img src='wink.png' class='wink2' style='width:30px; height:30px;'>";
}?>
</div>
<div class="flipClass" style="display: flex;" data-rowid="<?php echo $pixid?>" id="flip">react</div>
<div class="panelClass" style="" id="panel" data-rowid="<?php echo $pixid?>">
<input type="image" onclick="PlaySound2()" id="display" data-value="<?php echo $users['id'];?>" src="gormint2.jpg" class="close2 display gormint animated bounceIn " >
<input type="image" onclick="PlaySound3()" data-value="<?php echo $users['id'];?>" data-rowid="<?php echo $pixid?>" id="display2" src="bhai.jpg" class="close2 display2 bhai animated bounceIn">
<input type="image" data-rowid="<?php echo $pixid?>" onclick="PlaySound4()" data-value="<?php echo $users['id'];?>" id="display3" src="famer.jpg" class="close2 display3 bhai animated bounceIn">
<input type="image" onclick="PlaySound5()" data-value="<?php echo $users['id'];?>" id="display4" src="bancho.jpg" class="close2 display4 bhai animated bounceIn">
</div>
</div>
<div class="count2 ">
<span id="count" style="margin-top: -5%;" class="likes_count"><?php echo $users['likes']; ?> likes</span><?php
if ($description=='') {
echo "";
}else{ echo '<p style="margin-bottom: 5%" class="written"> <b>'.$users["username"].'</b> '.$description;'</p>';
}
?>
</div>
<form method="POST" action="" >
<div class="commentdiv">
<input type="hidden" name="id" id="id" class="id" value="<?php echo $pixid;?>">
<input type="hidden" name="username" id="username" value="<?php echo $activeusername;?>">
<input type="hidden" name="uid" id="uid" value="<?php echo $id3;?>">
<textarea style="" name="comment" id="comment" class="comment" placeholder=" comment here"></textarea>
<button type="button" style="background-color: Transparent;
background-repeat:no-repeat;
border: none;
cursor:pointer;
overflow: hidden;
color: #3897f0; font-weight:600;" class="submit" id="button_id">comment</button>
</div>
</form>
</div>
<div id="comments">
<?php
$sql = "SELECT * FROM comment where post_id='$pixid' limit 3";
$results = mysqli_query($con,$sql);
if (mysqli_num_rows($results)>0) {
while ($row = mysqli_fetch_assoc($results)) {
$commentid = $row['id'];
$comment = $row['comment'];
$string = covertHashtags($comment);
echo "<p class='written'>";
echo "<a href='users2?id=".$row['user_id']."' style='color:black !important;'><b>".$row['username']."</b></a>";
echo " ".$string;
$sql3 = "SELECT * FROM comment where id ='$commentid' and user_id='$id' order by comment desc limit 5 ";
$results3 = mysqli_query($con,$sql3);
if (mysqli_num_rows($results3)>0) {
echo "<div class='dropdown'>
<img src='ellipsis.png' class='dots'>
<div class='dropdown-content'>
<br><p class='delete' data-delete=".$commentid.">delete</p>
</div>
</div>";
}
else{
echo "";
}
echo "</p>";
}
}else{
echo "";
}
?>
</div>
</div>
<br><br>
<?php } ?>
now what should I do to add a load more button after first 15 posts and when user clicks on that button I want to load more 15 posts and there is also one more problem I have a set a refresh functionality through j query whenever a user clicks on like button or comments the page refreshes so would this cause any problem?

Show/hide info using slideToggle on button

Objective Inserting name(input-text) and info(textarea-contains multiple lines) into the database, and after submission of the form, at the same page, 2 columns are for displaying the same data in columns, name & info, but under info column. I have made buttons for each row in front of the names, which is used as slideToggle for showing/hiding which contains the data retrieved from the 'info' column
Problem - when I am clicking the button of 1st row, instead of displaying the info related to 1st entry only, it is sliding and showing all info(s) related to all entries at only click.
*others - one more input has been added to the form but as hidden used for id(auto increment)
----index.php-----
<?php include('php_code.php'); ?>
<?php
if (isset($_GET['edit'])) {
$id = $_GET['edit'];
$update = true;
$record = mysqli_query($db, "SELECT * FROM records WHERE id=$id");
if (count($record) == 1 ) {
$n = mysqli_fetch_array($record);
$name = $n['name'];
$acc = $n['acc_no'];
$info = $n['info'];
}
}
?>
<html>
<head>
<title>JSK</title>
<link rel="stylesheet" href="style.css" type="text/css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('form').hide();
$('p').hide();
$('#sp').hide();
$("#inf").click(function(){
$("p").slideToggle();
$('#sp').slideToggle();
});
$("#fo").click(function(){
$("form").slideToggle();
});
});
</script>
</head>
<body>
<div class="container">
<div class="left">
<?php if (isset($_SESSION['message'])): ?>
<div class="msg">
<?php
echo $_SESSION['message'];
unset($_SESSION['message']);
?>
</div>
<?php endif ?>
<?php $results = mysqli_query($db, "SELECT * FROM records"); ?>
<table>
<thead>
<tr>
<th>Name</th>
<th>Account No</th>
<th>Info</th>
<th colspan="2">Action</th>
</tr>
</thead>
<?php while ($row = mysqli_fetch_array($results)) { ?>
<tr>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['acc_no']; ?></td>
<td><button id="inf" onclick="myFunction()">show</button></td>
<td>
<a href="index.php?edit=<?php echo $row['id']; ?>" class="edit_btn" >Edit</a>
</td>
<td>
Delete
</td>
</tr>
<tr id="sp"> <td colspan="4"><p> <?php echo $row['info']; ?> </p></td>
</tr>
<?php } ?>
</table>
<div id="fotable" align="center">
<button id="fo">Add New/Edit</button>
</div>
<form method="post" action="php_code.php" >
<input type="hidden" name="id" value="<?php echo $id; ?>">
<div class="input-group">
<label>Name</label>
<input type="text" autocomplete="off" name="name" value="<?php echo $name; ?>">
</div>
<div class="input-group">
<label>Account No</label>
<input type="text" name="acc" value="<?php echo $acc; ?>">
</div>
<div class="input-group">
<label for="info">Info</label>
<textarea class="form-control" rows="8" name="info" id="info"><?php echo $row['info']; ?></textarea>
</div>
<div class="input-group">
<?php if ($update == true): ?>
<button class="btn" type="submit" name="update" style="background: #556B2F;" >update</button>
<?php else: ?>
<button class="btn" type="submit" name="save" >Add Account</button>
<?php endif ?>
</div>
</form>
</div><!-- left closed -->
<div class="right">
hello
</div> <!-- right closed -->
</div> <!-- container closed -->
</body>
</html>
---php_code.php-----
<?php
session_start();
$db = mysqli_connect('localhost', 'root', '', 'jskrecords');
// initialize variables
$name = "";
$acc = "";
$info = "";
$id = 0;
$update = false;
if (isset($_POST['save'])) {
$name = $_POST['name'];
$acc = $_POST['acc'];
$info = $_POST['info'];
mysqli_query($db, "INSERT INTO records (name, acc_no, info) VALUES ('$name', '$acc', '$info')");
$_SESSION['message'] = "Account saved";
header('location: index.php');
}
if (isset($_POST['update'])) {
$id = $_POST['id'];
$name = $_POST['name'];
$acc = $_POST['acc'];
$info = $_POST['info'];
mysqli_query($db, "UPDATE records SET name='$name',acc_no='$acc',info='$info' WHERE id=$id");
$_SESSION['message'] = "Account updated!";
header('location: index.php');
}
if (isset($_GET['del'])) {
$id = $_GET['del'];
mysqli_query($db, "DELETE FROM records WHERE id=$id");
$_SESSION['message'] = "ACC deleted!";
header('location: index.php');
}
?>
Concept:
If you are creating multiple form from same mysql table using php script, You need to give each form a unique id.
e.g.
<form method="post" action="php_code.php" id="form<?= $id ?>">
Then add data-target="#form" to button with class 'inf'. It will store id of form.
<button class="inf" data-target="#form<?= $id ?>">show</button>
When button is clicked we know which form to open from data-target.
<script>
$('.container').on('click','button.inf',function(e){
e.preventDefault();
var formid=$(this).attr('data-target'); //get value of data-target attribute
//...proceed to play toggle with this form 'formid'

modal popup keep populating only first item data on all item buttons

I am implementing cloth shopping website in which i am uploading cloth items with their images and description from admin panel. on home page i am retrieving all cloth items that are in stock and displaying using while loop. in order to view details i have put "view button" which on click opens modal popup and displays whole description of the item. But i am facing problem that every button of item on click only displays first item description in modal popup on all item button. I want that every item button should display item owns description. but it keeps populating first item data on every button.
Code:
<?php
$link = mysql_connect("localhost", "root", "") or die("Cannot Connect to the database!");
mysql_select_db("login", $link) or die("Cannot select the database!");
$sql = "SELECT * FROM add_stock";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {?>
<div class="grid_element">
<div class="show-image">
<form method="post" action="" id="myform" >
<img src="<?php echo $row['image'] ?>" name="image" onclick="openModal()" id="image" name="image1" target="_parent">
<figcaption>
<b>Product Code: <?php echo $row['id']; ?> <br/>
<?php echo $row['dress_description']; ?> <br/>
PKR <?php echo $row['price']; ?></b>
</figcaption>
</form>
<!-- view button -->
<button class="update fa fa-eye" id="popupview" onclick="openModal1()" title="View" type="image" /></button>
<!-- View Item modal popup -->
<div id="mpopupBox" class="mpopup">
<!-- mPopup content -->
<div class="mpopup-content">
<div class="mpopup-head">
<span class="close7">×</span>
<h2 style="font-family:Cooper Black;">Item Description</h2>
</div>
<div class="mpopup-main" ><br/>
<img src="<?php echo $row['image']; ?>" style="width: 300px; height: 300px; border-radius: 25px;">
<p style="margin-top: -250px; margin-left: 380px; "><font size="4"><b>Product Code: <?php echo $row['id']; ?> <br/>
PKR <?php echo $row['price']; ?> <br/>
Brand: <?php echo $row['brand_name']; ?> <br/>
Gender: <?php echo $row['gender_name']; ?><br/>
Category: <?php echo $row['category_name']; ?><br/>
Size: <?php echo $row['size_name']; ?> <br/>
Material: <?php echo $row['material_name']; ?> <br/>
Description: <?php echo $row['dress_description']; ?></font></b> </p>
<button style="margin-left: 380px; margin-top: 20px; width: 135px;" class="button button4 add-to-cart"><i class="fa fa-shopping-cart"></i>Add to Cart</button>
</div>
<div class="mpopup-foot">
<!-- <p>created by CodexWorld</p> -->
</div>
</div>
</div>
<script type="text/javascript">
var mpopup = document.getElementById('mpopupBox');
// get the link that opens the mPopup
var mpLink = document.getElementById("popupview");
// get the close action element
var close7 = document.getElementsByClassName("close7")[0];
// open the mPopup once the link is clicked
mpLink.onclick = function () {
mpopup.style.display = "block";
}
var imagess = document.querySelectorAll('button[title="View"]');
for (var i = 0, len = imagess.length; i < len; i++) {
imagess[i].addEventListener('click', openModal1);
}
function openModal1() {
mpopup.style.display = "block";
}
// close the mPopup once close element is clicked
close7.onclick = function () {
mpopup.style.display = "none";
}
</script>
</div>
</div>
1) The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead. Stop using mysql functions.
2) Why to connect database connection on each and every file. Create one common db file where database connection code is written and include in each file. Otherwise, when database or username or password get changed, then you have to change it in each and every file. So, to avoid it, create one common db file.
db.php
<?php
$link = mysql_connect("localhost", "root", "") or die("Cannot Connect to the database!");
mysql_select_db("login", $link) or die("Cannot select the database!");
?>
3) IDs can't be same through out a page. So, change it accordingly.
YourPage.php
<?php
include("db.php");
$result = mysql_query("SELECT * FROM add_stock");
while ($row = mysql_fetch_assoc($result)) {?>
<div class="grid_element">
<div class="show-image">
<form method="post" action="" id="myform" >
<img src="<?php echo $row['image'] ?>" name="image" onclick="openModal()" id="image" name="image1" target="_parent">
<figcaption>
<b>Product Code: <?php echo $row['id']; ?> <br/>
<?php echo $row['dress_description']; ?> <br/>
PKR <?php echo $row['price']; ?></b>
</figcaption>
</form>
<button class="update fa fa-eye openPopUp" data-url="ajax_pop_up.php?id=<?php echo $row['id'];?>" title="View" type="image" /></button>
</div>
</div>
<?php }?>
<style>
.displayBlock{display:block;}
.displayNone{display:none;}
</style>
<div id="mpopupBox" class="mpopup displayNone">
</div>
<script>
//For Opening Pop Up
$(document.body).on('click', '.openPopUp', function () {
$("#mpopupBox").removeClass("displayNone").addClass("displayBlock");
$.ajax({url:$(this).attr('data-url'),cache:false,success:function(result){
$("#mpopupBox").html(result);
}});
});
//For Closing Pop Up
$(document.body).on('click', '.close7', function () {
$("#mpopupBox").removeClass("displayBlock").addClass("displayNone");
});
</script>
4) Create one common ajax pop up file in same directory, where pop up content will appear.
ajax_pop_up.php
(if you are planning to change file name here, change in data-url of YourPage.php page, both are related to each other)
<?php
include("db.php");
$result = mysql_query("SELECT * FROM add_stock WHERE id=".$_GET['id']);
while ($row = mysql_fetch_assoc($result)){?>
<!-- mPopup content -->
<div class="mpopup-content">
<div class="mpopup-head">
<span class="close7">×</span>
<h2 style="font-family:Cooper Black;">Item Description</h2>
</div>
<div class="mpopup-main" ><br/>
<img src="<?php echo $row['image']; ?>" style="width: 300px; height: 300px; border-radius: 25px;">
<p style="margin-top: -250px; margin-left: 380px; "><font size="4"><b>Product Code: <?php echo $row['id']; ?> <br/>
PKR <?php echo $row['price']; ?> <br/>
Brand: <?php echo $row['brand_name']; ?> <br/>
Gender: <?php echo $row['gender_name']; ?><br/>
Category: <?php echo $row['category_name']; ?><br/>
Size: <?php echo $row['size_name']; ?> <br/>
Material: <?php echo $row['material_name']; ?> <br/>
Description: <?php echo $row['dress_description']; ?></font></b> </p>
<button style="margin-left: 380px; margin-top: 20px; width: 135px;" class="button button4 add-to-cart"><i class="fa fa-shopping-cart"></i>Add to Cart</button>
</div>
<div class="mpopup-foot">
<!-- <p>created by CodexWorld</p> -->
</div>
</div>
<?php }?>
Similar Question
GET PHP variable value from HTML data-id
Passing data via Modal Bootstrap and getting php variable?
Quick Links
Can an html element have multiple ids?
Go through it. And, if any problem comes, feel free to ask.

keep checkbox checked after submit using foreach loop?

My Code is:
<form method="POST" action="" style="margin-top: 30px;">
<div class="form-group" style="display: inline-block;">
<label for="Name" class="label-control" >Device Price</label>
<input type="text" name="price" class="form-control">
</div>
<div class="row" style="margin-bottom: 20px;">
<div class="col-md-3">
<?php
$r = 0;
$sql = "SELECT * FROM Subscribes ";
$result = $db->query($sql);
while ($row = $result->fetch_assoc()) {
if ($r == 5) {
echo "</div><div class='col-md-3'>";
$r = 0;
}
$r++;
$p = $row['price'];
echo "<label style='font-size: 16px; margin: 20px;'>";
echo "<input name='checkbox[]' type='checkbox' ";
echo "value=" . $p . " >" . $row['sub_name'];
if ($p == 0) {
echo "<label style='color:#f00'> Free </label>";
}
echo "</label>";
}
?>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group" style="margin-left: 35%;">
<button class="btn btn-info" name="sum" style="font-size: 24px;">TOTAL</button>
<label style="margin-left: 6%; font-size: 24px;">
<?php
if (isset($_POST['sum'])) {
$price = $_POST['price'];
$price = $price + $price * .52;
$total = $price;
if (!empty($_POST['checkbox'])) {
foreach ($_POST['checkbox'] as $value) {
$total = $total + $value;
}
}
echo $total;
}
?></label>
</div>
</div>
</div>
You can put a checked property to a checkbox:<input type="checkbox" checked>"
In your case, you have to check the POST data in the first block aswell and add the checked property to checkboxes that have been submitted.
echo "<input name='checkbox[]' type='checkbox' ";
echo "value=" . $p;
//if value is in the array of submitted checkboxes, add the checked property
if(array_search($p ,$_POST["checkbox"]) >= 0) echo "checked";
echo ">" . $row['sub_name'];
You can almost just check posted value to see if checked[$r] is on, but in the case where the user leaves some of the boxes unchecked, those don't get posted.
So, you need a way to identify each checkbox. You could do this by naming them like this when you echo them:
$id = $row['id']; // or whatever your id is
echo "<input name='checkbox[$id][]' type='checkbox' value=$p >"
Now, when the user submits the form, you know exactly which checkboxes should be checked. So you can simply add the checked attributed when you render them:
echo "<input name='checkbox[$id][]' type='checkbox' value=$p $checked>"
So altogether:
<?php
$r = 0;
$sql = "SELECT * FROM Subscribes ";
$result = $db->query($sql);
while ($row = $result->fetch_assoc()) {
if ($r == 5) {
echo "</div><div class='col-md-3'>";
$r = 0;
}
$r++;
$p = $row['price'];
$id = $row['id'];
$checked = null;
if(array_key_exists('checkbox', $_POST) && array_key_exists($id, $_POST['checkbox']){
$checked = "checked";
}
echo "<label style='font-size: 16px; margin: 20px;'>";
echo "<input name='checkbox[$id][]' type='checkbox' value=$p $checked>" . $row['sub_name'];
if ($p == 0) {
echo "<label style='color:#f00'> Free </label>";
}
echo "</label>";
}
?>

Get input before submitting to insert into action url

Im trying to get a value of an input into my buttons action url before the button is pushed.
I need to get the value of:
id="qty<?php echo $i;?>"
Into where it says:
<?php echo VALUE OF $qtyforaction; ?>
My Code is:
<?php $i = $_product->getId();?>
<form action="<?php echo $this->helper('checkout/cart')->getAddUrl($_product); ?>" method="post" id="product_addtocart_form_<?php echo $_product->getId()?>"<?php if($_product->getOptions()): ?> enctype="multipart/form-data"<?php endif; ?>>
<input type="text" name="qty" id="qty<?php echo $i;?>" maxlength="12" value="1" title="Qty" class="cartnum" />
<?php $qtyforaction = 'qty'.$i; ?>
<?php echo $qtyforaction; ?>
<button type="button" class="addtocartbutton button btn-cart" onclick="setLocation('<?php echo $this->helper('checkout/cart')->getAddUrl($_product); ?>qty/<?php echo VALUE OF $qtyforaction; ?>')" ><span><span>Order Again</span></span></button>
</form>
Would I have to use javascript to get it into the url string? My javascript is a bit ropey, would something like this work?
<script type="text/javascript">
var something= document.getElementById('<?php echo $qtyforaction;?>');
</script>
UPDATE WITH FULL CODE:
<?php
if (Mage::getSingleton('customer/session')->isLoggedIn()) {
/* Get the customer data */
$customer = Mage::getSingleton('customer/session')->getCustomer();
/* Get the customer's email address */
$customer_email = $customer->getEmail();
}
$collection = Mage::getModel('sales/order')->getCollection()->addAttributeToFilter('customer_email', array(
'like' => $customer_email
));
$uniuqProductSkus = array();
foreach ($collection as $order) {
$order_id = $order->getId();
$order = Mage::getModel("sales/order")->load($order_id);
$ordered_items = $order->getAllItems();
foreach ($ordered_items as $item)
{
if (in_array($item->getProduct()->getSku(), $uniuqProductSkus)) {
continue;
} else {
array_push($uniuqProductSkus, $item->getProduct()->getSku());
$_product = Mage::getModel('catalog/product')->load($item->getProductId());
$product_small_image_path = Mage::helper('catalog/image')->init($_product, 'small_image')->resize(200);
$product_thumbnail_path = Mage::helper('catalog/image')->init($_product, 'small_image')->resize(150);
$summaryData = Mage::getModel('review/review_summary')->load($item->getProductId());
echo "<li>";
echo "<div class='previous-name'><p><a style='color:black; font-weight:bold; font-size:14px;' href='" . $_product->getProductUrl() . "'>";
echo $item->getName() . "</a></p></div>";
echo "<div class='previous-image'><a href='" . $_product->getProductUrl() . "'>";
echo "<img src='" . $product_small_image_path . "' />";
echo "</a></div>";
echo "<div class='previous-rating'>";
echo "<p><a style='color:black; font-weight:bold; font-size:14px;' href='" . $_product->getProductUrl() . "#product_tabs_review_tabbed'>Review this beer now</a></p>";
echo $summaryData->getRatingSummary() . '% Would buy again <br/>';
echo "<div class='rating-box' style='float:left;'>";
echo "<div class='rating' style='width:" . $summaryData->getRatingSummary() . "%'></div></div>";
echo "</div>";
/**echo "<div class='previous-button'>";
echo '<button type="button" title="Add to Cart" class="button btn-cart" onclick="setLocation(\'';
echo $this->helper('checkout/cart')->getAddUrl($_product);
echo '\')"><span><span>Order Again</span></span></button>';
echo "</div>";**/
?>
<?php $i = $_product->getId();?>
<div class='previous-button'>
<form action="<?php echo $this->helper('checkout/cart')->getAddUrl($_product); ?>" method="post" id="product_addtocart_form_<?php echo $_product->getId()?>"<?php if($_product->getOptions()): ?> enctype="multipart/form-data"<?php endif; ?>>
<input type="text" name="qty" id="qty<?php echo $i;?>" maxlength="12" value="1" title="Qty" class="cartnum" />
<?php $qtyforaction = 'qty'.$i; ?>
<script type="text/javascript">
var xy = document.getElementsByTagName("input")[0].getAttribute("qty");
var x = "<button type='button' class='addtocartbutton button btn-cart' onclick='setLocation()'><span><span>Order Again</span></span></button>";
document.getElementById("buttonaddcart").innerHTML = x;
</script>
<div id="buttonaddcart">
<button type="button" class="addtocartbutton button btn-cart" onclick="setLocation('<?php echo $this->helper('checkout/cart')->getAddUrl($_product); ?>qty/')" ><span><span>Order Again</span></span></button>
</div>
</form>
</div>
<?php
echo "<div class='previous-clear'></div>";
echo "</li>";
}
}
}
?>
You need to get the value of the id attribute:
var x = document.getElementsByTagName("input")[0].getAttribute("id");
But how do you plan on using PHP to echo out this variable if PHP is loaded and done with before Javascript even comes into play? You could use Javascript though to display this variable on the page if that's all you needed.
If you had something in your HTML to target, you could do it like this:
document.getElementById("result").innerHTML = x;
But anyways, get the action attribute value...
var y = document.getElementsByTagName("form")[0].getAttribute("action");
Then set the action attribute to this + the qty...
document.getElementsByTagName("form")[0].setAttribute("action", x + y);
That should work for you, if not, try wrapping x + y in additional parentheses...("action", (x + y));

Categories

Resources