Can I make JavaScript write PHP?

12
asked by anonymous 01.10.2015 / 17:33

3 answers

13

Essentially not.

And many programmers do not understand this. They do not understand what I said in that question . PHP only generates a text that coincidentally can be a JS code, PHP does not even know what it is.

A JS within a PHP code will not run on the server, it is just text, for PHP that is not a code.

JS will run on the client, probably a browser and does not have direct contact with PHP. The contact between the JS code in the client and the PHP code on the server will be through communication through the HTTP protocol. That is, JS can send data to the server that will pass to the PHP code deciding what to do with it. Just this.

Simplified example:

var req = new XMLHttpRequest();
req.onreadystatechange = function() {
    if (req.readyState == 4 && req.status == 200) {
       // faz alguma coisa;
    }
req.open("GET", "pagina.php", true);
req.send();
}

Of course you can use JS on the server to assist PHP in some task and even generate PHP code for the server to run, but it's something separate and it's not what people usually do, probably because it's too much complexity and less.

Within "normal" PHP usage, you can not.

    
01.10.2015 / 17:38
12

You can not because javascript works on the client side of the http loop and php works on the server side, so the code generated by javascript will never run on the server, it will be just a string / common text containing php instructions. >

If you need to make javascript work with some php feature use ajax.

    
01.10.2015 / 17:39
3

The answer is yes , but not for the purpose you want. Using Node.js you can write files:

Note: All languages write files. But not all of them work together.

fs.writeFile('message.txt', 'Olá Mundo!', function (err) {
  if (err) throw err;
     console.log('Nada foi salvo!');
});

In .htaccess, just put this and your txt files become php:

AddType application/x-httpd-php .txt

Here you have more information about: link

Here is another practical example of saving files and saving a txt with the extension ".php", a PHP file:

Sample Demo

Github FileSaver

    
01.10.2015 / 22:42