Decoding json object retrieved from PHP in Javascript - javascript

I am having trouble using the json object echoed from php to javascript. In the php file I define
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
echo($json);
and then in javascript file I want to access this object.
$("#test_btn").click(function() {
$.get("serverside.php", function(data, status) {
console.log("data " , data["a"]); //undefined
console.log(JSON.parse(data)); // error
});
});
I get undefined for data["a"] and an error for JSON.parse. How should I use the returend data?

Based on your comment (echoing several json strings), you should do the following:
Initialize an empty results array;
Read your file and put it in an array or object using json_decode();
Add this array / object to your results array;
At the end, use json_encode() to encode and echo out your results array.

You must make a JSON.parse(data) before attempting to access to data['a'], and send a header from PHP that implicitly say the browser that the data output is going to be a JSON.
header ('Content-Type: application/json');

The problem might be that PHP is returning a string that looks like JSON.
In JS it might help to JSON.parse(data) to convert from string to JSON object, then you can access it.
$("#test_btn").click(function() {
$.get("serverside.php", function(data, status) {
$json = JSON.parse(data);
console.log("data " , $json["a"]); // should now return 1
});
});

you need to put json_encode or parse it in javascript

Related

json_decode expects parameter 1 to be string, says array is given. Why doesn't my string pass properly?

So, I've been struggling with this for the entire weekend and I still can't figure out what's wrong. I'm trying to pass some data through json_decode to be able to save it to a file and I keep getting the error it expects a string but an array is given. I'm using jQuery and PHP.
The data I send through the ajax call is, according to console.log(noBrack):
{"ID":2,"LLID":"LLID2","volNaam":"Test - 0","norm":"Zicht","instalDatum":"17-11-2017","endDate":"18-11-2017","serie":"0","klant":"Testklant","file":"data/Testklant (Heerenveen)/LLID2.json","gelDat":"27-10-2018"}
My Ajax call is:
$.ajax({
url: 'quickGrade.php',
type: 'POST',
data: noBrack,
datatype: 'json',
success:function(data){
alert(data );
}
});
My PHP code is:
$testSave = 'data/gradeTest.json';
$decode = json_decode($_POST, true);
file_put_contents($testSave, $decode);
Can anyone find out what I'm doing wrong? I've tested my string with an online json_decode tester and it said it was valid so I'm kinda hardstuck here.
The way you are sending data will give you $_POST array in php code. So actually you do not need to decode because the data is coming as $_POST array not a JSON string.
You should use json_encode to get JSON string to store in file. Because $_POST is an array, so you can't decode it like a Json string.
Your code will become this:
$testSave = 'data/gradeTest.json';
file_put_contents($testSave, json_encode($_POST));
You can read more about:
http://php.net/manual/en/function.json-encode.php
http://php.net/manual/en/function.json-decode.php

Access array posted with Javascript

I'm using the following code to send a form to a php processor:
$(document).ready(function(){
var $form = $('form');
$form.submit(function(){
$.post($(this).attr('action'), $(this).serialize(), function(response){
// do something here on success
},'json');
return false;
});
});
I presume that this sends the form to my php script with all the form values in json format but I then don't know how to then access this json and turn it back into the array i need to process in my PHP script.
Does anyone know how I access this variable in my processor script so I can process the data?
Also, what is the best way for me to view the data being posted so I can work out what to do with it, when I send the data the processor is obviously not displayed, is there a way to echo out/write the information received by the script to I can view it?
You can easily access to the json as an array called "$_POST" in your php.
for example, if you send the form as a json structured like this:
{
"name":"userID",
"psw":"password123"
}
in your php script there will be the variable $_POST with this structure:
$_POST = Array (
"name" => "userID",
"psw" => "password123"
)
EDIT
In a comment you asked me how to display the data received from the server,
that's quite simple,
in your php script just write this:
echo json_encode($_POST);
so that you output the $_POST array in the json format,
then in your script write this:
$.post($(this).attr('action'), $(this).serialize(),
function(data){ //"data" argument will contain the output from the server (that is the encoded $_POST array printed as json with the php code as showed above)
console.log(data); //log data
}
); //as you can see, I've deleted "json", becouse it's unuseful

Return JSON object from php script

I am making an AJAX GET request using jQuery to a PHP file. I want the PHP script to return a JSON object, however, currently it is returning a JSON string. I realise I can use JSON.parse in the jQuery code, however, any experience I have in making an AJAX call to an API a JSON object is returned. I am trying to do the same with the php script however, it is returning a string as opposed to an object.
Does anyone know what the best practice is here, and if the best practise is to return a JSON object how I would do this using PHP?
Please see the code below:
js
$.get('test.php', function(data){
console.log((data));
});
php
<?php
$jsonAnswer = array('test' => 'true');
echo json_encode($jsonAnswer);
In your PHP file, change the content type to application/json.
JS
$.get('/process.php', function(data) {
console.log(data);
} );
PHP
<?php
header( "Content-type: application/json" );
$jsonAnswer = array('test' => 'true');
echo json_encode($jsonAnswer);
Then your console should read Object {test: "true"} rather than just the JSON string.
Add json to the end of your get function to return json
$.get('test.php', function(data){
console.log((data));
},'json');//here
and/or add this header in php
header('Content-Type: application/json');
more info here
Without modifying PHP script you can do:
$.get( "test.php", function( data ) {
var arr = $.parseJSON(data);
console.log(arr);
alert(arr.test);
});

Working with javascript array

Hi I have a php script that successfully gets an array of data from an exsternal xml source, the array is called $file, I know that the php array is populated by using print_r($file).
I have tried to use the following php to pass to a javascript session:
//Convert to JSON Array
$jsonarray = json_encode($file, JSON_FORCE_OBJECT);
$result["json_array"]=$jsonarray;
But either this hasn't worked, or the following JS code below is wrong:
var jsonarray = result["json_array"];
alert(JSON.stringify(jsonarray));
Could someone please tell me where I am going wrong?
You should not use JSON.stringify there. JSON.parse is what you are looking for. Since you want to parse existing JSON, not create new JSON.
edit: Your code is a bit odd. I'd think you want something like this
php
//Convert to JSON Array
echo json_encode($file, JSON_FORCE_OBJECT);
js
alert(JSON.parse(data)); // Where data is the contents you've fetched from the server
You have to encapsulate php code :
<?php
$jsonarray = json_encode($file, JSON_FORCE_OBJECT);
$result["json_array"]=$jsonarray;
?>
var jsonarray = <?= $result["json_array"] ?>;
alert(JSON.parse(jsonarray));

How to access Json type returned from server?

Guys I have this response from server:
{"copy_am_email":"0","locations": [array here ... .....]}
which im pretty sure is a json type (I console logged it). That data above is fetched by ajax:
success : function ( data ) {
alert (data.locations[index]); //I should be able to access locations even without index
}
But my problem is locations is undefined. Or even copy_am_email. I accessed it like this:
data.locations . I even tried this data['locations'].
u have to parse it:
newJSON = JSON.parse( myJson );
i should note that you have the number zero as a string "0" it should just be 0.
Try to parse the JSON data using javascript's native method JSON.parse(data). Then try accessing locations the way you do.

Categories

Resources