

2) By adding in the JS script within the HTML document only the necessary data processed by PHP.

When you click on the button, the fetch() method will be executed and JavaScript will put the response inside the element. 1) By writing the entire JS script within PHP code and adding it to the web page with PHP function ' echo ' (or ' print '). You can run a local PHP server using php -s localhost:8000 command and open localhost:8000/index.html from the browser to see your HTML page. Please make sure that you’re opening the HTML file from the same server that serve your PHP files to avoid CORS issues. Once your files are ready, open the index.html file from the browser. In the code above, I used the full URL of my add.php, which is located at You need to change the address to your actual PHP file location. JavaScript will send a POST request to the PHP server and write the response inside the element. The fetch() method will be executed each time the element is clicked. addEventListener ( "click", function ()) They are two different programming languages. getElementById ( "add" ) let x = 5 let y = 3 btn. No, its not possible to write PHP code inside a JavaScript file or vice versa. If the variable needs to get stored on the server, use ajax to send it there.Add 5 + 3 let btn = document. The suggested js solutions are the way to go. However, the OP uses an html formated file (probably with php extension), no js file, so in this specific case there's no need for my suggestion.

All php parts in the js file will get executed and the js file with added server data will be handed to the browser. Parse js/css as a PHP file using htaccessĮdit: On http page request this trick makes files with js extension be parsed by the php compiler. Header set Content-type "application/javascript" You have to tell the server to evaluate the js files as php files, if you are running an apache server you can do this with a htaccess-file like this: As some people pointed out you have to keep in mind the php is evaluated on the server and then returned as static stuff to the browser who will then run the javascript with the added data from the server. Don't know if this is a very good idea, but you can. There is a way to run php in client-side javascript (not talking about server-side js here).
