Search code examples
javascriptvariablesurlonload-event

Unable to get variable from passing through URL


I have a variable stored username and I wish to pass this through a link to the next page. So I have:

<a href="register-form.php?username=username">Go!</a>

When you land on register-form.php there is an onload event for the script:

<body onload="inputUsername()">

function inputUsername(){
  console.log("I'm running" + username);
  document.getElementById('inputUsername').value = username;
   }

However I get an undefined variable error for username.

It seems to me that the URL is not passing the variable correctly. Should I be seeing my actual variable in the address line? Should I be seeing username=myusernameisthis ?

In essence, all I'm after is passing the variable username from page 1 to page 2. That's all.


Solution

  • Parameters passed in a url query string don't get magically loaded into the javascript global scope.

    As @Archios says you can parse the query string with javascript with something like:

     var username = getUrlVars()["username"];
    
     function getUrlVars() {
     var vars = {};
     var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,
        function(m,key,value) {
         vars[key] = value;
     });
     return vars;
    }
    

    but personally I prefer:

    function inputUsername(){
     var username= "<?php echo isset($_GET[username])?$_GET[username]:''; ?>";
     console.log("I'm running" + username);
     document.getElementById('inputUsername').value = username;
    }
    

    what would be even easier, is if you changed:

     <input id="inputUsername" type="text" name="username">
    

    to

     <input id="inputUsername" type="text" name="username" value="<?php echo $_GET[username]">
    

    and remove the onload event.

    the href on the previous page should look something like:

     <a href="register-form.php?username=<?php echo $username; ?>">Go!</a>
    

    assuming $username holds the current username

    where your script says

     username = wordOne + wordTwo + wordThree;
    

    add the line

     $('.userNameButton a').attr('href','register-form.php?username='+username);