I am attempting to send data from a javascript file to a php file to then insert the data into a MYSQL database. The javascipt file's purpose is to obtain the data and then hand it off to the PHP script, which then inserts it.
The data looks like: {"temperature":257,"pressure":100}
I have seen the js code below be used, but is this the best method for me given that both files are locally in the same folder?
javascript
request= new XMLHttpRequest()
request.open("POST", "JSON_Handler.php", true)
request.setRequestHeader("Content-type", "application/json")
request.send(str_json)
php
$str_json = file_get_contents('php://input');
As a side note I have tried the above javascript but am getting an error which looks like:
/home/pxmcnjmy/etc/feynmaniot.com/bin/subscriber2.js:38 request= new XMLHttpRequest() ^
ReferenceError: XMLHttpRequest is not defined
at MqttClient.<anonymous> (/home/user/etc/domain/bin/subscriber2.js:38:5)
at MqttClient.emit (events.js:314:20)
at MqttClient._handlePublish (/home/user/node_modules/mqtt/lib/client.js:1277:12)
at MqttClient._handlePacket (/home/user/node_modules/mqtt/lib/client.js:410:12)
at work (/home/user/node_modules/mqtt/lib/client.js:321:12)
at Writable.writable._write (/home/user/node_modules/mqtt/lib/client.js:335:5)
at doWrite (/home/user/node_modules/readable-stream/lib/_stream_writable.js:409:139)
at writeOrBuffer (/home/uswer/node_modules/readable-stream/lib/_stream_writable.js:398:5)
at Writable.write (/home/user/node_modules/readable-stream/lib/_stream_writable.js:307:11)
at TLSSocket.ondata (_stream_readable.js:718:22)
NodeJs is used on the server-side just like how PHP scripts are used on the server. So, use the MySQL module provided for you in NodeJs for that task. However, if you will ever need to call scripts like js from a PHP script or PHP from js scripts, try using some shell commands and pass the argument to the scripts (basically, command-line).
PS: I don't yet know the downsides to this, but remember, Node is single-threaded. So, calling a PHP script on that thread is your decision. You could find some better way.
Nodejs doesnt provide the browser XMLHttpRequest API. You can use http.request that comes natively with NodeJS or you can use axios