0

I am attempting to write a Json file to the server. The Object is created in Javascript and passed to PHP via Ajax. PHP will then write the data to a file on the server.

The problem I am having is Passing the object to PHP. Creating the Object is OK, as is writing to a file.

I have tried a wide variety of methods to pass the object (Post, Get, urlencoded, not urlencoded, stringified or not), but the PHP either gets "[object,object]" or nothing at all.

    var testData = [{"name": "Foo"},{"name": "Bar"}];

    $.ajax({
        url         : "include/WriteFile.php?json",
        type        : 'post',
        data        : JSON.stringify(testData),
        dataType    : 'application/json', 
        processData : false
        });

-- WriteFile.php

<?php
$json = $_GET['json'];


$jsonData = json_decode($json,false);
    // echo $jsonData;

    $myFile = "../myFile.json";
    $file = fopen($myFile, 'w') or die("can't open file");

    fwrite($file, $jsonData);  // Write file

    fclose($file);
?>

--

//  Header Info //
Parameters    application/x-www-form-urlencoded
[{"name":"Foo"},{"name":"...    
Source
%5B%7B%22name%22%3A%22Foo%22%7D%2C%7B%22name%22%3A%22Bar%22%7D%5D

xdebug is showing that both $_GET and $_RESPONSE are empty (Value = "").

Any help will be greatly appreciated.

  • Of course `$_GET` is empty ... you're using `type: 'post'` ... try changing `$_GET` to `$_POST` – SpYk3HH Jun 18 '14 at 14:31
  • also, your data doesn't quite look rite. I think you're going to end up with `$_POST['Foo']` equaling `NULL`. I could be wrong, but proper format would be `[{ name: 'Foo', value: 'Bar' }]`. Where then `$_POST['Foo']` would give you `String "Bar"`. Also, if you use that format, you dont need `JSON.stringify`. jQuery will send it through correctly as is using the Array I suggested. – SpYk3HH Jun 18 '14 at 14:34
  • Thanks, I think I mis-wrote my data when I got it ready to ask the Question here. My actual json is about 75 records. – user2221845 Jun 18 '14 at 14:39
  • no prob, you might really want to also look at http://api.jquery.com/serializeArray/ && http://api.jquery.com/serialize/ – SpYk3HH Jun 18 '14 at 14:44
  • **OK, I Got It!** My Data was OK. The issue was that neither $_GET or $_RESPONSE where the correct choice. I needed file_get_contents('php://input'). After that, all works fine. – user2221845 Jun 18 '14 at 16:14

0 Answers0