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

prtdomingo
  • 971
  • 4
  • 14
Boming YU
  • 61
  • 6
  • 2
    change request header content type to json and what is the problem you are getting ? – M A SIDDIQUI Jan 31 '17 at 09:58
  • 1
    http://stackoverflow.com/questions/8599595/send-json-data-from-javascript-to-php decode your json in php http://stackoverflow.com/questions/23750661/send-json-object-from-javascript-to-php – prasanth Jan 31 '17 at 09:59
  • 1
    What is the output of this on PHP? print_r($_POST); – bilgec Jan 31 '17 at 10:09

1 Answers1

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"];
nebulak
  • 146
  • 5