2

I have this function that is supposed to pass array to the test1.php on the server but I keep getting an error

Error while processing response: SyntaxError: Unexpected end of JSON input

I found out that this messages shows that my javascript input is ,well , not right. It occurs mostly due to the missing quotations, commas and so. However I don't see a problem with my input

mainpage.php:

function updatePHPScript() {
            var passArrayJSON = JSON.stringify(passArray); // Console: {month: Array(1), number: Array(1)}
            console.log("passArrayJSON:", passArrayJSON); //Console: {"month":["2018-01"],"number":["0000000000"]} - actual input that I'm trying to pass

            fetch("test1.php", {
                method: "POST",
                headers: {
                    'Content-Type': 'application/json'
                },
                body: passArrayJSON 
            })
            .then(response => response.json()) 
            .then(data => {
            console.log("Full Response Data:", data); 
            console.log("Response Message:", data.message);
            const phoneCountElement = document.getElementById('phone-count');
            // Access and display specific values from the response data
            phoneCountElement.innerHTML = data.message;
            })
            .catch(error => {
                console.error("Error while processing response:", error);
            });
        }

test1.php:

if (isset($_POST["passArray"])) {
    $passArrayJSON = $_POST["passArray"];
    $passArray = json_decode($passArrayJSON, true);

    $months = $passArray["month"];
    $clientNumbers = $passArray["number"];

    $response = array(
        "message" => "Hello from the server!"
    );

    header('Access-Control-Allow-Origin: *');
    header('Content-Type: application/json');

    echo json_encode($response);

So this is how my input looks {"month":["2018-01"],"number":["0000000000"]} but I cannot see what is wrong with it.

I simplified my test1.php so there is no direct use of data I'm passing, but since it's in the if statement, I suppose that I should get my response message if there is not other problem

Ice
  • 23
  • 6
  • Please may you share an example of what the PHP generated JSON looks like? – evolutionxbox Aug 21 '23 at 08:58
  • I suggest you log `$passArrayJSON` in test1.php before trying to decode it. – Jon Skeet Aug 21 '23 at 08:59
  • @evolutionxbox response looks like this {"message":"Hello from the server!"} but i have to put it out of If statement and modify my javascript to jest get value without input otherwise I get an error – Ice Aug 21 '23 at 09:02
  • @Ice What do you echo/return in case `if (isset($_POST["passArray"]) { ...` evaluates to `false`? And since you already mentioned that it works if you _remove_ the mentioned `if (isset( ... )) { ...` stuff, it's likely that `$_POST["passArray"]` is _empty_. So I'd guess that the JSON string you pass to PHP isn't available via `$_POST`... – David Aug 21 '23 at 09:05
  • @David currently nothing but I tried something like "message" => "FAILED!" with the same structure like when it success and I got that 'failed' message, that's how Ifigured out that there is something wrong with my input – Ice Aug 21 '23 at 09:11
  • As I said, I'd guess that `$_POST` does not contain the JSON string you sent to PHP and therefor `isset($_POST["passArray"])` results in `false`. Have you seen [this answer](https://stackoverflow.com/questions/8599595/send-json-data-from-javascript-to-php) where `file_get_contents('php://input')` is used instead of `$_POST` to access the JSON handed to the backend? – David Aug 21 '23 at 09:15
  • @David I pass this where number and month are arrays {"month":["2017-12"],"number":["572399532"]}, if its not available via $_POST how else can I receive it. – Ice Aug 21 '23 at 09:16
  • I haven't see it, I will check it now – Ice Aug 21 '23 at 09:17
  • Related: [Fetch post with body data not working params empty](https://stackoverflow.com/q/39842013/2943403) or [fetch API not sending data via post](https://stackoverflow.com/q/54270081/2943403) or [Parse Javascript fetch in PHP](https://stackoverflow.com/q/35091757/2943403) – mickmackusa Sep 02 '23 at 08:09
  • Or [Body not sent in "fetch" POST request and (my) solution](https://stackoverflow.com/q/52814151/2943403) or [Fetch doesn't send post data](https://stackoverflow.com/q/55250688/2943403) or [Fetch API POST, not sending
    data](https://stackoverflow.com/q/61152215/2943403)
    – mickmackusa Sep 02 '23 at 10:10

1 Answers1

1

Try reading the input stream. Post bodies when not submitted via form and form encoded, can be "anything" You also don't assign it to any variable "passArray" that apache/nginx/php could decode as a parameter to populate $_POST with.

So reading from the input stream would help.

$input = file_get_contents("php://input");

if ($input) {
    $passArray = json_decode($input, true);

    $months = $passArray["month"];
    $clientNumbers = $passArray["number"];

    $response = array(
        "message" => "Hello from the server!"
    );

    header('Access-Control-Allow-Origin: *');
    header('Content-Type: application/json');

    echo json_encode($response);
}

Tschallacka
  • 27,901
  • 14
  • 88
  • 133
  • 1
    When I use that instead of $_POST it works now, thank you – Ice Aug 21 '23 at 09:38
  • 1
    This answer is not needed. https://stackoverflow.com/a/55250858/2943403 – mickmackusa Sep 02 '23 at 08:14
  • 1
    [The fundamental goal of closing duplicate questions is to help people find the right answer by getting all of those answers in one place.](https://stackoverflow.com/help/duplicates#:~:text=The%20fundamental%20goal%20of%20closing%20duplicate%20questions%20is%20to%20help%20people%20find%20the%20right%20answer%20by%20getting%20all%20of%20those%20answers%20in%20one%20place.) – mickmackusa Sep 02 '23 at 10:11