PHP Javascript - keep localStorage on PHP session_destroy - javascript

I have a strange (for me) behavior about use of PHP session_destroy(), used for logout, and JS localStorage used for avoid continuous DB ajax request.
So. My current (and working) scenario:
At login form, PHP do a session_start() -> browser writes cookies with PHPSESSID (no localStorage at moment);
After logon, IF localStorage.getItem('myDataItem') === null, data are requested once (ajax) and written with localStorage.setItem('myDataItem', 'Hi, I'm your ajax response'). If localStorage.getItem('myDataItem') !== null do noting;
Code:
if(localStorage.getItem('myDataItem') === null){
$.ajax({
url: 'ajax.php',
type:'post',
data:{request: 'dbInfo'}
}).done(function(jsonObjectResponse){
localStorage.setItem('myDataItem', JSON.stringify(jsonObjectResponse))
});
}
On logout click element, browser runs a function with an ajax request that do a PHP's session_destroy() and do a JS location.reload()
and restart from the login form;
Code:
$("#logout_element").on('click', function(){
$.ajax({
url: 'ajax.php',
type:'post',
data:{request: 'logout'} /*ajax PHP do a session_destroy()*/
})
.done(function(){
location.reload();
});
});
So far, everything (F5/refresh) is regular, if it were not for the logout/session_destroy (), the localStorage disappears
My Goal
keep localStorage even after the session_destroy ()
Best,
Oscar

Related

PHP header("Location:index.html") nor javascript in php not working

I am making a logout button which calls a PHP script via an AJAX call but somehow my php is not redirecting. Also when I try to use javascript it doesnt work either.
I tried the following things:
Adding ob_start() and ob_end_flush()
Changing exit; to exit();
Changing header("Location: http://localhost/page_login.html)
to echo("<script>location.href = http://localhost/page_login.html';</script>");
When I open the php script directly in my URL (by just typing it in) it redirects me to the page.login.html however from the ajax call its not. When I print the data it prints the page_login.html file which also excludes the option that its not in the correct map.
Anyone any ideas on how to fix this?
HTML
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<div id="logout_button">
Logout
</div>
<script src="jquery-3.2.1.js"></script>
<script src="logout.js" type="text/javascript"></script>
</body></html>
JAVASCRIPT (logout.js)
$('#logout_button').click(function(){
$.ajax({
type: 'POST',
url: 'logout.php',
error: function(response) { console.log(JSON.stringify(response))},
success: function(data){
console.log(data);
}
});
})
PHP (logout.php)
<?php
header('Location: http://localhost/page_home.html');
exit;
?>
You have a misunderstanding of how AJAX is working in this situation. When you're performing an AJAX call, a separate request is being sent as your POST to the given URL. This does not inherently affect the original page you are on in the client window. Essentially, what is happening is:
A user clicks 'logout'
The server (i.e. not the client's web browser) is sending a request to your logout.php
logout.php runs its code and returns a response to your original page (success/fail in this case; or some data if you had a return in your PHP page)
The AJAX here is only a means of sharing information between the two pages, not to run them in succession. What you need to do is redirect the original page, and you can do this with JavaScript! After all, don't forget that JavaScript is our client-side language, with PHP being the server-side one.
There are any number of ways to redirect in JavaScript which you can find. For example, you may use window.location.href in this case:
$('#logout_button').click(function(){
$.ajax({
type: 'POST',
url: 'logout.php',
error: function(response) { console.log(JSON.stringify(response))},
success: function(data){
window.location.href = "http://localhost/page_home.html";
console.log(data);
}
});
});
Use location.href in Javascript inside ajax to redirect or reload, not in .php file
$('#logout_button').click(function(){
$.ajax({
type: 'POST',
url: 'logout.php',
dataType: "json",
error: function(response) { console.log(JSON.stringify(response))},
success: function(data){
location.href = "/page_home.html";
//console.log(data);
}
});
});
Also send response data from .php to logout/session destroy, like
<?php
// Code here to logout or session destroy
// return json or string
$response["success"] = true;
echo json_encode($response);
?>
When you call directly your php file, header('Location: http://localhost/page_home.html'); add Location field to the HTTP Header that tell the browser to redirect the user to the specified location.
If you call it via ajax, jQuery doesn't care about this header field.
What you need is :
$('#logout_button').click(function(){
//Insert your ajax call here if you need to do something server side like destroy the session
window.location.replace('http://localhost/page_home.html');
})
EDIT: As mentionned in the comments, it will be simpler to use a link to your logout.php with the header('Location: http://localhost/page_home.html'); in it.

Return variable from PHP after AJAX Post

I've read countless examples but I just can't get the following to work. I want to submit a form, process it on the server side then decide which php script to load into a div (dynamic loading I can do).
The head:
$.ajax({
type: "POST",
url: url, // passed with onclick
data: $("#" + formName).serialize(),
success: function(data) {
// Some JSON? to go here to store variable returned from PHP ($thisVariable)
}
});
return false; // avoid to execute the actual submit of the form.
The php:
// Process the request (add to database e.g.)
$thisVariable back to ajax

Ajax Login With PHP Issue

I am creating A login system using AJAX,PHP & SQL obviously.
Anyway I am trying to implement A real time login feature so it will log the user in without refreshing the page.
I have done that almost but the only issue when the user clicks remember me that uses cookies instead of sessions but the JQuery isn't proccessing that?
I want it to detect depending if it was checked ether remember the user or not it only starts a session, when it does register a cookie the logout page is not deleting the cookie which he did before i added the jquery code in so nothing on the php end and I am mainly A PHP Developer and still learning.
(I cannot post the server side code for privacy reasons as I be using this in A project
but it looks similar to any other normal php login script)
Here's the JQuery
function validLogin(){
var user_login=$('#user_login').val();
var user_pass=$('#user_pass').val();
var remember_me=$('#remember_me');
var dataString = 'user_login='+ user_login + '&user_pass='+ user_pass;
$("#flash").show();
$("#flash").fadeIn(100).html('Loading..');
$.ajax({
type: "POST",
url: "ajax/procces.php",
data: dataString,
cache: false,
success: function(result){
var result=trim(result);
$("#flash").hide();
if(result=='correct'){
window.location='index.php';
}else{
$("#errorMessage").html(result);
}
}
});
}
function trim(str){
var str=str.replace(/^\s+|\s+$/,'');
return str;
}
Thanks
You don't pass your variable 'remember me' to your ajax request. For instance :
data: {login: user_login, passwd: user_pass, rememberMe: remember_me}
Another point, be careful you treat information from client-side. Never trust the client. Test all your values in PHP.

Jquery ajax post to php but is saying no value in variable

I am working on an instant search thing and when I submit the form search-form it is going to make an ajax post to PHP. It sends and everything but then the PHP page says that the variable has no value but the data is clearly being posted.
$('#search-form').submit(function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "Search.php",
cache: false,
data: $("#search-form").serialize(),
success: function(data) {
alert($("#search-form").serialize());
$("#searched").fadeIn("fast");
$("#results").empty();
$("#results").append(data);
}
});
return false;
});
Make sure you have a console opened up in your browser, Firefox: bugzilla, Chrome and IE have a built-in. It shows you what is happening in asynchronous requests.
in your php file at the top do this:
var_dump($_POST);
//OR DO THIS:
// print_r($_POST);
Then look at your browser console to see what the response is. It should spit out an array. and you can see what the name of your data is. This is the quickest way to debug any ajax request.
Also, don't forget that you serialized the data with .serialize();

Only allow access to a php action through form submit, but when using an ajax call

i have a form that deletes the comment its in.
To only allow the page that carries out the php action to be viewed when the form is submitted i do a basic
if (isset($_POST['submit-delete'])) {
// carry out delete
}
this works fine, but i am using ajax to not reload the page.
The response is the same as i have used else where:
$(document).ready(function(){
$(".delrepcomment").submit(function(){
$.ajax({
type: "POST",
url: "process/deletecomment.php",
data: $(".delrepcomment").serialize(),
dataType: "json",
success: function(response){
if (response.commentDeleted === true) {
$('#successdisplay').fadeIn(1000),
$('#successdisplay').delay(2500).fadeOut(400);
}
else {
$('.delrepcomment').after('<div class="error">Something went wrong!</div>');
}
}
});
return false;
});
});
This however doesnt work, unless i remove the check to see if the form has been submitted.
Whats the best way around this? I want to keep the check for the form being submitted incase of js being turned off or any direct access attempts.
Thanks.
You should post the data you require for the script to work. In your case, you have to post a key-value-pair with "submit-delete" as the key and an arbitrary value (unless you check that value later in the code).
On the other hand, PHP stores the used HTTP method in $_SERVER['REQUEST_METHOD'], this would be "POST" in your case.

Categories

Resources