Providing Feedback After a Php Header Redirect - php

I have a html table in an application written with javascript (and jquery) and php. The contents of the table are stored in a MySql table.
When I want the user to add some data to the table, they click a button and a jquery ui dialog is shown, with a form for the user to fill out.
When the user fills out the form, they click save, and the form is submitted to a page of pure php, which saves the data to the table and then redirects to the original page with the table on, using
$url = BASE_URL . '/admin/pages/finance/pricing/pricing_schedule.php';
header('Location: '.$url); //Redirect to the right page
exit();
I am doing this because I don't want the message:
Confirm Form Resubmission - The page that you're looking for used information that you entered. Returning to the page might cause any action you took to be repeated. Do you want to continue?
to show should the user hit refresh for whatever reason.
However, because of the way I am doing this, I am struggling to provide a way to give feedback to the user should the save be unsuccessful.
When the user hits save in the jquery ui dialog box, the box is close when the form is submitted, so I can't provide feedback there because the error hasn't occurred yet.
When we are in the php page, as soon as we redirect back to the original page with the table on, any errors picked up are lost.
Can anyone offer any suggestions?

you could store any errors in the $_SESSION variable and print them out on the redirected page.

How about a simple GET parameter?
Something on the lines of:
header('Location: ' . $url . '?success=false&reason=blah');
And on that page at $url, you would first look for the value of $_GET['success']. If it is not "success", echo out additional HTML saying its not successful.
if ($_GET['success'] == "true") {
echo "<p>SUCCESS!</p>";
..
} else {
echo "<p>FAILED!</p>";
..
}

another idea is the transport of the message via the hash in the url:
if (isset($_POST['submit'])) {
...
header("Location: ".$_SERVER["REQUEST_URI"]."#".urlencode($msg));
...
}

Consider submitting your form through AJAX to avoid the page refresh.
Check out this tutorial: http://net.tutsplus.com/tutorials/javascript-ajax/submit-a-form-without-page-refresh-using-jquery/
Solution(Not Tested)
jQuery Code:
var form_data = $('#save_period_form').serialize(); alert(form_data);
$.ajax({
type: "POST",
url: "period_submit.php",
data: form_data,
dataType: 'html',
success: function(returninfo) {
if(returninfo=='1'){
alert('finish');
//will redirect to pricing schedule page after the user has pressed 'ok' on the alert popup.
window.location.assign('/admin/pages/finance/pricing/pricing_schedule.php');
} else {
alert('error occured');
}
}
});
PHP Code:
//Commented header redirection code because it's being done in the javascript code now.
//$url = BASE_URL . '/admin/pages/finance/pricing/pricing_schedule.php';
//header('Location: '.$url); //Redirect to the right page
//Assuming your save has been successful, we echo value '1'. Else echo something else..
echo '1';
exit();

Related

Losing session after a javascript redirect

