Nach Nach - 1 month ago 4
Javascript Question

JS Won't Redirect

I have this code that I have made and have been trying to fix it for days. I am trying to make it redirect to whatever the $link variable is set to. All it does is just give me a blank page. Any answers?

$l = $_GET['l'];
$db = new mysqli('localhost', 'root', 'password', 'link');
$sql = "SELECT * FROM links WHERE new_url='$l'";
$result = $db->query($sql);
if($result->num_rows > 0) {
$row = $result->fetch_assoc();
$link = $row['website'];
$string = $row['new_url'];
echo '<script type="text/javascript">',
'window.location = $link;',
} else {


If you'd done ANY kind of debugging, like viewing the source of the page you're generating, or even checking your brower's debug console, you'd be TOLD about your syntax errors. You're generating this:

window.location =;

Does that look like valid Javascript to you?

Never EVER directly dump text from PHP into a Javascript code block for this exact reason. PHP may just be outputting a URL, but it's going into a JS code block, so the JS code you're generating has to be VALID code. Always use json_encode():

$link = json_encode($row['new_url']);
echo "window.location = $link;"

which produces:

window.location = '';

Note the ' quotes...