I am trying to display the username and other session values stored in session at login.php. I post the form in index.php using ajax post which is in script.js. The session is stored but I can retrieve the value only after I refresh the page.
Can anyone please help me sort this issue.
My index.php file
<div id="profile">
<?php session_start();
if(isset($_SESSION['user_name']) && $_SESSION['user_name'] != ''){
echo "Hello ".$_SESSION['user_name'];
?>
<a href='logout.php'>Logout</a>
<?php } ?>
</div>
My script.js file
success: function(html){
if(html=='true'){
$("#login_form").fadeOut("normal");
$("#profile").html("<a href='logout.php' class='red' id='logout'>Logout</a>");
}
My login.php
echo 'true';
$_SESSION['user_name']='username';
Related
I am trying to pass the ID of the clicked image to next page. When I developed my code, it didn't redirect me to the next page. When I click F12 and check the POST in network, it shows that the variable is passed correctly to the next page as shown in the attached image but it didn't redirect me to the next page. So now I know that the variable is passed and received correctly in the next page but I need what needed in my code to direct me to the next page,
Note: when I tried to put window.location.href = 'userevent.php'; it redirect me but without the variable and gives me error (Notice: Undefined index: clicked in)
Also when I use url: '#userevent.php.Action("delivery", "service")',, it gives me network status 403
this is my code:
<?php
session_start();
require "init.php";
login();
?>
<html>
<!--...-->
<head>
<meta charset="utf-8">
<title> Ghost </title>
<!-- <link rel="Stylesheet" href="css/style1.css">-->
<link rel="stylesheet" href="css/style2.css" media="screen" type="text/css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script >
function myFunction(clicked) {
document.getElementById('test').innerHTML = clicked;
$.ajax({
type: "POST",
//url: '#userevent.php.Action("delivery", "service")',
url: 'userevent.php',
dataType:'json',
data: {"clicked": clicked},
success: function(data){
}
});
window.location.href = 'userevent.php';
}
</script>
</head>
<body>
<div class="sidenav">
Main Page
About Us
</div>
<div class="login-box">
<h1>Add Event</h1>
<div>
<p id="test"> </p>
<?php
// LOGIN USER
function login(){
global $con;
global $counter;
echo "<table align='center' >";
//$email = $mysqli->escape_string('');
$query="SELECT * FROM events ORDER BY ID ASC";
$result=mysqli_query($con,$query);
if ( $result->num_rows == 0 ) // User doesn't exist
echo "User with that ID doesn't exist!";
else { // User exists
$counter = 0;
$emptyArray = [];
while($row = $result->fetch_assoc())
{
$emptyArray[$counter]= $row["ID"];
if($counter == 0)
{
echo '<tr>';
}
echo '<td><img id=' . $row["ID"]. ' onClick="myFunction(this.id)" src="images/' . $row["photo"]. '" width="250px" height= "250px" alt="Avatar" >
<h1 id = "GFG_DOWN" style =
"color:white;text-align:center; font-size: 20px; font-weight: bold;"> '.$emptyArray[$counter].'
</h1> </td>';
$counter++;
if($counter == 3)
{
echo "</tr>";
$counter = 0;
}
}
}
}
mysqli_close($con);
?>
and this is the code in the second page:
<div class='textbox'>
<label> ID: ".$_POST['clicked']."</label>
</div>
The entire point of Ajax is that that request is made with JavaScript and the response is handled by JavaScript without navigating to a new page.
If you want to make a POST request and navigate to the resulting page, then use a <form>
window.location.href = 'userevent.php';
it redirect me but without the variable
Assigning a URL to location.href triggers browser navigation (with a GET request) to that URL.
It is a completely different request to the Ajax request so it doesn't have the data from that request.
Again: Use a form for this.
I read the data from database and I get the clicked id of the images.
Put the data you want to send in a submit button instead.
<form method="POST" action="userevent.php">
<?php while($row = $result->fetch_assoc()) ?>
<button name="clicked" value="<?php echo htmlspecialchars($row["ID"]); ?>">
<img src="images/<?php echo htmlspecialchars($row["photo"]); ?> alt="Put useful and unique alt text so people know what they are selecting if they can't see the image">
</button>
<?php } ?>
</form>
I think you are better off making a small form, since you want to send the user to a new page when clicking.
<?php while($row = $result->fetch_assoc()) ?>
<form action="userevent.php" method="POST">
<input type="hidden" name="clicked" value="$row["ID"]">
<img src="images/{{ $row['photo'] }}" class="img">
</form>
<?php } ?>
$('.img').click(function() {
this.form.submit();
});
*Edited to reflect your current edits.
I'm trying to make a system similar to a like/dislike system. I have it all setup, but my jquery.ajax function is not sending the data I need it to. The function is being called, but the data is not being set.
I've added a function to check for if the isset if statement is being called, but that function isn't being called, so I know it's something wrong with the ajax function. I've tried looking over other posts of similar problems, but none of those solutions worked. Sorry if this is just me being stupid, and the solution is easy.
PHP - community.php - The main webpage
<div id="entries">
<?php foreach($posts as $post): ?>
<div class="entry">
<div class="entryInfo">
<img src="IMAGES/PlaceholderAlbumCover.jpg" alt="Album Cover" class="center" height="200" width="200">
<div class="artistInfo">
<h4><?php echo $post['name'] ?></h4>
<p> <?php echo $post['artist'] ?> </p>
</div>
<div class="votes">
<i <?php if(userVoted($post['id'])): ?>
class="fas fa-heart vote-btn"
<?php else: ?>
class="far fa-heart vote-btn"
<?php endif ?>
data-id="<?php echo $post['id'] ?>" style="color:#f44242">
</i>
<span class="voteCount"><?php echo getVotes($post['id']); ?></span>
</div>
</div>
</div>
<?php endforeach ?>
</div>
Javascript - vote.js - Handles click detection and sending the response to vote.php
$.ajax({
url: 'index.php?page=community',
method:'post',
data: {
'action':action,
'post_id':post_id
},
success: function(data) {
if(action == 'unvote') {
$click_btn.toggleClass('far fas');
} else if(action == 'vote') {
$click_btn.toggleClass('far fas');
}
}
});
PHP - vote.php - Handles the server side of the system
if(isset($_POST['action'])) {
consoleLog();
$post_id = $_POST['id'];
$action = $_POST['action'];
switch($action) {
case 'vote':
$query="INSERT INTO rating_info (user_id, post_id, rating_action)
VALUES ($user_id, $post_id, 'vote')
ON DUPLICATE KEY UPDATE rating_action='vote'";
break;
case 'unvote':
$query="DELETE FROM rating_info WHERE user_id=$user_id AND post_id=$post_id";
break;
default:
break;
}
mysqli_query($dbconnect, $query);
echo getRating($post_id);
exit(0);
}
What it's supposed to do is increment or decrement the vote count in the mysql database by setting the action to vote or unvote, but the js file just never sets the action data, or the PHP script is never able to catch it.
You are passing the post data in the javascript as post_id but trying to retrieve it in the php script as $_POST['id']
Do this instead: $_POST['post_id']
On my main page I assign four different $_SESSION variables as follows:-
<p class="p-wht space left">Working: <? echo $_SESSION['Working'] ?></p>
<p class="p-wht green space left">Clear: <? echo $_SESSION['Clear'] ?></p>
<p class="p-wht red space left">Busy: <? echo $_SESSION['Busy'] ?></p>
<p class="p-wht cyan space left">STC: <? echo $_SESSION['STC'] ?></p>
These are set when the page loads:-
include('status.controller.php');
and they are set as:
$_SESSION['Working'] = $status['Working'];
$_SESSION['Clear'] = $status['Clear'];
$_SESSION['Busy'] = $status['Busy'];
$_SESSION['STC'] = $status['STC'];
They update when the page is refreshed or first loaded, but when I am trying to update them using AJAX the values don't seem to be changing.
I have tried:-
$(function(){
setInterval(function(){
$.ajax({
url:'scripts/php/status.controller.php',
success:function(data){
if(data == "scripts/php/status.controller.php"){
}else{
alert(data);
//location.reload();
}
}
});
},4000);
});
but this doesn't seem to update the values. It only updates the values when the page is completely reloaded, including location.reload(); which I don't want to use.
Any ideas?
ADDED; contents of status.controller.php file; here is the contents of this file; nathandasilva.co.uk/status.controller.txt
Can you tell me, what is the output of scripts/php/status.controller.php page. If the page will send html as output, then you should just replace the content, example:
<div id="content">
<p class="p-wht space left">Working: <? echo $_SESSION['Working'] ?></p>
</div>
<script>
$(function() {
setInterval(function(){
$.ajax({
url:'scripts/php/status.controller.php',
success:function(data) {
$("#content").html(data);
}
});
},4000);
});
</script>
I have this problem: I can't find out how to hide a div that appears just when session begins. So I a have a X button for closing, and when the page is refreshed, the div appears again! But I don't want to stop the session.
My code:
<div id="got-points" style="display:<?php echo (isset($customer) && !empty($customer) && isset($customer['customer']) && !empty($customer['customer'])) ? 'block' : 'none'; ?>"> // Checks if session is active
<div class="got-points-bg" style="display: visible;">
<div class="got-points-box">
<img class="got-points-close" src="<?php echo base_url();?>static/images/i8.png" /> //Close Button
My text here
</div>
</div>
</div>
And js
<script>
$(document).ready(
function() {
$(".got-points-close").click(function() {
$(".got-points-bg").hide("fast");
});
});
</script>
If it is on refresh then it is easy; just do it in the PHP session; like this:
HTML:
<div id="got-points" style="display:<?php echo (isset($customer) && !empty($customer) && isset($customer['customer']) && !empty($customer['customer']) && empty($_SESSION['first_load'])) ? 'block' : 'none'; ?>"> // Checks if session is active
<div class="got-points-bg" style="display: visible;">
<div class="got-points-box">
<img class="got-points-close" src="<?php echo base_url();?>static/images/i8.png" /> //Close Button
My text here
</div>
</div>
</div>
and in your PHP before then (like on login/session start) - this will obviously need significant editing since you haven't included your PHP I can't guess it very well, but this should provide a starting point:
<?php
//load user check pseudo code
if !empty($_SESSION[user]) and whatever other checks... {
$_SESSION['first_load'] = False; //important line number 2
}
//login pseudo code to demonstrate placement within your code
if user & pass = valid {
$_SESSION['first_load'] = True; //important line number one
}
That is assuming you want th div output but not displayed on subsequent loads.
Interesting question, how about something like this?
<?php
if(isset($_SESSION['variable'])){
sleep(3); /* Duration(in seconds) div is displayed for */
echo
"<script>
$( document ).ready(function() {
$(".got-points-bg").hide("fast");
});
</script>";
}
?>
try this
<?php error_reporting(0); session_start(); if(empty($_SESSION['user'])) echo "<div id='togglediv'> My text here </div>"; ?>
hope it will work
page show2.php:
<?php
session_start();
$_SESSION["abc"]=2;
print $_SESSION["abc"];
include 'import/function.php';
?>
<html>
.............
</html>
page show1.php:
<?php
session_start();
$_SESSION["abc"]=1;
print $_SESSION["abc"];
include 'import/function.php';
?>
<html>
.............
</html>
I've bind an ajax_call to a btn in html that print $_SESSION["abc"]
session_start();
include 'import/function.php';
if(isset($_POST["data"]))
{
print $_SESSION["abc"];
}
When I go in show1.php the page print 1 and ajax_call print 1.
When I go in show2.php the page print 2 but ajax_call print 1! why?