JS AJAX POST to PHP, edit JSON file is giving errors

post function in js:

        var srcd = document.getElementById("pictwo").src;

        $.ajax({
          type: "POST", //type of method
          url: "/file.php", //your page
          data: {
            src: srcd
          }, // passing the values
          success: function(res) {
            location.reload(); //do what you want here...

          }

        });
      }

file.php:

<?php
header('Access-Control-Allow-Origin: *');

$src = $_POST["src"];
$jsonString = file_get_contents('jsonFile.json');
$data = json_decode( $jsonString, true );

foreach ( $data as $key => $entry )
{
        if ( $entry['src'] == $src )
        {
                $data[$key]['counter']++;
        }
}
$newJsonString = json_encode( $data );
file_put_contents( 'jsonFile.json', $newJsonString );

?>

I know that the POST is successful, because I added a console.log(srcd) to the js function, and it was the desired value.

jaonFile.json:

[
        {
            "src": "https://",
            "counter": "0"
        },
        {
            "src": "https://",
            "counter": "0"
        },
        {
            "src": "https://",
            "counter": "0"
        },

The error in error_logs is :

PHP Warning: Invalid argument supplied for foreach() in /file.php on line 8

After the function is called, the json file is changed to null.

Why is this happening?

How can I fix this?

Thank you.

A post was merged into an existing topic: PHP error while incrementing values in JSON file

Sponsor our Newsletter | Privacy Policy | Terms of Service