I have a PHP variable thePHPvar in a file DoStuff.php in my website.
thePHPvar gets set to a string.
Then after that the code in DoStuff.php does
header("Location: http://localhost/theWebite/index.php");
I need 2 things in my onLoad handler inside the body tag of index.php:
<body onload="doLoad()">
My doLoad() function must be able to do 2 things:
1) get access to ‘thePHPvar’ variable, which again is a string (a path name) that was set in PHP code in DoStuff.php just prior to the header() redirect.
2) also, doLoad() must be able to detect when ‘thePHPvar’ is empty so it can avoid trying to use
‘thePHPvar’ and skip the logic that uses that string.
I’m new to php and javascript and have impressed myself with getting working what I have now,
but I’ve spent 1/2 day on this, read lots of similar issues on SO.
I have to be able to redirect back to index.php, grab this string variable and if it’s been set (not null), execute some javascript code.
Right now this is all my onLoad() does, and hey — it works. But not the right way, yet.
<head>
<script type="text/javascript">
function doLoad()
{
alert("Page is loaded");
}
</script>
</head>
Without introducing a bunch of new stuff I’d have to learn like Ajax etc., how can I get this done in javascript, html, php and what I have here?
You can use a session variable as Jorge said, if this myPHPVar is specific to a user. Otherwise, pass the variable in your header redirect:
As you’re a beginner, you probably won’t want to use JSON to get the variable from PHP to Javascript, but do look it up if you ever have to pass a lot of data to Javascript code.
If the user has any influence over that PHP variable, be sure to sanitise the variable against XSS attacks.
To check if myPHPVar is empty in your
doLoadmethod, just useif (!myPHPVar) { .... }