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());
});
Related
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.
I have a problem that when I use the loop to loop the elements in the session array it still runs normally, I try to use the code to reload only the shopping cart item, it reloads the cart, but it doesn't run. The PHP loop and my shopping cart are empty, what should I do?
<span id="soluonghang" class="badge badge-primary" style="background: #da251c;">
<?php echo $soluongsanpham; ?>
</span>
<div class="popup" id="giocart">
<div class="row header">
<span>Items</span>
<span>Amount</span>
</div>
<?php
if (isset($_SESSION['cart'])) {
foreach ($_SESSION['cart'] as $key => $value) {
?>
<div class="row items" id="itcart">
<span><?php echo $value['name']; ?></span>
<span><?php echo $a = ($value['dongia'] * $value['num']) - ($value['giam'] / 100 * ($value['dongia'] * $value['num'])) ?>đ</span>
</div>
<?php
}
} else {
}
?>
<div class="row checkout">
<span>Đi đến giỏ hàng ></span>
<span class="checkout-button" onclick="refesf()">Refesh giỏ hàng</span>
</div>
</div>
</span>
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>
I'm trying to scroll the end of the div when I open the ng-show chat window, but it only works on the second click. I've tried it in many ways but I'm not getting it to make the first click work already.
HTML CHAT:
<div class="chat">
<div class="" ng-show="chatdis">
<div class="chat-header vertical-center clearfix">
<img ng-src="user/pix.php/{{ctrl.idchat}}/f1.jpg" class="imgperfil img-circle" alt="avatar" ng-class="{'online': ctrl.useronline, 'offline': !ctrl.useronline}"/>
<div class="chat-about">
<div class="chat-with">{{ctrl.namechat}}</div>
</div>
<div class="close pull-right" style="opacity: 0.6;" ng-click="ctrl.fecharconversa()">
<i class="fa fa-times" aria-hidden="true" style="display: block;font-size: 16px;position: absolute;top: 6px;right: 8px;color: #797979;"></i>
</div>
</div> <!-- end chat-header -->
<div class="chat-history">
<ul style="margin: 0;padding: 0;">
<li ng-id="message-{{obj.id}}" class="clearfix" ng-repeat="obj in ctrl.mensagens | orderBy:'-'">
<div class="message" ng-class="{'other-message': obj.useridto == <?php echo $USER->id ?>, 'my-message float-right': obj.useridto != <?php echo $USER->id ?>}">
<p ng-bind-html="obj.smallmessage"></p>
<span class="tail-container"></span>
<span class="tail-container highlight"></span>
</div>
<div class="message-data" ng-class="{'align-right': obj.useridto != <?php echo $USER->id ?>}">
<span class="message-data-time" ng-class="{'text-right': obj.useridto != <?php echo $USER->id ?>}" ng-if="obj.useridto != <?php echo $USER->id ?>">
{{obj.firstname}} {{obj.lastname}} - {{obj.timecreated | date:"dd/MM/yyyy HH:mm"}}
</span>
<span class="message-data-time" ng-if="obj.useridto == <?php echo $USER->id ?>">
{{obj.timecreated | date:"dd/MM/yyyy HH:mm"}} - {{obj.firstname}} {{obj.lastname}}
</span>
</div>
</li>
</ul>
</div> <!-- end chat-history -->
<div class="chat-message clearfix">
<textarea name="message-to-send" ng-model="message" id="message-to-send" placeholder ="Escreva sua mensagem" rows="2"></textarea>
<button ng-click="ctrl.inseremensagem(ctrl.idchat, message, ctrl.namechat, ctrl.useronline)">Enviar</button>
</div> <!-- end chat-message -->
</div>
</div> <!-- end chat -->
CONTROLLER FUNCTION:
self.abrirconversa = function(useridfrom, name, useronline){
$rootScope.chatdis = true;
chatservice.conversachat(useridfrom).then(function(d) {
self.mensagens = d;
for(var i = 0; i < self.mensagens.length; i++){
//converte datas em Javascript
if(self.mensagens[i].timecreated != null && self.mensagens[i].timecreated != '12/31/1969 21:00'){
self.mensagens[i].timecreated = new Date(self.mensagens[i].timecreated);
}
}
self.idchat = useridfrom;
self.namechat = name;
self.useronline = useronline;
$('.chat-history').animate({scrollTop: $('.chat-history')[0].scrollHeight}, 0);
}, function(errResponse){
console.error('Error while fetching Currencies');
});
};
The controller function, I call it when I click on a list of people in the side menu. Can someone help me? :D
I am trying to implement infinity scroll but I am having issues. profile_page.php by default, should display 10 posts, then when the user reaches the bottom of the page, it should display another 10 rows from the database.
The problem is that I know my JQuery is working because the alert() is occuring when I reach the bottom of the page, but new data from the data is not being printed.
Here is my script (which can be found in **profile_page.php**):
<script>
$(document).ready(function(){
var load = 0;
$(window).scroll(function(){
if($(window).scrollTop() == $(document).height() - $(window).height()){
load++;
// start AJAX
$.post("inc/ajax.php", {load:load},function (data){
$(".userposts_panel").append(data); // images class
alert ("bottom");
});
}
});
});
</script>
And here is **ajax.php**
$load = htmlentities(strip_tags($_POST['load']))*10;
$query = mysqli_query ($connect, "SELECT * FROM user_thoughts WHERE added_by='$user' ORDER BY id DESC LIMIT ".$load.",10");
while ($row = mysqli_fetch_assoc($query)) {
$thought_id = $row['id'];
$message_content = $row['message'];
$date_of_msg = $row['post_details'];
$thoughts_by = $row['added_by'];
$attachent = $row['attachment'];
echo "<div class='message_wrapper'>
<div class='where_msg_displayed'>
<div class='more_options' style='float: right;'>
<li class='dropdown'>
<a 'href='#' class='dropdown-toggle' data-toggle='dropdown' role='button' aria-haspopup='true' aria-expanded='false'> More <span
class='caret'></span></a>
<ul class='dropdown-menu'>
<li><a href>Flag Post
<span id='options' class='glyphicon glyphicon glyphicon-flag' aria-hidden='true'></span> </a></li>";
if ($user == $username){
echo "<li>"; ?> <a href="del_post.php?id=<?php echo $thought_id;?>">Delete <?php
echo "<span id='remove' class='glyphicon glyphicon-remove' aria-hidden='true'></span> </a></li>";
} echo"
</ul>
</li>
</div>
<img src='$profile_pic' height= '68px' style='border: 1px solid #F0F0F0;'/>
<span style='margin-left: 10px;'>$message_content </span> <br/> <br/>";
if ($attachent !=""){
echo "<img src='user_data/attached_images/$attachent' style='width: 230px; height=230px;'/>";
} echo "
</div>
<div class='where_details_displayed'>
<a href='profile_page/$thoughts_by'> <b> $name_of_user </b> </a> - $date_of_msg
<div class='mini_nav' style='float: right;'>
<span class='glyphicon glyphicon-heart-empty' aria-hidden='true' style='padding-right: 5px;' onclick='changeIcon()' ></span> |
<a onclick='return toggle($thought_id);' style='padding-left: 5px;'> View comments ($num_of_comments) </a>
</div>
<div id='toggleComment$thought_id' class='new_comment' style='display:none;'>
<br/> $comment_posted_by said: $comment_body
</div>
</div>
</div>";
}
The echo consists of the divs in which each post is displayed. But when I reach the end of the page, no new content loads. For example, if there are 12 posts by user Alice, 10 will be displayed by default, then when I scroll down, the other two should load, but they dont.