0

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!

2
  • 1
    Why would it be null? An empty string is more likely. Commented Feb 8, 2014 at 17:29
  • just if vnew = '' ? But why isn't the else condition working Commented Feb 8, 2014 at 17:32

3 Answers 3

1

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";
} ?>
Sign up to request clarification or add additional context in comments.

7 Comments

I am taking care of the condition on the server side which is always safer. Instead of closing the php each time, you may echo the text within the php.
I have included an option where there is only 1 opening and closing php tag
try this instead - if (isset($_GET['v']))
hm did not change something. i don't get it
the else condition isn't working.. if v is set. everything is fine. if not nothing happens
|
1

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.

4 Comments

Ok now the if null query works. But not if v is set.. then nothing happens
if i set v to '123'. It will return 'v=123,123' now
Hmm, no. Try alerting vnew - if you access the file with v=12345 in the URL, your alert will be "12345". Tested.
You are right. But why isn't my else condition working then? :/
0

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

Comments

Your Answer

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.