JavaScript Redirection - php

Here is the code I have,
<script language="JavaScript">
var url = "http://localhost:8888/uploads/"+<? $name ?>+"/output.txt";
setTimeout("top.location.href = url",1000);
</script>
$name is a PHP variable which has the name of which directory I'm trying to redirect to.
Needless to say, it isn't working. What's wrong with it? I don't know a lot about javascript so I probably did something stupid
Thanks

If your mixing PHP with JavaScript, it's always advisable to check the output being sent to the browser: right click on your website and click view source!
JavaScript doesn't care whether the content being sent to it is static HTML, from a Database or generated by PHP. If its in the output, it'll parse it.
If you'd have done that, you'd notice that your not echo'ing the $name variable.
<script language="JavaScript">
var url = "http://localhost:8888/uploads/"+<? echo $name ?>+"/output.txt";
setTimeout("top.location.href = url",1000);
</script>
But that'd give you
<script language="JavaScript">
var url = "http://localhost:8888/uploads/"+ foo +"/output.txt";
setTimeout("top.location.href = url",1000);
</script>
Which isn't valid JavaScript, as foo is now a JS variable, not a string.
So you should have:
<script language="JavaScript">
var url = "http://localhost:8888/uploads/<? echo $name ?>/output.txt";
setTimeout("top.location.href = url",1000);
</script>
Furthermore, passing a string to setTimeout (or setInterval) is not recommend; for the same reasons against using eval(), so you should end up with something like this instead:
<script language="JavaScript">
var url = "http://localhost:8888/uploads/<? echo $name ?>/output.txt";
setTimeout(function () {
top.location.href = url
},1000);
</script>

Pass a function, not a string, to setTimeout.
var url = "http://localhost:8888/uploads/<?= $name ?>/output.txt";
setTimeout(function ()
{
top.location.href = url;
}, 1000);
I am assuming that the $name is properly filled in by PHP.

Try this:
setTimeout(function() { top.location.href = url; }, 1000);

Try like this:
var url = "http://localhost:8888/uploads/"+<? $name ?>+"/output.txt";
setTimeout(function() {
top.location.href = url;
}, 1000);

<?php echo "var url = 'http://localhost:8888/uploads/$name/output.txt'"; ?>
Remove pluses and braces - just put variable in url.
Also use Firebug to troubleshoot your JS code: http://getfirebug.com/

Use 'echo' or the slightly unreadable php short code <?= to echo out a variable.
<script language="JavaScript">
var url = "http://localhost:8888/uploads/<?php echo $name; ?>/output.txt";
setTimeout(function(){
top.location = url;
}, 1000);
</script>
I know I've created another closure, but feel it's more readable.

It should be:
window.location.href = url

Related

Passing sql string variable into javascript function

I am trying to pass a string from a query into a javascript function.
An integer will pass into the function but string will not.
echo "<a href='#' onclick='delete_game({$title});'
class='btn'>Delete</a>";
<script type='text/javascript'>
function delete_game(title){
var answer = confirm('Really?');
if(answer){
window.location = 'delete.php?id=' + title;
}
}
</script>
I expected the javascript function to be executed, but instead nothing happens.
Why don't you use ajax for this? As mentioned in comments mix PHP/JS isn't good.
In your HTML, you can do something like
I'm assuming that you are using Blade.
Delete Game
Then in your javascript, you do this using jQuery:
function deleteGame(title){
var answer = confirm('Really?');
if(answer){
$.ajax({
url : "your-php-file.php",
type : 'post',
data : {
title : title
}
})
.done(function(msg){
$("#result").html(msg);
})
.fail(function(error){
console.log(error);
});
}
}
In your PHP you process receiving the data from post $_POST
$title = $_POST['title'];
You can understand better the Ajax function of jQuery here.
A few things:
I would change window.location to window.location.href
Change your echo to:
echo "Delete";
Check if $title is set
var_dump($title);
If you'd like to make it a bit cleaner and are prepared to use jQuery:
Delete
<script type='text/javascript'>
$(document).on('click', '#delete', function () {
var title = $(this).data('title');
var answer = confirm('Really?');
if (answer){
window.location.href = 'delete.php?id=' + title;
}
});
</script>

How to embed & execute javascript into html?

