Sai Sudharsanan
Sai Sudharsanan

Reputation: 1

split JSON data from PHP to three arrays in JavaScript

I am passing values from PHP Script to JS using JSON encode.

$arr=array('X'=>$X,'Y'=>$Y,'par'=>$par);
echo json_encode($arr);

Which produces

{"X": ["-0.9537121038646844","-0.9537121038646844","-0.9537121038646844","0.9537121038646843",""],
 "Y": ["-0.9537121038646844","-0.7799936811949519","-0.5533396521383813","-0.37962122946864896",null],
 "par": ["0.009811016749950838","0.005007306592216437","5.058030686503405E-4","9.451402320405391E-4",null]}

In the javascript, I used the following command

{
   $.post("plot.php",param,function(data){dataType:"json";console.log(data);Var X1=data.X;});
}

But I am not able to obtain the values of X alone. I tried few suggestions from similar threads, but none of them did the trick.I need the three arrays, X,Y and Par to be used in JS.

Upvotes: 0

Views: 644

Answers (2)

Misters
Misters

Reputation: 1347

If you are using php you have to specify at the last parameter of post fn that is json type:

$.post("plot.php",param, function(data){ 
 console.log(data);
 var X1=data.X;
},'json');

Upvotes: 1

ComFreek
ComFreek

Reputation: 29434

Try this:

$.post("plot.php", param, function(data) {
    console.log(data);
    var X1 = data.X;
  },
  "json"
);

You can also use $.ajax (which is the function $.post internally calls):

{
  $.ajax({
    type: "POST",
    url: "plot.php",
    dataType: "json",
    data: param,
    success: function(data) {
      console.log(data);
      var X1=data.X;
    }
  });
}

Upvotes: 1

Related Questions