This question already has an answer here:
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");
}
</div>
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).
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.
function runPage(){
var page = '<?php echo $_GET['page']?>';
if(page!=''){
console.log("Page = " + page);
}
}
location.search
Return the query portion of a Url
URL:index.php?page=quiz
location.search="?page=quiz"