index.html
<script>
function check() {
var id = $('input[name=id]').val();
$("#result").load("/ajax.php", {id:id});
}
</script>
<input type="text" size="3" name="id"><br />
<button onclick="check();">Pay</button>
<div id="result"></div>
ajax.php
<?php
$id = (int)$_REQUEST['id'];
//some validations and SQL executions
echo "<script language=JavaScript src='https://*****/index.php?id=$id&invoice=$invoice&sum=$sum.......etc'></script>";
I try to form javascript in php file and embed it into div with id="result".
I've used get, load, ajax, createElement methods but the script doesn't execute.
try this..
$('#result').load('ajax.php');
In your php file ajax.php include the header.
header('Content-Type: text/javascript');
And in index.html add type=”text/javascript” to the script tag.
<script type=”text/javascript”>
function check() {
var id = $('input[name=id]').val();
$("#result").load("/ajax.php", {id:id});
}
</script>
You must load script as real script element. DOM conversion of "<script>/*...*/</script>" may fail in this case. This is done via standart DOM document.createElement function.
var script = document.createElement("script");
script.src = path;
Other way is to download the script via AJAX and then eval it.
Try using getScript:
$.ajax({
url: url,
dataType: "script",
success: success
});
try this:-
"<script language=JavaScript src='https://*****/index.php?id="'.$id.'"&invoice="'.$invoice.'"&sum="'.$sum.'".......etc'></script>";
Why wouldn't you load directly the script URL using AJAX?
ajax.php only should return path to the script:
$id = (int)$_REQUEST['id'];
//some validations and SQL executions
echo "https://*****/index.php?id=$id&invoice=$invoice&sum=$sum.......etc";
Besides that all HTML element attributes should be enclosed with quotes or apostrohpes.
Then you should load this url in javascript and generate script element here:
function loadScript(url,appendTo) {
var script = document.createElement("script")
script.type = "text/javascript";
script.src = url;
if(typeof appendTo.appendChild == "function") //Chceking if we can append script to given element
appendTo.appendChild(script);
else
document.body.appendChild(script) //This will not work in old IE, where document.body is not defined.
}
You call this function with script url and optional target element (where will be put in) as parameters.
Like this:
$.get("ajax.php",{param1:"value"},function(scriptUrl) {loadScript(scriptUrl, document.getElementById("result");})

Use a PHP variable inside a jquery click()?

I have this,
$(document).ready(function(){
$('#link').click(function(){
var user_login = <?php $base_url; ?>;
window.location = user_login + '/login';
});
});
note that $base_url is global variable. This works in FF but not on Chrome and IE. Thanks.
You need to add quotes around the php tags to designate that the value of $base_url is a string:
$(document).ready(function(){
$('#link').click(function(){
var user_login = "<?php echo $base_url; ?>";
window.location = user_login + '/login';
});
});
That way, when the browser gets this block, it will look something like:
$(document).ready(function(){
$('#link').click(function(){
var user_login = "http://www.example.com"; // after php is executed
window.location = user_login + '/login';
});
});
You need to echo the variable, not just simply have it in a code block. And for safety, to prevent introducing JS syntax errors, you should json-encode the value:
var login = <?php echo json_encode($base_url); ?>;
See below, note the quotes around the PHP echo
$(document).ready(function(){
$('#link').click(function(){
var login = '<?php echo $base_url; ?>';
window.location = user_login + '/login';
});
});
I suppose its a PHP file, you need to surround your variable contents by quotes to javascript
$(document).ready(function(){
$('#link').click(function(){
var login = <?php '\''.$base_url.'\''; ?>;
window.location = user_login + '/login';
});
});
Run this script in a PHP file, not in a .js file, and don't forget tho ECHO your variable and add quotes (in javascript), as said in other answers !

How to pass value from javascript to php using address bar

I have .js and .php files and html pages. I am including js files in html files and php files in js files.
I want to pass 'cat' value from js file to php file using address bar when I go to this page;
/demo/convert.html?cat=volume
But I have no idea how to do this.
By the way, this is a blacberry project and I am not sure if I can use address bar to pass value. Any idea is welcome.
Test this sample code with an URL like :
http://sputnick-area.net/test/index.php?foobar=works_as_a_charm
<?php
$var = $_GET['foobar'];
echo <<<EOF
<html>
<head>
<title></title>
</head>
<body>
demo of using PHP GET variable in Javascript :
<script type="text/javascript">
alert("$var");
</script>
</body>
</html>
EOF
?>
Edit :
if you'd like to handle GET variables from within JavaScript, consider the following HTML + JavaScript sample : http://sputnick-area.net/test/index.html?foobar=works_as_a_charm
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript">
var vars = [], hash;
var hashes = window.location.href.slice(
window.location.href.indexOf('?') + 1
).split('&');
for(var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
alert(vars['foobar']);
</script>
</body>
</html>
Sure you can. When your JS function is called, you would have to do something like this:
function someFunction(someParameters) {
//Do whatever you need to do
window.location = "/demo/convert.html?variableName=" + variable;
}
This will cause a page reload with the new variable accessible through PHP in the $_GET array. For example:
<?php
$name = $_GET['variableName'];
if(length($name) < 3) {
echo "That is a short name!";
}
?>
A page reload (used here), is necessary to send value to PHP as it is run server side. Your only other solution would be to use AJAX and load page content dynamically. This, however, would be the simplest solution.
EDIT:
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
var urlvariable = getUrlVars()['variableName'];

Automatic Page redirection not working in safari browser

I am using below code for automatically redirect to the page in a fraction of seconds.
<script language="Javascript" type="text/javascript">
<!--
var testTimerID;
testTimerID = window.setTimeout(autoDirect, 30*250 );
function autoDirect() {
window.location = 'home';
}
</script>
This script works fine in all browser except in safari browser.it does not automatically redirect to the another page(home). what is the issue?.how can i solve it?.
Try it like this:
<script language="Javascript" type="text/javascript">
//<!--
var testTimerID;
testTimerID = window.setTimeout(function(){
window.location.href = '/home';
}, 30*250 );
//-->
</script>
Usually JS does not work properly and in same way through all the web browsers... Therefore I advise to use jQuery as it is debugged for all common browsers...
Try aslo reading through this: How to redirect to another webpage in JavaScript/jQuery?
Also instead of relative URL You shoudl use absolute like http://www.mydomain.com/home/, so the code should be:
...
window.location.href = 'http://www.mydomain.com/home/';
...
.
This works perfectly in Safari 5 for windows
<script language="Javascript" type="text/javascript">
var testTimerID;
testTimerID = window.setTimeout(autoDirect, 30*250 );
function autoDirect() {
window.location = 'http://google.com/';
}
</script>

Categories