1

I'm trying to pass data (JSON) from a Javascript file to a PHP file and then return something. I already tried the PHP function file_get_contents('php://input') but unfortunately its not allowed in the system I'm using. But Curl is allowed, so I'm trying do do it with cURL.

Sadly, I don't get it to work properly.

JS Code:

var data = {
    'name': 'kevin'
};
var sendable = JSON.stringify(data);
console.log(sendable);
var request = new XMLHttpRequest();


request.open("POST", "http://192.168.64.2/testJsRequest.php", true);

request.onreadystatechange = function() {
    if (request.readyState == 4 && request.status == 200) {
        // $loggable = JSON.parse(request.responseText);
        // $name = $loggable['name'];
        console.log("RESPONSE " + (request.responseText));
    }
}

request.send(sendable);

PHP Code:

            <?php

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, 'php://input');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);

        $output = curl_exec($ch);

        if ($output === FALSE) {
            echo "cURL ERROR" . curl_error($ch);
        }
        curl_close($ch);

        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Headers: *');
        header('Access-Control-Allow-Method: POST, GET');

        echo($output);
2
  • It would probably be easier to send URL encoded data and $_POST Commented Feb 10, 2022 at 18:27
  • In the PHP code, do a print_r($_POST); and look at what it shows, it will probably have the data you sent via AJAX call Commented Feb 10, 2022 at 18:32

1 Answer 1

3

Your javascript looks good. On the server side you don't want to use cURL. CURL is for getting responses from other servers, not from a client.

Here is an example PHP script that should work with your example:

<?php
header('Content-type: application/json');

$data = json_decode(file_get_contents('php://input'));

$msg =  'Hello ' . $data->name . '.  Nice to meet you.';

echo json_encode(['name' => 'david', 'msg' => $msg]);

?>

Now in this example we are sending a JSON encoded object back in response. I did this since you said you want to pass JSON back and forth not just a text string. To accommodate this you have to modify your javascript slightly:

var data = {
    'name': 'kevin'
};
var sendable = JSON.stringify(data);
console.log(sendable);
var request = new XMLHttpRequest();


request.open("POST", "192.168.64.2/testJsRequest.php", true);

request.onreadystatechange = function() {
    if (request.readyState == 4 && request.status == 200) {
        console.log("RESPONSE: " + JSON.parse(request.responseText).msg);
    }
}

request.send(sendable);

It looks like you will know how to take it from here, but leave a comment if you need more help.

So in the PHP script $data will contain the full data structure that was encoded into JSON and sent via POST, and in javascript you can use data = JSON.parse(request.responseText) to get all the data sent back from PHP.


Edit to add examples of using POST for systems where direct access to the file system is restricted:

According to Mozilla docs there are two ways to submit data with XMLHttpRequest: Ajax only and using the FormData API and the disadvantage of the FormData option is that the data can't be JSON (stringified with JSON.stringify()). The advantage of the FormData API that we are interested in is that PHP will populate the $_GET, $_POST, $_REQUEST superglobals from data submitted in this way. We can also think of an easy workaround to send JSON through the FormData API.

First example using the FormData API normally:

var data = {
    'name': 'kevin'
};
var sendable = new FormData();
for ( var key in data ) {
    sendable.append(key, data[key]);
}
console.log(sendable);
var request = new XMLHttpRequest();

request.open("POST", "192.168.64.2/testJsRequest.php", true);

request.onreadystatechange = function() {
    if (request.readyState == 4 && request.status == 200) {
        console.log("RESPONSE: " + JSON.parse(request.responseText).msg);
    }
}

request.send(sendable);

sendable is now a FormData object and we append key/value pairs using the append method. Mozilla has all the details on FormData. The problem here is that you can't send complex nested data.

note: you can create simple indexed arrays just by appending multiple values with the same key.

On the PHP side it would look like this:

<?php
header('Content-type: application/json');
    
$msg =  'Hello ' . $_POST['name'] . '.  Nice to meet you.';

echo json_encode(['name' => 'david', 'msg' => $msg]);
?>

To send more complex data with JSON we can do this:

var data = {
    'names': ['kevin', 'david']
};
var json_str = JSON.stringify(data);
var sendable = new FormData();
sendable.append('data', json_str);

console.log(sendable);
var request = new XMLHttpRequest();

request.open("POST", "192.168.64.2/testJsRequest.php", true);

request.onreadystatechange = function() {
    if (request.readyState == 4 && request.status == 200) {
        console.log("RESPONSE: " + JSON.parse(request.responseText).msg);
    }
}

request.send(sendable);

And the corresponding PHP would look like this:

<?php
header('Content-type: application/json');

$data = json_decode($_POST['data']);

$msg =  'Hello ' . $data->names[0] . '.  Nice to meet you.';

echo json_encode(['name' => 'david', 'msg' => $msg]);
?>
Sign up to request clarification or add additional context in comments.

4 Comments

The PHP function file_get_contents is NOT allowed on the server, wich im using. So this solution doesn't work for me. There has to be another way to get this data!?
Is there any solution including the use of cURL?
I can say for sure cURL is not going to help here since it makes outgoing connections you are trying to get data that is sent with an incoming request. Your other options are found in the $_REQUEST superglobal. Data can be set and sent to PHP from javascript through GET, POST and COOKIEs. I will update my answer with a POST example.
I really appreciate your help, thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.