简体   繁体   中英

saving json data to json file using ajax PHP

My json file looks like this:

count_click.json

[
  {
    "link": "google.com",
    "count": 2  
  },
  {
    "link": "yahoo.com",
    "count": 3
  }
]

now I open this file using

$.getJSON('count_click.json',function(data){

    // do something with data

   var stringData = JSON.stringify(data);

    $.ajax({
    type: 'POST',
    contentType: 'application/json; charset=utf-8',
    url: 'http://127.0.0.x:3xx9/update.php',
    data: {stringData: stringData},
    success : function(d){
       alert('done');}            
    })

}) // end of getJSON function 

update.php

<?php
$a = file_get_contents("php://input");
file_put_contents('http://127.0.0.x:3xx9/count_click.json', json_encode($a));
?>

I get error in the browser console:

POST http://127.0.0.x:3xx9/update.php 404 (Not Found)

But the file is there. When I go to this http://127.0.0.x:3xx9/update.php in the browser, I see the contents of the php fine perfectly fine.

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...).

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM