Need an Ajax call to destroy session - javascript

I have a script where when a user get verified he/she is brought to Home.php. At the moment Home.php doesn't do much. But in the bottom left hand corner I have a log out button. And as you know when the user clicks on this button he expects his session to be destroyed and for him to be redirected to a log in page. Unfortunately you can't make a click listener in php. I have browsed for an hour looking for a solution but I have not been able to find the right key word or something.
This is my code
EDIT: You only really have to read some code from Home.php the est is only if someoe wants to run the code if they are not sure of their answer
Index.php(Login Page)
<?php
session_start();
mysql_connect("localhost","root","") or die ("cannot");
mysql_select_db("virtualdiary") or die ("db");
if (isset ($_POST["Username"])&& isset($_POST["Password"]))
{
$Username = $_POST["Username"];
$Password = $_POST["Password"];
$_SESSION["username"] = $Username;
$DB_Check = " SELECT * from users Where username = '".$Username."' and password = '".$Password."' " ;
$result = mysql_query($DB_Check);
if(mysql_fetch_assoc($result) === false){
$error = "invalid username or password";
}else{
header( 'Location: Home.php' ) ;
}
}
?>
<html>
<head>
<link type="text/css" rel="stylesheet" href="Index.css"/>
<title>Login</title>
</head>
<body>
<div id="main">
<div class="messages">
<?php
if(isset($error))
echo $error; ?>
</div>
<form action="Index.php" method="post">
<h5>Diary Name:</h5>
<input name="Username" type="text"/>
<h5>Password:</h5>
<input name="Password" type="password"/>
</br>
</br>
</br>
<input name="login" type="submit"/>
</form>
<p>Click HERE to register.</p>
</div>
</body>
</html>
Home.php
<?php
session_start();
echo "Username = " . $_SESSION["username"] . " !";
mysql_connect("localhost","root","") or die ("cannot");
mysql_select_db("virtualdiary") or die ("db");
if (isset($_POST["entry"])){
$entry = $_POST["entry"];
$submission = "INSERT INTO `virtualdiary`.`entries` (`entry`) VALUES ('". $entry . "')";
mysql_query($submission);
}
?>
<html>
<head>
<link type="text/css" rel="stylesheet" href="Home.css"/>
<title>Home</title>
</head>
<body>
<h1>Entry: </h1>
<form method="post" action="Home.php">
<textarea name="entry" rows="24" cols="87">
<?php
if (isset($_POST["entry"])){
echo $entry;
}
?>
</textarea>
</br>
</br>
<input name="submit" type="submit"/>
</form>
<button id="LogOut">Log Out</button>
</body>
</html>
From what I have found from searching around I will need a Home.js file with an ajax call. I don't know the first thing about Ajax so I will probably need code to paste or a very blunt tutorial.
Thanks

