php decode json array - javascript

I have a php page that receives a json object from javascript page, but i was not able to decode the json in php. How to decode the json and store in php such that $arr[0]=[1,2,34,5,2]; $arr[1]=[2,1,34,5,2]; $arr[2]=[8,1,34,5,2]; in php ?
after removing "myString = JSON.stringify(myObject);"
echo $value; outputs "Array"
echo $value[0]; outputs nothing
echo $value->{"key"}; outputs nothing either
how can i actually get the array contents?
javascript:
var mon=[1,2,34,5,2];
var tue=[2,1,34,5,2];
var wed=[8,1,34,5,2];
var myObject = {'key' :'value','key2':'value','key3':'value'};
myObject.key = mon;
myObject.key2 = tue;
myObject.key3 = wed;
myString = JSON.stringify(myObject); //this line removed
var jsonString = JSON.stringify(myObject);
$.ajax({
type: "POST",
url: "n3.php",
data: {data : jsonString},
cache: false,
success: function(aaa){
alert("OK");
$("#pageContent").html(aaa);
}
});
php:
<?php
$value = json_decode($_POST['data']);
echo $value; //this echos the whole json object
echo $value->{"key"}; //this outputs nothing
?>

You are JSON encoding your data twice on the Javascript side. When you call json_encode in PHP once, you get a JSON encoded object back. That's why echo $value outputs the whole string. If it was a PHP array at this point it would output "Array" or an error in case it was an object, it would not output the whole content.
Either json_decode it again, or don't double encode it in Javascript.

Related

convert js array to php array and check its content

I want to sent a JS array to remote php server and convert it to a php array.
To check if php array is equal to js array I'm trying to get its members inside result div, but without success.
var rlist = ["title1", "title2", "title3"];
var b = JSON.stringify(rlist);
$.ajax({
url: 'reorder.php',
type: 'post',
data: {'b': b},
success: function(data) {
$("#result").html(data);
}
});
reorder.php
$rlist = json_decode( $_POST['b'], true );
echo $rlist;
try to put this code in the reorder.php
$rlist = json_decode( $_POST['b'], true );
foreach ($rlist as $value) {
echo "<div>" . $value . "</div>";
}
You can use json_decode as jQuery ajax submits it's arrays as json.
// Use as object
$json = json_decode($_POST['postdata']);
// Use as
echo $json->seomthign
$json = $_POST['postdata'];
// Output array
echo "<pre>";
var_dump(json_decode($json));
echo "</pre>";

Ajax read PHP generated json

So I want to send a json to an ajax call but I don't know how to read the json when is sent. And also my json looks strange because of the backslashes...
This is my ajax:
function find(){
var type = $('#object_type').val();
$.ajax({
type : 'POST',
url : 'get_user.php',
data : {
'type' : type
},
dataType : 'json',
error : function(response){
alert('SOMETHING WENT WRONG');
},
success : function(response){
This is what I get as a response:
"[{\"name\":\"Test\",\"link\":\"test.php\"},{\"name\":\"Test2\",\"link\":\"test2
.php\"}]"
}
});
}
This is my PHP function:
$type = $_POST['type'];
$user_array;
$user = mysqli_query($conn, "SELECT name,link FROM user WHERE `type` LIKE '%".$type."%'") or die();
while ($row = mysqli_fetch_array($user, MYSQLI_ASSOC)) {
$row_array['name'] = $row['name'];
$row_array['link'] = $row['link'];
array_push($user_array, $row_array);
}
mysqli_close($conn);
$result = json_encode($user_array, 128);
echo json_encode($result);
First change that you should make :
You don't need to encode two times
$result = json_encode($user_array, 128);
echo json_encode($result);
should be
$result = json_encode($user_array, 128);
echo $result;
Now the response should look like
[{"name":"Test","link":"test.php"},{"name":"Test2","link":"test2
.php"}]
which is a valid Javascript Array and can be accessed using following code :
var len = response.length;
for(i=0;i<len;i++){
console.log(response[i].name);
console.log(response[i].link);
}
As provided in techierishi's answer. Do not encode your response twice. Just do
echo $result;
The JSON should be valid and parsed, why?
json_encode is used on a valid PHP array returned from a MySQLi query.
dataType is used, explicitly forcing jQuery to JSON.parse the response and no errors where raised during that process.
The JSON that is returned has the following structure
ROOT
ARRAY
ARRAY OBJECT
OBJECT PROPERTY
To address something like that:
root[array index].property
Will give you the array's value, which is an object. That object has multiple properties.
[] means array
{} means object
So [{name:"value 1"},{name:"value 2"}] is actually
ARRAY
[0].name = value 1
[1].name = value 2
So retrieving information like name from your JSON will be:
response[0].name; // = test

json string is not converting into object

Here is the server side code I am trying to send json
$x = array();
$timestamp = strtotime('22-09-2008');
$x["x"] = $timestamp;
$x["y"] = 22;
$val = '[{ "name": "weight", "dataPoints": ['.json_encode($x).'] }]';
echo json_encode($val);
So output for above code looks like
"[{ \"name\": \"weight\", \"dataPoints\": [{\"x\":1222041600,\"y\":22}] }]"
Below is the client side code I get the data via Jquery getJSON
var jqxhr = $.getJSON( "https://domain/gettracker.php?id="+id, function(data) {
console.log(data);
})
I suppose getJson converts json to object automatically , but it logs the raw json like below
"[ { name: "weight", dataPoints: [{"x":1222041600,"y":22}] } ]"
I tried to do json parse , but i get error.
I guess I am not sending the data properly via php.Can some one guide me ?
Your JSON string is not valid - the property names should be enclosed in double quotes - ", and you don't need to encode the string again.
$val = '[{ "name": "weight", "dataPoints": ['.json_encode($x).'] }]';
echo $val;
Or better yet, use json_encode to create the string for you:
$data = array(
'name' => 'weight',
'dataPoints' => $x
);
echo json_encode($data);

JSON format issue in JavaScript

Following is my JavaScript code to get JSON data:
$(document).ready(function()
{
$.support.cors = true;
$.getJSON('http://example.com/root_dir/test_json.php', function(data1)
{
alert("data1= "+data1);
});
});
but the above alert shows me JSON in following format-
If I hit my php script URL in browser, it shows JSON data in expected formate as shown below-
[{"name":"AB","std":"7","number":"82"},{"name":"CD","std":"9","number":"90"},{"name":"PQ","std":"12","number":"79"}]
Following is my test_json.php code-
<?php
//Create an array
$json_response = array();
$row_array['name'] = 'AB';
$row_array['std'] = '7';
$row_array['number'] = '82';
array_push($json_response,$row_array);
$row_array['name'] = 'CD';
$row_array['std'] ='9';
$row_array['number'] = '90';
array_push($json_response,$row_array);
$row_array['name'] = 'PQ';
$row_array['std'] = '12';
$row_array['number'] = '79';
//push the values in the array
array_push($json_response,$row_array);
echo json_encode($json_response);
?>
getJSON decodes the JSON into a JavaScript data structure.
Concatenating it with a string will implicitly call toString() on it. That will turn arrays in to a comma-seperated format and plain objects into "[Object object]".
Nothing is going wrong. That is the expected behaviour.
If you want to see the data in JSON format, then use JSON.stringify(data) or use .ajax instead of .getJSON and access the raw text data in the jqXHR object.

json_encode with multidimensional array returning string "array" instead of data

I am passing a multidimensional array back to a .php file using json, jquery, and ajax. My goal is essentially to fill a drop down box (id=project) with multiple entries. Here's some code snippets:
$("#turninId").change(function() {
var user_id = $("#turninId").val();
$.ajax ( {
url:"send_input.php",
type: "POST",
dataType: "json",
data:{id_selection: user_id},
success:function(response) {
for (var i=0; i<response.proj.length; i++) {
$("#exp").html(response.proj[i]);
$("#project").html(response.proj[i]); } });
});
In send_input.php (backend), I query a db, and send the information to an array. Then I use json_encode.
$query="SELECT project FROM main";
$results = $db->query($query);
while ($row_id = $results->fetchArray()) {
$proj_option[] = "<option value=\"".$row_id['project']."\">".$row_id['project']."</option>\n";
$pselected=$row_id['project'];
}
$output = array( "proj" => "$proj_option");
echo json_encode($output);
My problem is that this is RETURNING THE STRING "Array".
For example, if I do: response.proj[0], I get "A" returned.
What gives? I've seen a few people with questions about this error, but no definite solution. Any help?
This is because you are casting $proj_option to a string by enclosing it in quotes. Just remove the quotes and you will get the array.

Categories

Resources