0

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!

2
  • $_POST['data'] is null, as expected. You aren't sending post data, you're sending a string as the request body. Commented Jul 11, 2013 at 15:38
  • This was true, this and the post below I had to stringify the json first. Commented Jul 11, 2013 at 21:52

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Same problem the output is just NULL
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.