0

I wont create a JSON file and save this with a php script. I got this error message (Firefox)

NS_ERROR_XPC_JSOBJECT_HAS_NO_FUNCTION_NAMED: JavaScript component does not have a method named: "available"'JavaScript component does not have a method named: "available"' when calling method: [nsIInputStream::available]

When i use Chrome I didn't get the error message but it doesn't work too.

JavaScript:

var jsonString = '{ "foo": 1, "bar": { "baz" : 1 } }';
var data = JSON.parse( jsonString );
var xhr = new XMLHttpRequest();     
xhr.open('POST', './php/upload.php', true);
xhr.send(data); 

PHP:

$dateiname = "test12345.json"; 

if (isset($_POST) && count($_GET)==0) { 

    $jsonObj = $_POST; 
    $fh = fopen($dateiname, 'w'); 
    $input = json_encode($jsonObj); 
    fwrite($fh, $input); 
    fclose($fh); 
}
Rahil Wazir
  • 10,007
  • 11
  • 42
  • 64
JonasB
  • 1
  • 2
  • 1
    The error is telling you that you're trying to call a function called "available", but it doesn't exist. In the Javascript you provided, there isn't any mention of this function so you'll need to find it and add it to your question. – ecnepsnai Jul 02 '14 at 20:57
  • this has nothing to do with PHP. It's purely a client-side Javascript problem. – Marc B Jul 02 '14 at 20:57
  • try doing `xhr.send(JSON.stringify(data))` - from the solution that worked here for a similar question http://stackoverflow.com/questions/15772920/firefox-exception-javascript-component-does-not-have-a-method-named-available – dave Jul 02 '14 at 20:58
  • 2
    It is not clear to me where you error is being generated nor how the PHP code relates to the javascript. Also there does not seem to be any reason to use JSON in your javascript. Just remove the single quotes and the string and you get a javascript object literal saving the step of needing to parse JSON. – Mike Brant Jul 02 '14 at 20:59
  • Can you send an object through XHR that way though? i was under the impression it needs to be a string. either a param string, or a json string. – Kevin B Jul 02 '14 at 21:05
  • The argument to `xhr.send()` must be a string, not an object. And in PHP, `$_POST` is an array constructed from URL-encoded `param=value&param=value` parameters. If you want to read the raw post data, you have to use the `php://stdin` filename. – Barmar Jul 02 '14 at 21:15

1 Answers1

0

The Javascript should use:

xhr.send(jsonString);

because the data being sent must be a string, not an object.

In PHP, to read the raw post data, you should use:

$rawjson = file_get_contents("php://stdin");
$jsonObj = json_decode($rawjson);

$_POST can only be used for form data that's formatted using URL-encoding or multipart/form-data encoding.

Barmar
  • 741,623
  • 53
  • 500
  • 612