I send an ajax request with jquery like this:
$.post("ajax/myFile.php", {
myValue: "test"
}, function(response) {
console.log($.parseJSON(response))
})
content of myFile.php
myFunctionA();
myFunctionB();
function myFunctionA() {
echo json_encode(array('error' => 0, 'message' => "Hello World"));
}
function myFunctionB() {
echo json_encode(array('error' => 0, 'message' => "Hello again"));
}
my console.log result:
Uncaught SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 44 of the JSON data
how can I handle this? :/
You can't return multiple JSON values from your script. You need to combine them into a single value.
echo json_encode([myFunctionA(), myFunctionB()]);
function myFunctionA() {
return array('error' => 0, 'message' => "Hello World");
}
function myFunctionB() {
return array('error' => 0, 'message' => "Hello again");
}
This will return both results as elements of an array in JavaScript.
Related
This question already has answers here:
adding data into json with PHP
(2 answers)
Closed 3 years ago.
hello I made a post method with the API, I want to make a response like the following what can?
{
"status": 200,
"error": false,
"data": [
{
"id_kab": "56",
"id_prov": "1",
"kd_kab": "CGK10000"
}
]
}
what I did through POSTMAN now results like this
{
"id_kab": "56",
"id_prov": "1",
"kd_kab": "CGK10000"
}
this my code insert to database
public function submit_post() {
$data = array(
'id_kab' => $this->input->post('id_kab'),
'id_prov' => $this->input->post('id_prov'),
'kd_kab' => $this->input->post('kd_kab')
);
$insert = $this->db->insert('service', $data);
if ($insert) {
$arr=array(
'status' => 200,
'message' => 'Success'
);
header('Content-Type: application/json');
echo json_encode($arr,TRUE);
} else {
$this->response(array('status' => 'fail', 502));
}
}
how to change the response? thank you
From the response given, data should be given as an array, So please try the below code
$output = array();
$data = array();
$data[] = array(
'id_kab' => $this->input->post('id_kab'),
'id_prov' => $this->input->post('id_prov'),
'kd_kab' => $this->input->post('kd_kab')
);
$output["data"] = $data;
$output["status"] = 200;
$output["error"] = false;
echo json_encode($output); exit;
OutPut is as follows
{
"status": 200,
"error": false,
"data": [{
"id_kab": "56",
"id_prov": "1",
"kd_kab": "CGK10000"
}]
}
Demo
I'm iterating over an array of objects, some of them nested in a non-uniform way. I'm doing the following:
foreach($response['devices'] as $key => $object) {
foreach($object as $key => $value) {
echo $key . " : " . "$value . "<br>";
}
}
Which works...until it hits the next embedded array/object, where it gives me an 'Notice: Array to string conversion in C:\xampp\htdocs\index.php on line 65' error
I'm relatively new to PHP and have thus far only had to deal with uniform objects. This output is far more unpredictable and can't be quantified in the same way. How can I 'walk' through the data so that it handles each array it comes across?
You should make a recusive function this means, the function call itself until a condition is met and then it returns the result and pass through the stack of previously called function to determine the end results. Like this
<?php
// associative array containing array, string and object
$array = ['hello' => 1, 'world' => [1,2,3], '!' => ['hello', 'world'], 5 => new Helloworld()];
// class helloworld
class Helloworld {
public $data;
function __construct() {
$this->data = "I'm an object data";
}
}
//function to read all type of data
function recursive($obj) {
if(is_array($obj) or is_object($obj)) {
echo ' [ '.PHP_EOL;
foreach($obj as $key => $value) {
echo $key.' => ';
recursive($value);
}
echo ' ] '.PHP_EOL;
} else {
echo $obj.PHP_EOL;
}
}
// call recursive
recursive($array);
?>
This prints something like this :
[
hello => 1
world => [
0 => 1
1 => 2
2 => 3
]
! => [
0 => hello
1 => world
]
5 => [
data => I'm an object data
]
]
I hope this helps ?
I will create a json file with PHP with json_encode. I intend to include a function that I will call inside array before I change it to json. Whether calling functions inside an array can be done?
$arrayList = array(
array(
'uid' => "1234",
'nilai' => getBoolean (1)));
function getBoolean ($value) {
if ($value == 0 ) {
echo "false";
} else {
echo "true";
}
}
echo json_encode ($arrayList);
Output json
true[{"uid":"1234","nilai":null}]
What if I want json output like below
[{"uid":"1234","nilai":true}]
So the value of the function (getBoolean) goes into json not outside. Thanks
PHP uses an applicative order evaluation strategy so getBoolean(1) will be evaluated before the array is assigned to $arrayList.
However, you have a bug in your getBoolean function. You need to return a boolean type value, not the string version of the boolean.
Code: (https://3v4l.org/AOdn3B)
$arrayList = [ [ 'uid' => '1234', 'nilai' => getBoolean (1) ] ];
function getBoolean ($value) {
return (bool) $value;
}
echo json_encode ($arrayList);
Output:
[{"uid":"1234","nilai":true}]
p.s. I wouldn't personally bother to write a custom function for this. Just prepend (bool) directly to your array value.
$arrayList = [ [ 'uid' => 1234, 'nilai' => (bool) 1 ] ];
Then again if you have negative numbers or some other fringe case, use:
if ($value == 0) {
return false; // boolean, not string
} else {
return true; // boolean, not string
}
I am trying to display data for a plugin with a predefined json format, but after I try the data does not match the format how the problem?
JSON Required
[
{
latLng: [-6.17343444,1206.834234294],
name: 'XY'
},
{
latLng: [-6.1742343244,106.898987294],
name: 'XK'
}
]
Result my JSON
[
{
"latLng": "-6.17343444,1206.834234294",
"name": "XK"
},
{
"latLng": "-6.1742343244,106.898987294",
"name": "XY"
}
]
myscript PHP
public function lat_lang() {
foreach($this->model->name_model() as $row){
$data[] = array(
'latLng' => $row->lat_long,
'name' => $row->city
);
}
header('content-type: application/json');
echo json_encode($data);
}
call JSON
$.parseJSON('<?php echo base_url().'mycontrollers';?>', function(datas) {
console.log(datas);
});
You can use explode() to transform the string "-6.17343444,1206.834234294" into an array [-6.17343444,1206.834234294]:
public function lat_lang() {
foreach($this->model->name_model() as $row){
$data[] = array(
'latLng' => explode(',',$row->lat_long),
'name' => $row->city
);
}
header('content-type: application/json');
echo json_encode($data);
}
If you want to get floats (for all value in the JSON), you could use JSON_NUMERIC_CHECK:
json_encode($data, JSON_NUMERIC_CHECK);
Or, just for a specific value:
$latLng = explode(',', $row->lat_long);
$latLng = array_map('floatval', $latLng);
$data[] = array(
'latLng' => $latLng,
'name' => $row->city
);
First, im new in PHP so please bear with me.
Im creating a web service for android, and this is my code :
if($size > 0)
{
$resultArray = array();
foreach($result as $child)
{
if($child)
{
//add to array
$resultArray[] = array('result' => 'true',
'total' => $size,
'id' => $child['id'],
'user_id' => $child['user_id'],
'name' => $child['name'],
'gender' => $child['gender'],
'born_date' => $child['born_date'],
'born_hour' => $child['born_hour'],
'hospital' => $child['hospital']);
}
}
$this->response($resultArray, 200);
}
else
{
$this->response(array('result' => 'false'), 404);
}
I use the size to validate whether the result is OK 200 (has some data) or error 404. However, there is a possibility that the result's size is 0 (no data) but the result is OK (code 200). How to tell the different?
I tried to use boolean variable instead of $size, but its not working.
Thanks for your help.