Reputation: 665
I am trying to send string data to a php script on localhost:8080 to be saved, but the Javascript function cannot find the php file and gives a 404 error.
This is the Javascript:
var data = new FormData();
data.append("data" , myStringData);
var xhr = new XMLHttpRequest();
xhr.open('POST', "http://localhost:8080/Source/ServerInputManager.php", true);
xhr.send(data);
This is the ServerInputManager.php script:
<?php
if (!empty($_POST['data'])) {
$data = $_POST['data'];
$fname = "NewFile.txt";
$file = fopen($fname, 'w'); // Creates new file
fwrite($file, $data);
fclose($file);
}
?>
I know the php file exists because I can download it from that URL in chrome. I can also read the contents with a GET request using that URL. But whenever I try to use POST, it gives a 404 error. I am not using any php libraries, but I am using node to run a server.js script.
This is the file structure:
|- index.html
|- index.css
|- server.js (ran by node)
+- Source
|- InputManager.js (contains the javascript code)
+- ServerInputManager.php (contains the php code)
I've also tried using these directories:
http://localhost:8080/Source/ServerInputManager.php
http://localhost:8080/ServerInputManager.php
localhost:8080/Source/ServerInputManager.php
localhost:8080/ServerInputManager.php
/Source/ServerInputManager.php
Source/ServerInputManager.php
/ServerInputManager.php
ServerInputManager.php
But they all gave 404 errors. What am I doing wrong?
Upvotes: 1
Views: 875
Reputation: 665
To answer my own question,
I found Randy Casburn's comment most useful
you have no POST 'route' to /Source/ServerInputManager.php in your Express router setup.
Although I did not exactly solve the problem, I found another way to get to the same result.
This is the new Javascript code:
fetch("http://localhost:8080/targetInput", {
method: 'POST',
body: myStringData,
}).then(response => {
console.log(response);
})
This is what I added to my server.js script:
var fs = require('fs');
var app = express();
app.post('/targetInput', function(request, response) {
request.on('data', function(data) {
data = data.toString();
// Do whatever with the string data on the server
response.end("Success!");
});
});
The php file is no longer used.
Upvotes: 0
Reputation: 1817
I guess this js file runs on a client browser and it was served by the same server that holds your php app.
If that's the case, then you should expose an endpoint on the server side that expects POST requests on some url like /input
(for example).
Then your js code should be:
xhr.open('POST', "/input", true);
xhr.send(data);
Remember: you don't perform POST requests directly to php files but to a server that works with php. The server shall receive the POST request on /input and delegate the processing of said request to ServerInputManager.php (or delegate all requests to ServerInputManager.php and only process POST requests on /input).
Hope this helps
Upvotes: 1