How do clients handle JavaScript after they receive the "Location" HTTP header? - javascript

Consider the code:
somepage.php
<?php header('Location: index.php'); ?>
<!DOCTYPE html>
<html>
<head>
<script>
doSomething(); // does the browser run this?
</script>
</head>
</html>
I am trying to put Google Analytics there, but I am not sure if people are actually loading the analytics JS at all.
Does the browser actually look at the output after the Location header has been sent? If so, does it actually run the JavaScript?

Most browsers ignore the response body when a redirect header is sent. So it won't display HTML, and it won't execute Javascript.
If you want to execute something before redirecting, don't use the Location: header. Send a page that executes the Javascript, and then executes
window.location.href = "index.php";

Related

PHP Redirect to different url using header("Location:") does not work

I am quite new to php, I did some research and tried someone else's solution but it did not work out for me. I want to redirect users to another page after a certain code has been executed. I realized that there are no error messages and the site does not change. So I removed almost everything from the code and put it into a small test.php file.
The same issue persists.
<!DOCTYPE html>
<html>
<body>
<h1>Tes2</h1>
<?php
// Execute some code here
sleep(10); // Give the user 10 seconds to read the output of my code
// redirect the user with php or trigger a JS script to do that
header("Window-target: _parent");
header("Location: https://www.w3schools.com/");
?>
</body>
</html>
Expectation: The page should execute the main php script (visualized by the comment) and trigger a timer. When the timer ends, it should redirect me to "www.w3schools.com". There should be no errors or other messages. The redirect should be done by the php code, if possible (JS would be a possible way to solve this, but I would still need to start the JS code after my php code has been executed).
Result: The page shows up and loads the of the html code. The site remains and does not change. There are no errors.
Environment: Running on Chromium
Version 96.0.4664.45 (Offizieller Build) for Linux Mint (64-Bit)
The Website is functional and did execute PHP code as expected, but not this one.
Is there a light weight and universal (for most popular browsers) solution which will redirect the users to another page?
Headers must be set before any data is transmitted, so you can't just stick them in the middle of a file. Quoting the the manual:
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP.
So at the very least you'll need to rewrite your file to:
<?php
header("Window-target: _parent");
header("Location: https://www.w3schools.com/");
?>
<!doctype html>
...
Also, never sleep() in an http(s) response: that response should finish as fast as it can, no matter what content it needs to generate. Sleep has no place in (really any) PHP code.
A combination of PHP and JS seems to be the easiest solution. But that might be only my opinion. I tried to document the code as good as possible, so others can understand it:
<?php
function redirect() { // Create some JS code which will pause for 3 seconds and execute the move function afterwards. This Function will redirect the user
echo "<script>";
echo "function move() {window.location.replace('http://www.w3schools.com');}";
echo "setTimeout(move, 3000);";
echo "</script>";
}
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Test2</h1>
<?php
echo "<p>You will be redirected after the code has been executed!</p>";
// Run actual code
redirect(); // Redirect using JS code
?>
</body>
</html>

Why does this JQuery.get example from w3schools not work for me?

This is going to be downright obvious to someone else, but for the life of me, I cannot figure it out.
I've copied the HTML from http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_ajax_get
I changed one line slightly so that .get url points to the full w3schools.com url (this works just fine on their example page). This is the code:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.get("http://www.w3schools.com/jquery/demo_test.asp",function(data,status){
alert("Data: " + data + "\nStatus: " + status);
});
});
});
</script>
</head>
<body>
<button>Send an HTTP GET request to a page and get the result back</button>
</body>
</html>
This code works just fine for me on the w3schools website, but when I paste it into a new file called "hi.html" on my home computer and open it up in Chrome and Firefox, it fails.
I'm copying and pasting this html directly, why does this fail?
Your web browser prevents the Ajax request from executing because of the same-origin policy (https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy). Basically, when you run the script on localhost:80, you can only make Ajax requests to pages on localhost:80. W3Schools is on a different host.
The same-origin policy exists for security reasons. For example, suppose you are logged into Facebook. If the same-origin policy didn't exist, a programmer could make a malicious website that makes an Ajax request for Facebook.com and it would return with your login cookies. It could then send your login cookie to the malicious programmer. The malicious programmer could then take your login cookies and impersonate you on Facebook.

Chrome - Unable to read sessions for cross domain requests

