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;
}
});
Related
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.
On each page I check if the user is connected (i.e.: if the user session is active or not).
validateSession();
function validateSession() {
if (!isset($_SESSION['CurrentLogged_USR_Id'])) {
header("Location: 'http://example.com');
}
}
It's working.
But if the user is on a page from a long time and the system needs to make an ajax call, the same check is done but do not redirect the user.
Why ?
I've include the validateSession() on my php page called by ajax but the redirection is not make.
Thanks.
You cannot redirect in PHP that is called through AJAX. Rather return a flag that identifies that session has expired and make redirection in JavaScript.
Below is sample code snippet.
$.ajax({
url: "urlToAJAX.php",
success: function(isSessionExpired){
if(isSessionExpired)
{
window.location = "http://example.com";
}
}});
You can follow this code.
Ajax
$.ajax({
url:..
type:..
success(data){
if(data == "SESSION_EXPIRED"){
window.location = "your-login-page";
}
}
});
In your PHP code, you have check if the session is available. If not echo the string SESSION_EXPIRED.
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();
I'm using codeigniter for my web application which is having user registration feature. And also i am using ajax in most of the places for loading the page. The problem is, if some function is called through ajax to load a page and if session does not exists, it is not redirecting to the login page. But it is working when we visits the same URL through browser(It is redirecting to the login page). What should i do to resolve this problem?
This is the code for checking session we are using.
$userid=$this->phpsession->get('userid');
if(!($userid))
{
redirect('home','refresh');
}
In your controller detect if it is an ajax request:
if($this->input->is_ajax_request())
{
$userid=$this->phpsession->get('userid');
if(!($this->usermodel->is_user($userid)))
{
echo "1";
}
}
In ajax detect the response and redirect to the login page:
$.post('index.php/login', function(data){
if(data == "1")
{
document.location.href = <?php echo site_url("home"); ?>;
}
});
In my javascript I have some ajax requests $.getJSON({...}) for various actions. I have a php app that handles these ajax requests. Before processing the actual request, my app first checks the session and in the case the user hasn't logged in yet, it sends a refresh signal back. Something like:
if (not logged in) {
header('Refresh: 0;');
}
else {
//process request
}
But the client doesn't actually refresh. Is there something I'm missing when it comes to AJAX requests and the http refresh header?
AJAX requests don't affect the browser until told to do so. Meaning, if i fetch a page using AJAX, it gets returned, maybe stored in a variable and that's it. It does not do anything after that. You need to parse the return data and act accordingly.
In your case, you might rather return something like JSON, have the client side parse what the return data meant, and act accordingly.
i tend to do something like:
{
"directives": {
//contains directives what to do first before parsing the data
"whatToDo" : "redirect"
},
"payload" : {
//actual page data
}
}
So the file your calling in your request contains the header('Refresh: 0;'); ? Because that has no effect at all, what i would do is if the user is not logged in return an unique string like so:
if (not logged in) {
echo "NOTLOGGEDIN";
}
else {
//process request
}
and then in your AJAX request check if they are logged in:
$.get("someURL", function(data) {
if(data == "NOTLOGGEDIN"){
//Do something
} else{
//Display data
}
});