简体   繁体   中英

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.

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);

I think You are trying to get query string variable to javascript not to php. Try something like:

Get query string parameter to js

You are getting an undefined variable error because you have not set the js variable 'username' anywhere. Setting this in the URL is NOT the same as defining a variable.

If you are setting the URL correctly you shouls see something like 'register-form.php?username=Francesca'

You can do this with a mix of PHP and javascript.

In your register-form.php:

register-form.php:

if(isset($_GET["username"])) {
  $username = $_GET["username"];
} else {
  $username = "not set";
}

in your js (this is better than calling <body onload="inputUsername()"> ):

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

Better yet would be to not use js at all and do this all in PHP:

<?php
if(isset($_GET["username"])) {
  $username = $_GET["username"];
} else {
  $username = "not set";
}
?>

<input name="username" id="username" type="text" value="<?php echo $username ?>">

Here ya go. I commented the code so it makes more sense hopefully. Basically, we get the url from the address bar and parse out the pieces one by one to get what we want.

window.ParseQueryString = function () {
    //Get the current location in the address bar
    var url = window.location.href,
        parameterSet = [],
        //Get everything to the right of the '?'
        parameterString = url.split('?')[1];

    //Do we have anything to work with?
    if (parameterString) {
        //Lets get all individual parameter in the parameter string
        var parameterParts = parameterString.split('&');

        for (var i = 0, e; e = parameterParts[i++];) {
            //Get the parameter key and the value
            var parameter = e.split('=');

            //Push it into the array
            parameterSet.push({
                'key': parameter[0],
                'value': parameter[1]
            });
        }
    }

    //Give me my prettyfied query string array plz!
    return parameterSet;
}

console.log(ParseQueryString());

Using this code with a window location of http://www.home.com?s=search&f=images will yield:

[{ key: 's', value: 'search'}, {key: 'f', value: 'images'}]

With this, in your onload callback, you can call the ParseQueryString and look through it to find the username value and populate it to textbox.


Edit


I am added a function that instead of returning an array of key/value pairs, it will return an object with the query string keys as the fields on the object.

window.ParseQueryString = function () {
    //Get the current location in the address bar
    var url = window.location.href,
        parameterSet = {},
        //Get everything to the right of the '?'
        parameterString = url.split('?')[1];

    //Do we have anything to work with?
    if (parameterString) {
        //Lets get all individual parameter in the parameter string
        var parameterParts = parameterString.split('&');

        for (var i = 0, e; e = parameterParts[i++];) {
            //Get the parameter key and the value
            var parameter = e.split('=');

            //Add a new field to the object
            parameterSet[parameter[0]] = parameter[1];
        }
    }

    //Give me my prettyfied query string array plz!
    return parameterSet;
}

Here is a fiddler demonstrating your specific use case. Please note that the fiddler is appending a query string to the url as fiddler wouldn't allow it otherwise. This occurs on line 3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM