3

Here is the code: (the #debug div text is shown below)

$("#debug").text(JSON.stringify(data));
// Try to save to a file
$.ajax({
    type: 'POST',
    url: './json.php',
    dataType: 'json',
    data: JSON.stringify(data),            
    success: function(xhr, status, errorMessage) {
        if( xhr.responseText == "Success" ) {
            alert("Success!");
        } else {
            alert("response was "+xhr.responseText);
        }
    },
    error: function(xhr, status, errorMessage) {
        $("#debug").append("RESPONSE: "+xhr.responseText+", error: "+errorMessage);
    }
});

The JSON.php page is:

<?php
openlog("scriptLog.txt", LOG_PID | LOG_PERROR, LOG_LOCAL0);
   $json = $_POST['json'];
// open syslog, include the process ID and also send
// the log to standard error, and use a user defined
// logging mechanism
    syslog(LOG_DEBUG, "Received Data");

   if (json_decode($json) != null) { /* sanity check */
    $file = fopen('./data.json','w+');
     fwrite($file, json_decode($json));
     fclose($file);
   } else {
     syslog(LOG_DEBUG,"Failure");
     return "Failure, json decode is null";
   }
   closelog();
   return "Success";
?>

In the log I get:

Mar 14 14:50:54 scriptLog.txt[21902] : Received Data

Mar 14 14:50:54 scriptLog.txt[21902] : Failure

In the debug div text I get:

{"1457981454959":{"id":1457981454959,"code":"1","title":"Test","date":"22/03/2016","description":"a Task"}}RESPONSE: , error: SyntaxError: JSON Parse error: Unexpected EOF

1) How can I examine the posted data? I.e. "Received Data: "+WHAT in syslog to see its structure. 2) JSON parse error? Most examples I see use this stringify function. then they use json_decode to get the values. Why the parse error?

John Wooten
  • 685
  • 1
  • 6
  • 21
  • Why would you have something called `_POST['json']`, you're just sending a string with no keys, and it doesn't look like the sent JSON even has a key with that name? Also, the parse error is because you're using `dataType:json`, which expects to get JSON back from the server, but instead it just gets a regular string saying `Success` etc. – adeneo Mar 14 '16 at 19:13
  • So, how would I send the data as a JSON string? How should I return the response? – John Wooten Mar 14 '16 at 19:15
  • Just send the object -> `data:data` and jQuery will turn it into `x-www-form` for you so it's available by keys is `_POST`, and make sure you return valid JSON from the server. – adeneo Mar 14 '16 at 19:17
  • 1
    [This](http://stackoverflow.com/questions/8893574/php-php-input-vs-post) might help you. – IROEGBU Mar 14 '16 at 19:54

1 Answers1

1

1) How can I examine the posted data? I.e. "Received Data: "+WHAT in syslog to see its structure.

As I understand you are debugging the code, so syslog can be not the best idea. I would simply use the browser network console to see the content of requests and a simple php file like this to see the content of $_POST:

<?php
   echo json_encode($_POST);

In more complex cases - use the actual debugger.

2) JSON parse error? Most examples I see use this stringify function. then they use json_decode to get the values. Why the parse error?

You are trying to use the json key in your $_POST, but you didn't instruct jQuery to add it, so you are receiving not what you expected.

There are few issues with your $.ajax call, here is the commented version:

$.ajax({
    type: 'POST',
    url: './json.php',
    dataType: 'json', // Note: dataType is only important for the response
                      // jQuery now expects that your server code
                      // will return json

    // here you need to add the 'json' key
    data: {'json': JSON.stringify(data)},       

    // the success method has different order of parameters      
    //success: function(xhr, status, errorMessage) {
    success: function(data, status, xhr) {
        alert("response was "+data);
    },
    error: function(xhr, status, errorMessage) {
        $("#debug").append("RESPONSE: "+xhr.responseText+", error: "+errorMessage);
    }
});

Now on the server you will have $_POST['json'] with serialized string and you can json_decode it.

Alternatively you can send the JSON data without serialization:

var data = {'test': 'abc'};

$.ajax({
    type: 'POST',
    url: './json.php',
    // No 'JSON.stringify()', just send your data
    data: data,
    ...
});

And on the server you will have $_POST['test'] with abc value (so you have your json already converted into array).

Borys Serebrov
  • 15,636
  • 2
  • 38
  • 54