Js var to php var, Ajax?

Trying to find out how to pass a js variable to php $string but having trouble. So far I have this:

var button1 = BABYLON.GUI.Button.CreateSimpleButton("but1", "Save");
button1.top = 300
button1.width = 0.2;
button1.height = "40px";
button1.color = "white";
button1.cornerRadius = 20;
button1.background = "grey";
 var p1 = text.text

 $word3= <script>document.writeln(p1);</script>;

 $insert = "UPDATE users SET word1 = '$word3' WHERE username = '$username'";
 mysqli_query($db, $insert)


The $insert part works only if I put in $word3= “”; and it adds to mysql.
Most of the ajax examples are in HTML , so I am having trouble with this.


Hi Charlie,
try putting the contents of $word3 in double quotes
$word3= "<script>document.writeln(p1);</script>" ;

There seems to be a bug somewhere.
When I put it in " " it sends

" script>document.writeln(p1);</script "

to Mysql, instead of just the word in text.text.

I am using Netbeans IDE .php page.
I’v tried this on a .php page and " script></script" is not working(highlighted) in a <?php ?> block.

I’m no PHP expert, and it’s a bit out of the scope of this forum, but - aren’t you combining front-end and backend in a way that will prevent it from actually working?

The basic idea behind AJAX is that the front-end is sending a request to the server (not an sql query), and the server gets this request and does whatever it wants with it (like an sql query). So when pressing the button, you need to use JavaScript (and probably not php) to get the value and send it to the server.

The code you wrote is not dynamic. It’s fixed to the point of writing the document, which means that unless there is already content in text.text, p1 will always be empty.

PHP is precompiled, script elements are post compilation.

You would have to do what @RaananW and look into ajax. Where as you would have a secondary PHP file that you POST or GET with the xhr() and then pass the data package to it from that.

you can then have a response from the php page that you did the request to letting you know if the insert was successful or not and then have your javascript do the correct callbacks.

Order is:
User-Page Loads
Script requests XHR with Data package
Server Responds Compiles and runs the PHP script you requested.
XHR request responds with the results depending on your PHP scripts output
You parse the response and go about your day.