AJAX request redirection - php

I apologize for my bad english :)
I'm doing php file with ajax request. json response comes in the format of. but in some cases can be redirect. In this case I want the redirect of the page.
Could you please help me. Thank's.
Example PHP File :
<?php
$status = $_POST['status'];
if($status == 'a'){
// return json response
}else{
echo "<form action='http://www.url.com'>..</form><script type='text/javascript'>form.submit();</script>";
}
?>
Example JS File :
$.ajax({
type: "POST",
url: 'http://www.my_php_file.com'
});

You can issue the redirect in the usual way, by returning a 3xx response with a Location header. The browser will follow the redirect (it doesn't make the JavaScript code doing the ajax call handle it).
So for instance, if you want to issue a 301 ("permanent moved"):
header('Location: http://www.google.com',true,301);
exit;
(I didn't know the specifics of how to issue the 3xx in PHP, but found them in this answer).
Side note: I doubt www.google.com is going to work, I assume that was just an example.

Use window.location = "http://www.yoururl.com"; to issue a redirect via JS.

In your php file replace php redirection with javascript redirection like this:
<script type="text/javascript">
window.location.replace("http://www.google.com");
</script>

Related

Javascript page redirect from Ajax script

Due to some unforeseen reason, I cannot use a *.php extension for my page. And I need to put conditional redirection in the page.
I plan to use *.html, and javascript/Ajax to call a PHP which evaluates the condition
and accordingly sends back a redirection command.
The condition is being evaluated, but how can I give a redirection command from this internal PHP is not clear to me.
You can actually map all your .html files to .php using .htaccess.
If that doesn't work for you, your logic should be as follows:
PHP:
echo json_encode(array("redirect_url" => $url));
Javascript with jQuery (assuming you require AJAX to redirect):
$.getJSON("PHP/Controller/Url", function(data) {
window.location.href = data.redirect_url;
});
Javascript (if you simply serve a static html file)
<script>
window.location.href = "redirect_url";
</script>
You can use
window.location = "http://new-url"
or
window.location.href = "http://new-url"
In JS,
location.assign("http://www.google.com")
will redirect your current frame to Google.
So don't send redirect header in PHP, send "flags" in response body and use JS to redirect.

Obtain actual browser URL in PHP

I need to retrieve the actual URL that the user see's in their browser. I have an Ajax request running at page load. Hence, the regular $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"] expression returns the request URL of the Ajax request instead of the actual URL in the browser.
Any idea how to get this?
You could pass it up from javascript in your ajax request, using window.location.href.
Also, it's likely that $_SERVER['HTTP_REFERER'] will contain the browser's current location.
You could also try using $_SERVER['HTTP_REFERER'];. This might work, not 100% sure though.
You can't do that with server-side code, as there is no server-side variable that refers to what the client sees. The only thing you CAN see (and then again, it depends on the browser the user's using, some don't pass this info) is the HTTP_REFERRER variable. This however, is only set when a page calls another, not when users first access your site.
See this for more details.
A possible solution however, might be to use javascript function to send the browser's top URL to the server using an AJAX query, and to fire it client-side whenever a user loads the pages) you want to get this info for.
Edit: Damn, too slow, already answered!
Pass a hidden input that has the browser value set with your ajax request. Unless someone is being malicious, it should suffice.
If you do an Ajax-request, you could pass the address available through Javascripts window.location.href variable as a POST-variable with the request.
With jQuery it would be something like:
$.ajax({
url: 'your-url.php',
type: "POST",
data: { url: window.location.href },
success: function (data) {
// Do something on success
}
});
With such a request you could access the URL on the server-side with a simple:
<?php
$url = $_POST["url"];
?>
Actual Website Link in php
<?php
echo $actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
?>
Server-side languages can't see what happens after they've rendered and outputted the page.

jQuery to post to php file

I have an index.html file which I want to run some jQuery when it is loaded. Essentially, I want to check to see if a user is already logged in based on some session variables.
So index.html will contain some jQuery which uses $(document).ready(function(){ });
In this function I want to just fire autheticate.php which checks to see if $_SESSION['user'] is set, if it is then it will redirect to home page otherwise it will redirect to login page...
how can I post in jQuery without having a html form? I just want to post to a url...
EDIT:
Based on #jondavidjohn's answer I changed my web app so that it uses index.php to check sessions:
<?php
session_start();
if(isset($_SESSION['username'])){
//go to home page
header('Location: ...home.html');
}else{
//go to login page
header('Location: ...login.html');
}
?>
It is surely possible doing this with javascript, but it is not secure at all...
You need to be checking at the server level for $_SESSION['user'] before you even send the content to the browser...
My answer would be to do the checking / redirecting with PHP before anything gets sent to the browser, it will be less complicated and more secure...
The reason a javascript solution is insecure is that you are relying on a technology that resides and is controlled by the client to control access to protected areas.
You can use $.post(url, params), where url is a string and params is a hash with your post data.
$.post("/authenticate.php",null,function(data){
// do something based on response returned
if($data){alert("authenticated");}
else
alert("not authenticated");
});
in your php file
if(isset($_SESSION['user']))
{
echo true;
}
else
return false;
Use $.post() to post data via AJAX to a page. Doing it this way won't allow the PHP script to redirect the user, you'll have to java JavaScript redirect them.
$.post('/path/to/page.php', {userID: 5}, function(data){
// Use window.location to redirect
});
Or, you can create a "fake" <form> element, and post that.
var $form = $('<form/>').attr({
method: 'post',
action: '/path/to/page.php'
});
var $input = $('<input/>').attr({
name: 'userID',
type: 'text'
}).val('5');
$input.appendTo($form);
$form.submit();
I suggest you take #jondavidjohn's advice, and have PHP redirect the user before the page is sent to the browser. That's much more secure.
Why bother with the AJAX request? Since you're building the page with PHP, just have PHP embed some variables in a JavaScript block:
<script type="text/javascript">
var is_logged_in = <?php echo $_SESSION['logged_in'] ? 'true' : 'false' ?>;
</script>
This'd save you an HTTP round-trip to retrieve data you already had available.

PHP- Ajax and Redirect

i have a jquery Ajax request happening on a page. On php side i am checking if the session is active and doing something. If the session is not active i want to redirect the user to another page in php(header redirect). how do i do it.
I know how to achieve it in javascript(i.e if session_fail then change window.location but is there something that i can do in php/cakephp
Redirects only say "The data you requested can be found here".
HTTP provides no way to say "Even though you requested a resource to go inside a page, you should should leave that page and go somewhere else".
You need to return a response that your JavaScript understands to mean "Go to a different location" and process it in your own code.
If I understand what you want to happen then this is how I'm implementing it. It's in Prototype instead of jQuery but it shouldn't take you long to translate:
new Ajax.Request('process.php', {
on401: function(response) {
var redirect = response.getHeader('Location');
document.location = redirect;
}
});
In your PHP, output the following if the session is inactive:
header('Location: http://example.com/login.php', true, 401);
exit;
This is what you would want in your php IF THIS WERE A REGULAR REQUEST, NOT AN AJAX
if (isset($_SESSION)) doSomething();
else header("Location: otherUrl");
Since this is an Ajax call, you are not passing control to the php, but just trying to get a response that (likely) fills a particular section of your page. You do not mention what jQuery ajax function you use, but it matters. I would imagine you are using either $.get() or $(element).load() ??
Without knowing the particulars, this is my best suggestion for you.
Ajax call: $.get(url, callbackFunc);
php:
if(isset($_SESSION)) echoSomething() else echo("redirect");
callbackFunc:
function(data)
{ if (data == "redirect") window.location = otherUrl;
else
$("#desiredElement").html(data);
}

Form that makes browser redirect when accessed by either a regular form submit or an Ajax request - is this possible?

I have a web page with a form. When the user submits the form, I want the server to make the browser redirect to a different page from the form action. Right now, I am doing this by using PHP's header function to send a 302 status code. It works fine.
I am trying to make the page on the server redirect the browser in the same way, regardless of whether it was submitted normally (without Javascript) or via Ajax. I tried to do this by setting the window location to whatever URL is in the Location header. I am using jQuery, and doing a call like this:
$.ajax({
url: this.action,
type: "POST",
data: getFormData(this),
complete: function(request) {
window.location.assign(request.getResponseHeader("Location"));
}
});
However, that didn't work. After thinking about it, I realized that this is not very surprising. In an Ajax request, the browser is supposed to transparently handle redirect responses such as 302 codes before changing the readyState. When the complete function runs, it is looking for the Location header in the final destination and not finding it.
As an experiment, I then tried sending a 200 status code with a Location header. I tried the Ajax request and it worked fine. However, when I did the non-Ajax submit, it didn't work. The browser went to the form action page and stayed there, like it was ignoring the Location header.
Is there any way to make the same page redirect in both cases, without the server having to know or care whether the request is an Ajax request?
In case this matters, I tried the form in various browsers (IE8, IE7, IE6, Firefox 3.5, Chrome) with similar results each time. Also, I am doing a post request to avoid bumping into IE's 2083-character URL length limit.
HTTP 302 response are consumed silently by XmlHttpRequest implementations (e.g. jQuery's ajax function). It's a feature.
The way I've solved this in the past is to detect for XmlHttpRequests and issue a "Content-Location" header (rather than a "Location" header). The most cross-library way of doing this is to check for the "X-Requested-With" http header in your server-side code (jQuery, Prototype, Mootools among others set this):
if (#$_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
header('Content-Location: ' . $redirect_url);
} else {
header('Location: ' . $redirect_url);
}
You still need to special-case your client-side code:
$.ajax({
// ...
complete: function(xhr) {
var redirect_url = xhr.getResponseHeader("Content-Location");
if (redirect_url) {
window.location = redirect_url;
}
}
})
If the user is getting redirected regardless, why the Ajax? The whole point of Ajax like this is to make changes to the page without a page refresh, so the technique you're using seems a little like building a printer that outputs into a shredder hopper.
I'd like to know more about your use-case for this. From what I understand your trying to get your application to load a page based on the 'Location' header of an Ajax call within it? I'd ask why?
An HTTP header doesn't seem to be the right place to get that information from. Isn't your application essentially making a query that says "Where shall I redirect to?". There's no reason the Ajax response actually has to respond with a 302 and a 'Location' header. Why not just have it respond with JSON or XML which contains the new URL?
Edit: Just re-read your penultimate paragraph. I'm not sure there's a good way of achieving what you want. The concept sounds broken to me. :)
Pass additional parameter to your ajax request for easy identify type of request. When ajax - do not redirect - just send target url, then redirect client side in ajax callback via location.href
like this:
$.post('/controller/action', {formdata}, function (redirect_to) {
location.href = redirect_to;
});
Will "complete" work:
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
complete: complete(xhr, status) {
window.location.assign(xhr.getResponseHeader("Location"));
}
});
Did you try using the error function instead of complete?
$.ajax({
url: this.action,
type: "POST",
data: getFormData(this),
error: function(request) {
if(request.status == 302)
window.location.assign(request.getResponseHeader("Location"));
}
});
jQuery sends any 3xx response to the error function. Maybe the 'Location' header will still be available at this stage.
Why not have your "ajax action" simply fill in the needed form fields and submit the form instead? This way you'll get exactly the same behavior as when submitting by hand.
Here is another option although you will need to do some cross browser tests:
complete: function(request) {
if(request.status == 200) {
var doc = document.open(request.getResponseHeader('Content-Type'));
doc.write(request.responseText);
doc.close();
}
}
Major drawbacks: URL in address bar doesn't change; could mess with back button/history
Although I think #crescentfresh's idea is the way to go

Categories