Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm trying to write a json file based upon a filled in Form

So I used an external Library for jquery that converts the Form into legitimate JSON. When I console.log that output I do get a valid json data returned.

So whenever I pass the data into a php using $.ajax and write the content to a file the PHP saves the file but the inside it just says "NULL"

here is my AJAX:

$(document).ready(function() {
    var json = $("#user-form").serializeJSON();
    $.ajax({
        url: "writejson.php",
        type: "POST",
        data: json,
        processData: false,
        contentType: 'application/json'
    });
})

And here is my PHP:

<?php
    $myFile = "kiosk.json";
    $fh = fopen($myFile, 'w') or die("can't open file");
    fwrite($fh,var_export($_POST['data'], true));
    fclose($fh);
?>

and here is what the outputted file says:

NULL

I tried looking it up here first and tried numerous options but none of them seem to save the correct data. really strange.

Thanks in advance!

share|improve this question
 
$_POST['data'] is null, as expected. You aren't sending post data, you're sending a string as the request body. –  Kevin B Jul 11 at 15:38
 
This was true, this and the post below I had to stringify the json first. –  Shuyinsama Jul 11 at 21:52
add comment

2 Answers

up vote 1 down vote accepted

You could always change your json string from this

 var json = $("#user-form").serializeJSON();

to this

 var json = {data: $("#user-form").serializeJSON()};

That way when you try to retrieve $_POST['data'], it will actually be set because you defined it.

EDIT: Important point by Shuyinsama - pointed out that you have to use the JSON.stringify method on JSON objects before posting them to PHP:

In my case this is what I did:

var jsontext = JSON.stringify($("#user-form").serializeJSON());

var json = {data: jsontext};

and then use the first PHP file to write it into a valid JSON file.

And always remember you can use the json_decode(); within PHP if you ever need to do some processing on your JSON data, and json_encode();, respectively.

share|improve this answer
 
Same problem the output is just NULL –  Shuyinsama Jul 11 at 21:29
add comment

Unless there's a post variable called "data", this will return null. You might want to try http_get_request_body()

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.