You could change the logout href to /Logout.php, and in Logout.php have
<?php
session_start();
session_destroy();
header('Location: /Index.php');
?>
That will simply destroy the users current session, then redirect the user back to the Index.php page.
The AJAX way would be (using jQuery, I can't remember the vanilla JS syntax for ajax calls)
$.ajax({
type: 'GET',
url: '/Logout.php',
success: function(msg) {
if (msg == 'loggedOut') {
window.location.href = 'Index.php';
}
}
});
And then you'd need to change Logout.php, instead of the header line, make it echo/die/print loggedOut (or a json string which would probably be better, but this is just an example).

Related

get selected value from select and post to MySQL Table

I am fairly new at PHP HTML and found some help on this site but cannot get the code to work as part of my script
On clicking the SUBMIT button a record is posted to the database table (Transactions) but the FIELD (Code) is empty, it should contain a 3 letter uppercase string e.g. ABC
The ALERT shows that the value is stored in the variable $code but an empty string is posted to the table
Your help is greatly appreciated by this novice
<?php
// Include config file
require_once 'config.php';
// Define variables and initialize with empty values
$code = "";
$code_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST")
{
// Validate Code
$code = strtoupper($code);
// Check input errors before inserting in database
if(empty($code_err)){
// Prepare an insert statement
$sql = "INSERT INTO Transactions (Code)
VALUES (?)";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "s", $param_code);
// Set parameters
$param_code = $code;
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Records created successfully. Redirect to landing page
$url = 'http://localhost:8888/portfolio/index.php';
echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL='.$url.'">';
exit();
} else{
echo "Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
}
}
// Close connection
mysqli_close($link);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Create Record</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<link href="style1.css" rel="stylesheet" type="text/css"/>
<style type="text/css">
.wrapper{
width: 450px;
margin: 0 auto;
}
</style>
<script>
function getValue(obj){
alert(obj.value);
$code=(obj.value);
**alert($code);**
}
</script>
<!--Display heading at top center of screen-->
<div>
<center><h3>Peter's Portfolio - Shares</h3></center>
</div> <!-- end of Div -->
</head>
<body style="background-color:#fcf8d9">
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-6">
<div class="page-header">
<h2>Create Transaction Record</h2>
</div>
<form class="form-horizontal" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<!-- ASX CODE -->
<div class="form-group">
<label for="name" class="control-label col-xs-6">ASX Code:</label>
<div class="col-xs-6">
<?php
$conn = new mysqli('localhost', 'root', 'root', 'Portfolio') or die ('Cannot connect to db');
$result = $conn->query("SELECT Code, Coy_Nm from Companies ORDER BY Code");
echo "<html>";
echo "<body>";
echo "<select Name='Code' ID='Code'onchange='getValue(this)'>";
while ($row = $result->fetch_assoc()) {
unset($Code, $Coy_Nm);
$Code = $row['Code'];
$Coy_Nm = $row['Coy_Nm'];
echo '<option value="'.$Code.'">'.$Coy_Nm.'</option>';
}
echo "</select>";
echo "<input type='hidden' value='submit'>";
//$code=$_POST['Code'];
//echo $code;
?>
</div>
</div>
<!--Submit and Cancel Buttons-->
<input type="submit" class="btn btn-primary" value="Submit">
Cancel
</form>
</div>
</div>
</div>
</div>
</body>
</html>
Javascript and PHP cannot simply communicate to each other live.
try this
function getValue(obj){
alert(obj);// check if obj has something in it before proceeding to "value"
alert(obj.value);
}
After require_once 'config.php',
Focus on the following line :
$code = "";
When you submit form and form action is self, this means that your post data will be sent to the same file and when the code is read from your file it makes $code empty every time. of course, an empty value will be sent to DB. move this line inside if condition or change this logic.

Send PHP errors back to index

So I have an index.php and a r.php. R.php is the registration part. And index.php is the actual form. My question is how can I have errors from r.php be send back to index.php if they exist. So instead of displaying errors on r.php I want them on index.php and prevent the form from advancing.
Here's the index.php
<!DOCTYPE html>
<html>
<body>
<form method="post" action="r.php">
<input type="text" name="name" placeholder="Name">
<input type="submit">
</form>
</body>
Its all very simple. Now here's r.php
<?php
$name = $_POST['name'];
if ($name < 3){
//display error
}
else {
//proceed
}
?>
Should I do this with JS? Or this there a better way.
One way is to use sessions:
<?php session_start(); ?>
<!DOCTYPE html>
<html>
<body>
<?php echo isset($_SESSION['message']) ? $_SESSION['message'] : ''; ?>
<form method="post" action="r.php">
<input type="text" name="name" placeholder="Name">
<input type="submit">
</form>
</body>
<?php
session_start();
unset($_SESSION['message']);
$name = $_POST['name'];
if ($name < 3){ // you probably want strlen($name) < 3
$_SESSION['message'] = 'error';
header('Location: index.php');
exit;
}
else {
//proceed
}
?>
Other than sessions you could redirect back with a query string and use that:
header('Location: index.php?message=' . urlencode('some kind of error');
Then:
<?php echo isset($_GET['message']) ? $_GET['message'] : ''; ?>
Using a single script for this would be easier, just put this all in one file, and check to see if the form has been submitted. If the form has been submitted, you an just include the variables you want straight away.
This is pretty crude, but it gives you an idea of where you can go with this:
<?php
if (isset($_POST['name'])) {
// Begin processing form stuff
$name = $_POST['name'];
// Initialise error variable
$error = null;
if ($name < 3) {
// Display error, for example:
$error = 'Name is less than 3';
} else {
// Proceed
}
}
?>
<!DOCTYPE html>
<html>
<body>
<?php if ( ! empty($error)) { ?>
<p><?php echo $error; ?></p>
<?php } ?>
<form method="post" action="r.php">
<input type="text" name="name" placeholder="Name">
<input type="submit">
</form>
</body>
</html>
<!DOCTYPE html>
<html>
<?php
$msg = '';
if(isset($_GET['e'])
{
$msg = "Error! Input not valid.";
}
?>
<body>
<?php
if($msg!='')
{
echo "<font color='red'>".$msg."</font>";
}
?>
<form method="post" action="r.php">
<input type="text" name="name" placeholder="Name">
<input type="submit">
</form>
</body>
Just pass a variable e using GET request to the index page if an error is found.
<?php
$name = $_POST['name'];
if ($name < 3){
header("Location: index.php?e=error");
}
else {
//proceed
}
?>
GET request will send the variable e using the URL, and if e is found to be having a value, it means there was an error in r.php
Use javascript for simple form validation. In case you require some security stuff or db stuff, you can use session/cookie or use header function to go back.

can I get text from html and put it into variable in php without submitting a form?

I have a form in html:
<form>
<label><input type="hidden" name="pNameChange" value=""></label>
</form>
and I want to get the value of this input in php without submitting it in a form.
this is my javascript:
var pName= null;
$(document).ready(function(){
$('img').click(function(){
pName= $(this).attr("name");
console.log(pName);
});
});
My php:
$pName = isset($_POST['pNameChange']) ? $_POST['value'] : '';
what I want is. you click on the picture,
1.the value of the name attribute of the picture is going to be saved into the variable pName (javascript),
2.it then goes into the form and changes the value of the form to the variable pName (javascript),
3.php picks up the value of the form (which should now be equal to pName),
4.then stores it into a variable $pName (php).
5.I also want $pName (php) to be globally used throughout all the pages of the website.
edit
this is my index page:
<?php
$pName = isset($_POST['pNameChange']) ? $_POST['value'] : '';
$db_connection = mysqli_connect('localhost','root','',"project_online_planner");
if (!$db_connection){
die('Failed to connect to MySql:'.mysql_error());
}
$query="SELECT * FROM project limit 5 ";
$results = mysqli_query($db_connection,$query);
$intro=mysqli_fetch_assoc($results);
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Project planner online</title>
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<script type="text/javascript" src="ppo.js"></script>
<link rel="stylesheet" href="ppo.css"/>
</head>
<body>
<div id="bgNav">
<div id="login">
Register
Log in
</div>
<nav id="nav">
Home
</nav>
</div>
<h2 class="titlePage">Home</h2>
<div id="bgTile">
<?php
while($row = mysqli_fetch_array($results))
{
$project = $row["name"];
echo nl2br("<a href='project.php'>" ."<img name=\"$project\" width='100px' alt='Procject name' height='100px' class='tile' src=". $row['image'] ."/>". "</a>");
}
?>
<div class="tile" id="tileM"><h2>Meer</h2></div>
</div>
<form>
<label><input type="hidden" name="pNameChange" value=""></label>
</form>
</body>
</html>
what I want: click on the image then you get sent to the project page where (php) $pName is equal to the value of (javascript) pName
project page:
<?php
$newRecord = null;
$pName = isset($_POST['pNameChange']) ? $_POST['value'] : '';
$db_connection = mysqli_connect('localhost','root','',"project_online_planner");
if (!$db_connection){
die('Failed to connect to MySql:'.mysql_error());
}
//insert into database
if(isset($_POST['insertComments'])){
include('connect-mysql.php');
$username = $_POST['username'];
$comment = $_POST['comment'];
$sqlinsert = "INSERT INTO user_comments (username, comment, project) VALUES ('$username', '$comment', '$pName')";
if (!mysqli_query($db_connection, $sqlinsert)){
die('error inserting new record');
}
else{
$newRecord = "1 record added";
}//end nested statement
}
//text from database
$query="SELECT * FROM user_comments where project = '$pName' ";
$results = mysqli_query($db_connection,$query);
$intro=mysqli_fetch_assoc($results);
$query2="SELECT * FROM project where name = '$pName' ";
$results2 = mysqli_query($db_connection,$query2);
$intro2=mysqli_fetch_assoc($results2);
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Project planner online</title>
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<script type="text/javascript" src="ppo.js"></script>
<link rel="stylesheet" href="ppo.css"/>
</head>
<body>
<div id="intro">
</div>
<div id="bgNav">
<nav id="nav">
Home
<a class="rightNav" href="register.php">Register</a>
<a class="rightNav" href="login.php">Log in</a>
</nav>
</div>
<div id="projectTile">
<span id="statusCheck"><?php print_r($intro2["status"]); ?></span>
<h2 id="prTitle"><?php print_r($intro2["name"]); ?></h2>
<div id="prPic"><img width="300" height="200" src="<?php print_r($intro2["image"]); ?>"></div>
<div id="prDescription"><?php print_r($intro2["description"]); ?></div>
</div>
<div id="comments">
<?php
while($row = mysqli_fetch_array($results))
{
echo nl2br("<div class='profile_comments'>" . $row['username'] . "</div>");
echo nl2br("<div class='comment_comments'>" . $row['comment'] . "</div>");
}
?>
</div>
<div id="uploadComments">
<form method="post" action="project.php">
<label for="name"><input type="hidden" name="insertComments" value="true"></label>
<fieldset>
<legend>comment</legend>
<label>Name:<input type="text" id="name" name="username" value=""></label><br/>
<label>Comments: <textarea name="comment" id="comment"></textarea></label>
<input type="submit" value="Submit" id="submitComment">
</fieldset>
</form>
</div>
<?php
echo $newRecord;
?>
<form>
<label><input type="hidden" name="pNameChange" value=""></label>
</form>
</body>
</html>
HTML:
do you have more then 1 image on page? its better if you add ID in image. No need for form and hidden fields for what you want done.
make sure your img has ID like <img id="imageID"...
JavaScript:
var pName= null;
$(document).ready(function(){
$('#imageID').click(function(){
pName= $(this).attr("name");
$.post("project.php", { pNameChange: pName },
function(data) {
// do something here.
});
});
});
above code should work as expected. Now in project.php > $_POST['pNameChange'] should receive the value of pName (image's name attr).
I don't understand what you want when you said $pName available globally on all pages. Please elaborate further, may be look into storing it as cookie/session?
EDIT:
Consider using session to pName value... by simple starting/resuming session in start of file:
<?PHP
session_start();
and then...
to set/update value:
if(isset($_POST["pNameChange"]))
$_SESSION["pName"] = $_POST["pNameChange"];
and then use $_SESSION["pName"] instead of $pName on all pages.
Try Ajax method in jQuery , hope it solves your problem
https://api.jquery.com/jQuery.ajax/
or
https://api.jquery.com/jQuery.post/
Actually, you do not need AJAX for this, all your index.php does it passes the image's name to project.php so try:
In index.php:
<form name='form1' method="post" action='project.php'> <!-- form attributes given -->
<label><input type="hidden" name="pNameChange" value=""></label>
</form>
Javascript:
var pName= null;
$(document).ready(function(){
$('img').click(function(){
//onclick of image, we will save the image name into the hidden input
//and submit the form so that it goes to project.php
$('input[name="pNameChange"]').val($(this).attr("name"));
$('form1').submit()
});
});
And in your project.php:
//now project.php can get the posted value of 'pNameChange'
//There is no input field with `name`->`value`, so $_POST['value'] is invalid.
$pName = isset($_POST['pNameChange']) ? $_POST['pNameChange'] : '';
And if you need this value across multiple pages, global will not work, use sessions.
ok this "additional" answer is to focus on session only. use the codes for client-end from my previous answer and try this on server-end.
index.php Page:
<?php
session_start();
$pName = isset($_SESSION['pNameChange']) ? $_SESSION['pNameChange'] : '';
project.php Page:
<?php
session_start();
$newRecord = null;
$pName = isset($_SESSION['pNameChange']) ? $_SESSION['pNameChange'] : null;
if(is_null($pName) && isset($_POST['pNameChange'])) {
$_SESSION['pNameChange'] = $_POST['pNameChange'];
$pName = $_POST['pNameChange'];
}
hope it helps

search result not showing in the same window

my search result does not show on the same window, i would want the result to be displayed on the same window. i have found the same question but the code is different from what I'm using so i cant relate to it: Search wont show on same page
scenario 1:
if I put in the action="search_result2.php" - it will redirect the result on the other page
scenario 2:
if i used action="" in this code below, its not doing anything
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script>
$(document).ready(function(){
$("#results").show();
});
</script>
<script type="text/javascript">
$(document).ready(function(){
$("#search").on('click',function() {
var find = $('#find').val();
var field = $('#field').val();
$.post('search_result2.php',{find:find, field:field}, function(data){
$("#results").html(data);
});
return false;
});
});
</script>
</head>
<body>
<div id="container" style="width:auto">
<div id="mainContent">
<h2>Search</h2>
<form name="search" method="post" action="">
Seach for: <input type="text" name="find" id="find" /> in
<Select NAME="field" id="field">
<Option VALUE="testA">A</option>
<Option VALUE="testB">B</option>
<Option VALUE="testC">C</option>
<Option VALUE="testD">D</option>
</Select>
<input type="hidden" name="searching" value="yes" />
<input type="submit" name="search" id="search" value="Search" />
</form>
<div id="results">
</div>
</div>
</div>
</body>
</html>
here is my search_result2.php:
<?php
//This is only displayed if they have submitted the form
if (isset($_POST['searching']) && $_POST['searching'] == "yes")
{
echo "<h2>Results</h2><p>";
//If they did not enter a search term we give them an error
if (empty($_POST['find']))
{
echo "<p>You forgot to enter a search term";
exit;
}
// Otherwise we connect to our Database
mysql_connect("host", "username", "passw") or die(mysql_error());
mysql_select_db("testdb") or die(mysql_error());
// We preform a bit of filtering
$find = strtoupper($_POST['find']);
$find = strip_tags($_POST['find']);
$find = trim ($_POST['find']);
$field = trim ($_POST['field']);
//Now we search for our search term, in the field the user specified
$data = mysql_query("SELECT * FROM testtable WHERE upper($field) LIKE'%$find%'");
//And we display the results
while($result = mysql_fetch_array( $data ))
{
echo $result['testA'];
echo " ";
echo $result['testB'];
echo "<br>";
echo $result['testC'];
echo "<br>";
echo $result['testD'];
echo "<br>";
echo "<br>";
}
//This counts the number or results - and if there wasn't any it gives them a little message explaining that
$anymatches=mysql_num_rows($data);
if ($anymatches == 0)
{
echo "Sorry, but we can not find an entry to match your query<br><br>";
}
//And we remind them what they searched for
echo "<b>Searched For:</b> " .$find;
}
?>
If you want to load in the same page, without refreshing the page, you'll need to make an ajax request.
If you can reload the page, the php part must be in the same "location" as your original link.
For example if you put that code on the top of the same file with the form (and rename it with a .php extension), it should work (if the php can interpret in that folder).

Get form popup upon successful submission

How do I go about getting this form to display "Submitted" using basic javascript popup window upon successful submission?
<!DOCTYPE html>
<html>
<head>
<title>Site :: </title>
<link rel="stylesheet" media="screen" href="css/wicahost.css" />
<link rel="stylesheet" media="screen" href="css/global.css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.js"></script>
<?php require_once('inc/php/clearfieldJs.php'); ?>
<script type="text/javascript">
$(document).ready(function() {
$("#splashtease").RSV({
rules: [
"required,emAdd,Please enter your email address.",
"valid_email,emAdd,Please enter a valid email address.",
]
});
});
</script>
</head>
<body>
<script src="http://www.benjaminkeen.com/software/rsv/jquery/jquery.rsv.js"></script>
<div id="splashTeaserBox">
<h1 class="wicasplashcenter">Signup!</h1>
<div class="wicasplashcenter">Captivating interests and inspiring collaboration.</div>
<form id="splashtease" action="inc/subscribe.php" method="post">
<?php $usrBrowser = $_SERVER['HTTP_USER_AGENT']; $todayDt = date('Y-m-d'); ?>
<input type="text" name="emAdd" class="splashtease" value="Your Email Address ..." onFocus="clearText(this)" />
<input type="hidden" name="brwsr" value="<?php echo $usrBrowser; ?>" style="margin:0; padding:0;" />
<input type="hidden" name="dt" value="<?php echo $todayDt; ?>" style="margin:0; padding:0;" />
<input type="submit" name="submit" value="" class="splashteasesub" />
</form>
</div><!--splashTeaserBox--></body>
</html>
PHP
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="dnbame"; // Database name
$tbl_name="subscriber"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
/* Obliterate bad input */
$goodEmail = mysql_real_escape_string($_POST['emAdd']);
$goodBrowser = mysql_real_escape_string($_POST['brwsr']);
$goodDate = mysql_real_escape_string($_POST['dt']);
$sql= "INSERT INTO subscriber (Email, Browser, DateSubscribed) VALUES('$goodEmail','$goodBrowser','$goodDate')";
$result = mysql_query($sql);
if (!$result) {
die('Invalid Email, please retry.');
}
else{
echo var success;
}
?>
A basic example:
In subscribe.php, change:
else{
echo var success;
}
to:
else {
echo "<html><body onload=\"alert('Submitted');\"><p>Submission successful.</p></body></html>";
}
#user886187's solution will reload the page upon submission and then display a JavaScript pop-up when the page has reloaded.
You might want to submit the form and then display the pop-up without reloading the page. In that case you need to submit the form via Ajax, and then alert "submitted" in the callback function:
function callback() {
alert('submitted');
}
Here's a tutorial on how to submit a form via Ajax:
http://net.tutsplus.com/tutorials/javascript-ajax/submit-a-form-without-page-refresh-using-jquery/
put this code in your subcribe.php
else {
header ('Location: formPage.php?message=Success');
}
and this code inside head of formPage.php
<head>
<?php if ($_GET['message']) {echo '<script type="text/javascript">alert("Form Submited Successfully");</script>';} ?>
</head>

Categories

Resources