Reputation: 2510
In my php i'd like to redirect via javascript/jquery a url with a php variable via js function.
My js function
function Redirect(url){
document.location.href=url;
}
In my php page i try in this way but I fear there is a problem with the syntax in the $url.
if ($opz = 1){
$url = "index.php?opz=OK#PG2&id=" . $_GET['id'];
echo "<script>";
echo "$(function(){ Redirect($url); });";
echo "</script>";
}
If I try to redirect in this way everything works perfectly (no Redirect function).
echo "<script>
document.location.href='index.php?opz=OK#PG2&id=$_GET[id]'
</script>";
Can anyone suggest me what is the correct syntax to pass my php variable via the js Redirect function? Thanks.
Upvotes: 1
Views: 3176
Reputation: 810
Just change echo "$(function(){ Redirect($url); });";
to
echo "$(function(){ Redirect('$url'); });";
Notice the quotes. the url is to be passed to the Redirect function as a string. So enclose it in single quotes. like Redirect('$url');
Upvotes: 2
Reputation: 4967
your problem is simple:
echo "$(function(){ Redirect($url); });";
should be replaced with
echo "$(function(){ Redirect('$url'); });";
Upvotes: 2
Reputation: 324610
The problem is caused by the fact that your generated HTML looks like this:
Redirect(index.php?opz=.....);
As you can see, you're missing quotes.
To put a variable from PHP into JavaScript, I always use json_encode
. This ensures that, no matter what I pass it, JavaScript will see the same thing. It takes care of quoting, escaping, even iterating over arrays and objects.
Upvotes: 0
Reputation: 2540
try like below
if ($opz = 1){
$param = 'opz='.urlencode("OK#PG2").'&id='.$_GET['id'];
$url = "index.php?".$param;
echo "<script>";
echo "$(function(){ Redirect($url); });";
echo "</script>";
}
and pick up opz using urldecode();
Upvotes: 0
Reputation: 41
Assuming the Javascript code being generated is OK try window.location
Upvotes: 0
Reputation: 8179
Why you are trying to redirect your webpage using javascript.
You can do it with PHP also. Use PHP header()
function to redirect your page.
if ($opz = 1){
$url = "index.php?opz=OK#PG2&id=" . $_GET['id'];
header("Location:".$url);
}
Upvotes: 1