+ 1
How can I use Javascript variables in Php?
3 odpowiedzi
+ 3
INFO: you can write all JS code inside PHP document.
example:
normal web code
https://code.sololearn.com/W92YbRPPbmF0/?ref=app
converted web code to php (no php syntax)
https://code.sololearn.com/wN3T3QkNBocd/?ref=app
+ 1
Thanks for the quick answer it helped a lot
0
You can't do it directly. php executes on the server and Javascript executes on the client (person viewing the website) computer. While you can use php inside javascript (because of the order of execution when rendering a page) the opposite is true of true.
That said, you can use ajax in javascript to send data to a php file on the server and get a result back. I prefer jQuery for this. It would look something like this.
js file
var payload = { key1: "value1", key2: "value2};
$.ajax({
type: "post",
url: "/file/on_server.php",
data: payload,
success: function(response) {
// do something with response
response = JSON.parse(response);
document.write(response.answer);
}
});
php on server
<?php
$result['answer'] = $_POST['key1'] * $_POST['key2'];
echo json_encode($result, JSON_HEX_APOS);
?>
This takes a json object and posts it to a php file which does whatever you need and returns and json encoded string. The javascript parses the string to a json object and again does what you need with the result.