0

I am calling a php page (using PHP7.0) from javascript (on Chrome Version 67.0.3396.99). Reading around the web, I used a code example. Passing a json string through PUT to php is supposed to deliver a $_POST variable that is a map.

{"a":"A","b":"B","c":"C"} becomes

$_POST = [ "a" => "A", "b" => "B", "c"=>"C" ]

However, in my code below, javascript passed instead

$_POST = [ "{"a":"A","b":"B","c":"C"}" : "" ]

This is bizarre. If not a map, I would have expected a String

Did I do something wrong? This is a little nerve-wracking to think the code is unreliable for production. Or perhaps there is a better approach?

javascript:

function testeroo(){
 json_ = '{"a":"A","b":"B","c":"C"}'
 jQuery.ajax({
 type: "POST",
 url: './test.php',
 data: json_,
 success: function (obj) {
 alert(obj); 
 },
 error: function () {
 alert("ERROR testeroo");
 }
 });
}

test.php confirms this:

foreach ($_POST as $key => $value){
 $zeroKey = $key; 
 //only one key, so $zeroKey is only key
}
$j = json_decode($zeroKey);
 //$j is the expected map
asked Aug 24, 2018 at 12:50

2 Answers 2

4

your json_ is string, remove ''

 json_ = {"a":"A","b":"B","c":"C"}
answered Aug 24, 2018 at 12:53
Sign up to request clarification or add additional context in comments.

Comments

0

two solutions:

1

as suggested by the other user:

remove '' from your json string

2

if you want to use a string you must also use the function JSON.parse()

Example

 var json_= '{"a":"A","b":"B","c":"C"}';
 json_= JSON.parse(json_);
answered Aug 24, 2018 at 12:58

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.