How do I use a JavaScript variable as a php function parameter?

Hi all,

I’m trying to create a webpage that allows users to create an account with a username, password, and security question. My database stores this information, and when a new user signs up, I want to make sure they don’t pick a user name that already exists, because I need to keep them unique for relational data purposes. So, I wrote a function in php that fills an array with the usernames that are already there, and then compares them in a loop to the username that the user has entered in the html form. I was hoping not use the method of sending JavaScript data to php via an href, because I also have JavaScript validation that occurs on the form submit, and I think linking somewhere before that to check the username would screw up the rest of the validation.

So what I tried was to store the following string in a php variable: “”;

When I use echo to print the variable that holds this string in php, it indeed prints out the result I want, which is the literal value of txtUsername. However, when I pass this string variable as a parameter to my username comparison function in php, I get a nonsensical result, because php doesn’t realize that the angle brackets and the script identifier and so forth are to be interpreted in a certain way. So, it just thinks it’s a plain string, instead of fetching the txtUsername.value from JavaScript.

Any suggestions on how I can get this JavaScript data into a literal string that php can recognize?

You can not pass javascript variable to a php function in the way as you describe. PHP is a server side language, while javascript is client side. Any php code is processed on server, and HTML is sent back to client browser. If you want to send a variable from Javascript to php script, you need to either use Ajax or to reload page in browser passing your value of your variable to php script via query string.

Sponsor our Newsletter | Privacy Policy | Terms of Service