I have a html file basically calls a php file via ajax and if a login is successful, redirects the user to the index.php page via a redirect (window.location... etc.)
When the index.php loads it checks to see if a session variable is set and if not - redirects the user back to the login page. The problem is that even though the login is a success and the session variable has been set, it is no longer set when the index.php file is loaded. Please see image for overview of process.
The problem is that even though the login is successful and the $_SESSION variable was successfully set, after the javascript redirect the session is reported as being not set.
I do include the session_start() directive in both php files. Any advice would be much appreciated.
Sorry for not including code - here is the code I am using 1st - the ajax request and redirect from html page
function loginCompany(){
let email = 'test#test.com';
let pass ='124';
if ((email =='') || (pass==''))
{
alert('Please enter a user name or email and password');
$('#email').focus();
return;
}
$.ajax({
url: 'compAuth.php',
type: "POST",
async:true,
dataType: 'json',
data: {
email:email,
pass: pass,
userName : email
},
success: function (res) {
if (res){
if (res.status == 'Success')
{
window.location.replace('index.php');
return;
}
else {
console.log('not success : ');
if (res.status == 'Error') {
alert(res.description);
}
}
}
},// Success
error: function (res) {
}
});
}
Next is a snippet from Page B (the php script that sets the session and returns json results
$response = [ 'status' => 'Success'];
session_start();
$_SESSION['dbname'] = $row['dbname'];
echo json_encode($response);
And lastly - Page C which is called after a redirect from the initial HTML page (page A)
session_start();
if (!isset($_SESSION['dbname'])) {
header("location: login.php");
So its this last page (page C the index,php file) that does not see the $_SESSION variable as being set
Many thanks..
Paul.
P.S Also just to say that there is no cross-domain traffic - its all on the same domain :) Thanks.
After a couple of hours of destructive testing, it seems that the problem was with one of my required php files. It seems there was an error in one of the files but instead of generating an error - it just stopped the session variable from being set. Does not seem logical but at this point - I am just happy its working. I am new to this and assumed I was just "getting it wrong". Sorry for wasting peoples time and thanks for the feedback.
Paul.

Handling redirection when session timeout via ajax

I have a view function which only logged in user can see. When clicking the view button, it will send an ajax request to PHP function and return back the result which then be displayed in the html. The issue is, if the user idle for too long, when they suddenly come and click the view button again, the display (where the ajax response supposed to be displayed) will show the login page instead of the requested data.
It was because the PHP session has expired. I want to prompt an alert to tell them about this timeout session and redirect them to the login page instead but I don't know how to do that cause I tried to console.log() the PHP session and it's still showing all of the session. I am convinced that this is something like a memory or a flash cache (not very sure).
QuickView = (pc_no) =>{
$.ajax({
type: 'get',
url: '<?= $ajax_url; ?>view-receipt/'+pc_no,
data: { pc_no:pc_no },
success: function(res){
console.log(<?= json_encode($this->session->userLogged); ?>)
<?php if($this->session->userLogged){ ?>
$('#receipt-inline-view').html(res);
<?php } else { ?>
if(alert('Your session has expired. Please re-login.')){
window.location.href = '<?= base_url(); ?>';
}
<?php } ?>
}
})
}
Based on the code above, the user session will be stored in $this->session->userLogged. After PHP timeout, it should be cleared. But from console at ajax there, it's still showing the session even after it gets cleared up. Hence, the redirection also cannot be triggered.

Index page refresh when logged-in

I have an index.php page, which behaves as follows :
if a session var exists and is set, it displays a menu + some info
about the user (userID, IP adress, link to disconnect)
if the session var is not set, it displays a login form
So if you go there for the first time, you'll see the login form.
When the user provides his login+password, there is an AJAX call to login_check.php. The main purpose of this page is to generate a session variable (if the user info meets several requirements), but it also sends error messages back to the bottom of the form (under the form of JSON var) in case of authentification failure.
Here is its core :
login_check.php
if (authentification($login, $password)) {
//creates the session variable
$_SESSION['auth'] = $login;
//? here I'd like to refresh the index page
}
else {
//the error that will be displayed at the bottom of the form
$json_err .= "Incorrect login or password";
}
index.php looks like this :
if (isset($_SESSION['auth'])) {
//the menu is displayed, because the user is looged-in
}
else {
//the login form is displayed, because the user is not authentificated
}
So far, I have to manually refresh the index page so that it takes the session var into account. Is there a way to do it automatically ?
Solutions like "location.reload" are not really suitable, because of the error messages that might be displayed. I also tried to call again index.php from login_check.php using "include" or "header" but it didn't work.
Should I make a conditional refresh within my jQuery function, depending on what data was sent back by login_check.php ?
What would you advice ?
Thanks
I think you need to eun your checklogged.php for example once every 5 min and if user if not logged redirect to login page.
<script type="text/javascript">
$(function() {
getStatus();
});
function getStatus() {
$status = $('#islogged').load('login_check.php');
setTimeout("getStatus()",50000);
}
</script>

PHP+AJAX (jQuery) - Reading session data on $.post() return

I am currently writing an "Edit Account" module. Using jQuery.post(); I can successfully update my database, and I can write to the session variables from the PHP script - however,
when trying to access the Session variable that I just wrote to, the data does not seem to have been updated.
I write to the session like this: $_SESSION['email'] = 'john#doe.com'; in my Ajax.php
My jQuery (minified) callback on success:
$.post(...,function(res)
{
if(res=='success')
{
// Alert the new E-Mail, read from the Session!
alert("<?php echo $_SESSION['email']; ?>");
}
}
However, the alert does not output john#doe.com, it outputs whatever the E-Mail was it was when the entire page was loaded. When I refresh the page, the session data has been properly updated.
I do have session_start(); on both index.php (my site) and in Ajax.php
If you need more info please do let me know. :)
First of all it should be
alert("<?php echo $_SESSION['email']; ?>");
and secondly $.post is dynamic but <?php echo $_SESSION['email']; ?> is static. It renders once, on load, not everytime you make an .post() so if
$_SESSION['email'] = 'blah'; by the time the page is loaded, the alert will always be alert("blah"); , until you reload the page.
If you want to alert the new session variable you have to make a new ajax request to a php file (ie. return_session.php?key=email ), that will return the new session variable
Thats because the alert string is generated when the page is loaded. And when you make an ajax request it still doesnt change, because its not refreshed.
On ajax success you should output the responseText and then it will work.

redirecting an ajax processing page

I have a page that checks to see if the user logged in and if the user is not, uses an jQuery ajax call to a php processing page to get the information. But to get the information it has to redirect out to the 'login site' which sits on a different server, and the 'login site' then POSTs back the login information to the php page, and the php page turns the raw data into something the first page can understand.
Well at least that's what's suppose to happen.
What actually happens is that once the php processing page redirects I get a 302 error. I've tried going to the php page without the ajax call to it and it works fine, redirecting to the 'login site' and accepting the post back.
I can't remove the ajax call and just code the bounce into the first page because the page is html, unfortunately it has to stay that way, and html pages don't like POSTs to them and crash.
Below is the code with the ajax call...
if (Login == null) {
$.get("some_php_page.php", { }, function(data) {
if (data == "") {
} else {
//set login cookie;
}
});
}
Below is the php processing page...
if ($RefererServer != LoginServer) {
header( "Location: LoginServer/verify.php");
} else {
// send login information back
}
Anyone have any idea?
On the server side, you should return a json:
{ "success: false, "redirect": http://redirecturl.com }
On the client side, redirect is made by js
$.ajax({
// ....
success: function(response){
window.location = response.redirect;
}
});

Categories