Assign Variable to PHP

Hi there,

I was wondering if it were possible to assign a PHP variable’s value to that of a JS variable.
What I mean is having a var in JS, and then making a PHP variable equal to the JS one.

Like this:

function username() {
var username = "Mr. Jones";

<?php $username = username; ?>


Now of course, this file will be .php, and will be called as such when including it to a page (<script type=“text/javascript” src=“username.php”).

The above code doesn’t work… But I want to know if it can be done in such a manner.
I just want a PHP variable to be equal to a variable in JS.

Any ideas?

Without something like AJAX there is no way you can do this.
What is it that you ultimately would like to achieve with this? Maybe there are other ways :slight_smile:

Well, I was hoping to quickly determine if a username exists with the use of JavaScript and PHP… Without having to reload the page.

Remember, you are OUTPUTTING javascript from PHP, so you just need to echo the value.

If you are using the technique I showed in my reply to your other post, it is a no brainer.
Show more of your current code.

I agree with ScallioXTX that this functionality is best suited for AJAX.

Yes in that case you indeed need AJAX.
Here’s a tutorial on how to that with jQuery: check username availability in ajax and php | ajax username checker

Alright, thanks.