saving json data to json file using ajax PHP

前端 未结 2 1359
伪装坚强ぢ
伪装坚强ぢ 2021-01-17 02:45

My json file looks like this:

count_click.json

[
  {
    \"link\": \"google.com\",
    \"count\": 2  
  },
  {
    \"link\": \"yah         


        
相关标签:
2条回答
  • 2021-01-17 02:55

    You could edit your PHP:

    <?php
        $a = $_POST['stringData'];
        // you should check $a consists valid json - what you want it to be
        file_put_contents('count_click.json', $a);
    

    You really should check that posted data to be valid and not saving something unwanted. Also you could check that request really is POST -> $_SERVER['REQUEST_METHOD'].

    Maybe you find some other methods to improve security (for example only allow post from own domain...).

    0 讨论(0)
  • 2021-01-17 03:17

    A few problems.

    file_get_contents("php://input"); Why? You are already sending a Post with data, no need to complicate things with a stream.

    Also file_put_contents needs the path to the actual file on disk, not a URL!

    data: {stringData: stringData} from your AJAX request means you can access it on your server with $data = $_POST['stringData'];.

    Simply echo something out to see if you are actually getting anything.

    echo json_encode( array("Payload" => $_POST['stringData']) );

    If that doesn't work, try accessing the endpoint with your browser (not the file as that does not need PHP for the browser to read it).

    Point your browser to http://127.0.0.x:3xx9/update.php and on your server, simply

    echo "Request received!";

    If you see that in your browser, your endpoint is working and you can continue troubleshooting. If you don't, then this is beyond JS and PHP and probably has to do with your server's settings. If you are using RStudio's Shiny Server, then that does not work for PHP

    In any case, your endpoint should always return something when called. Not just save the file. It is just good practice.

    header("HTTP/1.1 200 OK");

    0 讨论(0)
提交回复
热议问题