Marc Ster
Marc Ster

Reputation: 2316

Parameter from url with php and write it into js variable in an if condition

I am trying to get a parameter from the url with php and write it into a js variable to do some jquery stuff.

my url looks like that

www.example.com/?v=12345

My Code

vnew = "<?php echo $_GET["v"];?>";
if (vnew  == null) {
myfunction();
}
else {
$(".myDiv").attr('src','newsrc');   
$(".title").html("bla");
};

if the url is like www.example.com shouldn't the value be 'null', so that my function fires? However if i set it to '12345' the else condition does not fire either.

What is wrong here? Thank you!

Upvotes: 0

Views: 153

Answers (3)

malta
malta

Reputation: 858

Change it like this:

<?php if ($_GET["v"]) { ?>
    myfunction();
<php } else { ?>
    $(".myDiv").attr('src','newsrc');   
    $(".title").html("bla");
<?php } ?>

OR

<?php 
if ($_GET["v"]) {
    echo "myfunction();";
} else {
    echo "$(\".myDiv\").attr('src','newsrc'); $(\".title\").html(\"bla\");";
} ?>

to check if your condition is working:

<?php 
if ($_GET["v"]) {
    echo "myfunction();";
} else {
    echo "Hello";
} ?>

Upvotes: 1

Fven
Fven

Reputation: 547

Try var_dump($_GET["v"]) on the base url. Use that value in your comparison.

Upvotes: 0

Mitya
Mitya

Reputation: 34596

It'll never be null, only an empty string. Think about what the JS output is if no value is passed:

vnew = ""; //no PHP output between the quotes, as no value found

In any case you don't need PHP to grab the var, in any case.

var tmp = location.search.match(/v=([^&]+)/), vnew = tmp ? tmp[1] : null;

In this case, the value WILL be null if no value is found.

Upvotes: 1

Related Questions