1

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.

asked Sep 17, 2013 at 8:31
1

6 Answers 6

2

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');

answered Sep 17, 2013 at 8:40
Sign up to request clarification or add additional context in comments.

Comments

2

your problem is simple:

 echo "$(function(){ Redirect($url); });";

should be replaced with

 echo "$(function(){ Redirect('$url'); });";
answered Sep 17, 2013 at 8:39

Comments

1

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);
}
answered Sep 17, 2013 at 8:35

Comments

0

Assuming the Javascript code being generated is OK try window.location

answered Sep 17, 2013 at 8:35

Comments

0

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();

answered Sep 17, 2013 at 8:35

Comments

0

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.

answered Sep 17, 2013 at 8:38

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.