Shuyinsama
Shuyinsama

Reputation: 326

write json to a file using jQuery and Ajax and PHP

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!

Upvotes: 0

Views: 3877

Answers (2)

SixteenStudio
SixteenStudio

Reputation: 1026

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.

Upvotes: 1

PaulProgrammer
PaulProgrammer

Reputation: 17710

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

Upvotes: 0

Related Questions