0

I encoded an array into JSON in javascript:

var data = JSON.stringify(cVal);

And here is my ajaxrequest object:

function ajaxRequest(url, method, data, asynch, responseHandler){
var request = new XMLHttpRequest();
request.open(method, url, asynch);
if (method == "POST")
    request.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); 
request.onreadystatechange = function(){
if (request.readyState == 4) {
    if (request.status == 200) {
        responseHandler(request.responseText);
        }
    }
};
request.send(data);
}

and I send the json to php with this ajaxrequset:

ajaxRequest("setOrder.php","POST", data , true , dosetOrder);

in php side:

$array=$_POST['data'];

but system says that the data in a undefined index in php

3

1 Answer 1

1

Create an object and stringify to json

var data = {};
data["username"] = username;
data["password"] = password;
var jsonData = JSON.stringify(data);

Send it to your endpoint

function ajaxRequest(url, method, data, asynch, responseHandler){
  var request = new XMLHttpRequest();
  request.open(method, url, asynch);
  if (method == "POST")
    request.setRequestHeader("Content-Type","application/json"); 
  request.onreadystatechange = function(){
    if (request.readyState == 4) {
      if (request.status == 200) {
        responseHandler(request.responseText);
      }
    }
    request.send(data);
}

decode it at your endpoint

plain PHP

$body = json_decode(file_get_contents("php://input"), true);
echo $body["username"];

Slim Framework PHP

//example with Slim PHP framework
$body = json_decode($app->request->getBody(), true);
echo $body["username"];
Sign up to request clarification or add additional context in comments.

3 Comments

Which crystal ball told you about $app->... in OP's code?
it's an example using Slim PHP framework as the code comment tells you, I only tried to show how you get the values from your parsed object.
I added a plain php example to make it more general.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.