0

I'm using GET to retrieve a query string from my url e.g:

index.php?page=quiz

Then I want to run my function getPage which is JS using the value of page= (in this case it's quiz)

So I have an onload function which only runs if page has a value:

<body
    <?php
        if(!empty($_GET["page"])){
            //echo "onload='runPage(" . $_GET["page"] . ")'";
            echo "onload='runPage()'";
        }
    ?>
>

This basically works out as:

<body onload="runPage(quiz)">

I want to pass quiz in this case to the runPage function so that I can use it within it. For example:

function runPage(this){
  var page = this;
  console.log("Page = " + page);
}

But this just throws an error saying quiz is undefined... where is my logic wrong?

Edit: So I've updated my code and am now getting:

<body onload='runPage("quiz")'>

But now I want to take "quiz" and pass it to this function:

function runPage(){
// run stuff in here using the value of that variable e.g:
console.log("You've come through from the URL with quiz on the end");
}
user1486133
  • 1,309
  • 3
  • 19
  • 37

4 Answers4

0

You need to put the variable in there. For an inline event handler, it's a little trickier:

<body <?php
  if( !empty($_GET['page'])) {
    echo 'onLoad="runPage('.htmlspecialchars(json_encode($_GET['page'])).');"';
  }
?> >

Normally, you can just use json_encode to pass a variable from PHP to JavaScript in a safe, XSS-proof manner. But because you are in an inline event handler, you need to also use htmlspecialchars to ensure that it doesn't break your HTML context (as that could potentially be another XSS vector otherwise).

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
0

You need to enclose your string in quotes. Because you're already nesting quotes in your PHP code you'll need to escape them like this:

echo "onload='runPage(\"" . $_GET["page"] . "\")'";

Be careful, though. This is susceptible to script injection. At the very least you need to sanitise the contents of $_GET['page'].

Your Javascript function then becomes:

function runPage(page){
  console.log("Page = " + page);
}

Note that this is a keyword and has a special meaning in Javascript. You don't need it anyway - just use a different variable name.

  • 1
    What happen if I set up you the bomb, and send you to `http://example.com/index.php?page="); alert("All your base are belong to us` ? – Niet the Dark Absol Apr 02 '14 at 13:32
  • OK so I tried this. But I don't understand how to get that value: ("thisvaluehere") from the onload and be able to use it in the function. – user1486133 Apr 02 '14 at 13:43
0

location.search Return the query portion of a Url


URL:index.php?page=quiz


location.search="?page=quiz"

Omar Sedki
  • 608
  • 6
  • 14
-2
function runPage(){
  var page = '<?php echo $_GET['page']?>';
  if(page!=''){
    console.log("Page = " + page);
  }      
}