Question

I've been experimenting with PHP forwarding to the end of making a modal window that appears with only a link and no modal script on the current page.

With PHP you can forward like this:

<?php
header( "Location: http://example.com" );

And also you can forward using alternate URL Schemes, for instance you can open an SMS Message like so:

<?php
header( "Location: sms:867-5309" );

So for instance you could have "http://yoursite.com/phone-number.php" start an sms conversation on a supporting device and also keep the page you left open.

I've also seen people use the URL Scheme "javascript:" to run javascript from the browser address bar or a bookmarklet.


My Problem is: Whenever I try to execute Javscript with the PHP header redirect nothing happens, like so:

<?php
header( "Location: javascript:alert('hey!');" );

My Question is: Why won't it execute and Is there a way to make it work?

Was it helpful?

Solution

No, the javascript URI-scheme is just a fake non-standardized scheme, allowed by browsers for backwards compatibility in anchor elements to execute JS. It has been deprecated for a long time in favor of the correct event syntax, like this:

<a onclick="alert('hey!')">Click me!</a>

If you want to execute Javascript 'in a redirect' you should reverse the approach - instead of doing a server request directly, use an Ajax request to invoke the serverside code, and then use an onSuccess callback to execute the JS code to be run afterwards.

It is even possible, easily with libraries like jQuery or Mootools, or manually using eval, to have an Ajax request actually return Javascript code which is then executed, allowing you even more flexibility.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top