javascript - json from js to php - failed to open stream: http request failed -
i trying send json data js php, , pass mongo rest.
the following outputs json string (that works fine later if put string in php file, please see snippet below).
js send json:
var s = json.stringify(send); //s contains previous data in arrays, etc ic(s); function ic(s){ var ajaxurl = './im.php'; $.getjson(ajaxurl, {da: s}, function(data) { console.log (data); }); }
in im.php:
$s = $_get["da"]; // <-- doesn't work //$s = '{"r":"pax","c":1,"w":["kiwi","melon"],"g":["cat","dog"]}'; //<-- works fine $opts = array( "http" => array( "method" => "post", "header" => "content-type: application/json", "content" => $s, ), ); $context = stream_context_create($opts); $result = file_get_contents("https://api.mongolab.com/api/1/databases/$db/collections/$collection?apikey=$key", false, $context); var_dump($result); // dumps response document
at firefox debugger, can see file being called, no data added.
error_log file created: failed open stream: http request failed! http/1.1 400 bad request
i tried urlencode($s) in php, still not working. $db, $collection , $key defiend in php, no problem there.
what missing?
basically json.stringify(send) function designed in such way make json getting.
json.stringify(value[, replacer[, space]])
you should use function properly. read docs know more. useful if have input value js array or js object can converted single string.
you getting '{/"r/":/"pax/",/"c/":1 in case if trying stringify json in string format.
these:
var s = ['1','2','3']; , var s = "['1','2','3']";
are totally different things.
if sending array or json object can send directly using code above. example :
send = {"r":"pax","c":1,"w":["kiwi","melon"],"g":["cat","dog"]}; ic(send); function ic(s){ var ajaxurl = 'im.php'; $.getjson(ajaxurl, {da: s}, function(data) { console.log (data); }); }
make sure handle array @ php side properly. if want return json, do:
$s = $_get["da"]; //this array. var jsonobject = json_encode($s);
or can stringify there , provide.
or else send string , use json_decode make json in php
Comments
Post a Comment