First I'm apologizing if the title of my question is not correct or not clear. But I will explain my issue below.
Lets say I have a web application called mywebapp.com and i have a page loadjs.php. Here, I have some JS code and the content time of the file is application/javascript.
loadjs.php (mywebapp.com)
header("content-type: application/javascript")
echo "alert('some message here');";
I will use the above file in a page (index.html) of another web app as a javascript source. let's say that it is anotherwebapp.com.
index.html (anotherwebapp.com)
<html>
<head>
<script type="text/javascript" src="//mywebapp.com/loadjs.php"></script>
</head>
<body>
Some contenct here..
</body>
</html>
When this runs, there should be javascript alert as I wrote in loadjs.php (mywebapp.com).
Note:
The above is working without any issue.
My Issue:
Lets assume now I want to display this alret only for the logged in users for mywebapp.com. That means, when a user who has logged in already in mywebapp.com will see an alert when they visit anotherwebapp.com in the same browser.
So my loadjs.php file will be as below.
header("content-type: application/javascript")
if(isset($_SESSION['logged_in']) && $_SESSION['logged_in']==true)
echo "alert('some message here');";
Let's assume that $_SESSION['logged_in'] has been already set after the user login.
It was working properly in Firefox and and IE. But..
Chrome browser was not working properly.
So the reason is, chrome cannot read the session value as other browsers do.
Is there any special reason for this and is there any way to overcome this?
(Please note that the above coding sample is just an example to explain my issue.)
Looking forward to hear from you.
Session is handled server-side, so this is not a Chrome problem.
It could be a caching problem: the js file is first loaded without the alert (because the user is not logged in) but when the user logs in the js is loaded from cache and not downloaded again causing the alert to not display.
Chrome has a pretty "aggressive" caching policy, had some troubles like this before.
You should try to add a timestamp or some kind of dummy value like so that on every page reload you force the javascript file to be downloaded again
<head>
<script type="text/javascript" src="//mywebapp.com/loadjs.php?dummy=
<? echo time() ?>"></script>
</head>
I haven't been using php for quite some time so this might not work but you should get the idea
This is an interesting issue. I do not have an environment to test this right now, but the first thing I would like to do is to print the $_SESSION['logged_in'] while making a request using FF, then Chrome. If for Chrome the value is false, you have to debug why. It could be a crossdomain policy issue.
You can take a look at this: https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS
Maybe you need to send this header from mywebapp.com:
Access-Control-Allow-Origin: http://anotherwebapp.com
Please also share if the js console of Chrome shows any error.
Update: the issue was due to chrome browser cookie settings dialed in to be restrictive. Go to chrome://settings/content and make sure Block third-party cookies and site data is not checked.
I had a similar issue.
The reason for your problem is:
The session ID is sent as a cookie, and since your request is cross-domain, it's considered a third party cookie by the browser. Several browsers will block third-party cookies.
The solution to your problem is
Generate the session ID on the client (in the browser), use Javascript sessionStorage to store the session ID then send the session ID with each request to the server.
Details in this article (related to XMLHttpRequest, but your issue is essentially the same): Javascript Cross-Domain Request With Session

How to change content of website loaded in iframe?

I need to change content of website using jQuery loaded in iframe from other domain such this:
<html>
<head>
</head>
<body>
<iframe src="site.com/somepage.html></iframe>
<script>
$('iframe').find('div#message').value('hello');
</script>
</body>
</html>
Also I added target link to whitelist.
Could any helps? Thanks.
If you want to get a website of different domain you have to use parser in your server side which will parse the html from the website and then echo the parsed html to your client side
Due to cross-site attack/mocking securities, for a long time this is no more possible in the mainframe browsers (Chrome, IE, Fire) with domains diferent of your own.
You could achieve that thru proxying, by proxying I mean, using a server side solution where you get the HTML generated by "site.com" and outputs it as was in your domain.
Your script is running during runtime so it will not find the DOM of the iframe and will break. What you can do is create a function on your parent page like:
//On Your Parent page
function modifyIframeContent() {
$('iframe').find('div#message').value('hello');
}
Then call this function from the iframe after it loads.
// On Your Iframe page
window.onload = function() {
parent.modifyIframeContent();
}
Of course: Your iframe must be of same domain for this work.

jQuery: Can't run $.get (http get) on Chrome

I want to use JavaScript to make a simple http get.
I used jQuery to perform my request. My code runs on IE8.0 but not in Chrome (ver 6.0).
My page has the following code: (to simplify, i made a simple request to a html page, but my needs is other)
<!DOCTYPE html PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html>
<script type"text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<SCRIPT TYPE="text/javascript" >
function sendGet(){
$.get(
"http://www.google.pt",
function(data) {
alert('page content: ' + data);
});
}
</SCRIPT>
<head>
<title> Http Get Demonstration </title>
</head>
<body>
<p/>
<input type="button" value="Http Get" onclick="sendGet();" />
</body>
</html>
As i said, when i load this page on IE and press the button, i get the alert with the html code. But in Chrome the alert appears with empty text (null?). In Chrome Console from "Developer tools" i get the message: "XMLHttpRequest cannot load http://www.google.pt/. Origin null is not allowed by Access-Control-Allow-Origin."
Anyone can explain me what's the meaning of this message? And what i should change to my page run in Chrome?
Thanks
Due to same origin policy you cannot send AJAX requests to different domains than the one hosting your page. So unless your page is hosted on http://google.pt you cannot send an AJAX request to this domain. One possible workaround is to setup a server side script on your domain which will act as bridge between google.pt and the client or use JSONP if the distant domain supports it.
Although i can't remember if i changed any IE option, the Darin Dimitrov seems explain my problem.
I found some tricks can be used (beyond the Dimitrov answer):
use a PHP script:
http://jquery-howto.blogspot.com/2009/04/cross-domain-ajax-querying-with-jquery.html
configure IE by editing regedit (not recomended):
http://msdn.microsoft.com/en-us/library/dd565656(VS.85).aspx
(I belive there's some other way to disable cross domain protection without editing regedit. But i couldn't find it)
Are you opening the html file directly from a file (e.g. does the address bar say file://usr/path/to/the/file)?
We've found chrome won't let you 'ajax' in files from other domains when running under file://. However, in Safari it works fine.
Best solution for us is to use something like MAMP to run a local Apache server.

Categories