how to create json response status in codeigniter - json

I made json code using json encode, the results are correct, but I want to add a satatus response to the object. How to ?
this my code
public function get(){
header('Content-Type: application/json');
$db = $this->M_order->db_order();
$response = array();
$data = array();
foreach ($db as $key) {
$data[] = array(
'id' => $key->id_user,
'name' => $key->name,
'destination' =>$key->destination
);
}
$response['data'] = $data;
echo json_encode($response, TRUE);
}
this result my json
{
"data": [
{
"id": "1",
"name": "amar",
"destination": "USA"
}
]
}
here I want to add a status header in object, like the following ...
{
"status": 200,
"error": false,
"data": [
{
"id": "1",
"name": "amar",
"destination": "USA"
},
]
}
how to create ?

As I understand your question,
$response = array();
$data = array();
foreach ($db as $key) {
$data[] = array(
'id' => $key->id_user,
'name' => $key->name,
'destination' =>$key->destination
);
}
$response['status'] = 200;
$response['error'] = false;
$response['data'] = $data;

Related

file_get_contents parse json insert database

Hi I encountered a problem. I will record the data I received from the database.
JSON=>
{
"success": true,
"timestamp": 1565251506,
"base": "EUR",
"date": "2019-08-08",
"rates": {
"AED": 4.119657,
"AFN": 87.689574,
"ALL": 121.192477,
"AMD": 533.113395,
"ANG": 1.998509,
"AOA": 398.760307,
"ARS": 51.036305,
"AUD": 1.654423
}
}
After Json decode
array:5 [
"success" => true
"timestamp" => 1565205306
"base" => "EUR"
"date" => "2019-08-07"
"rates" => array:168 [
"AED" => 4.118588
"AFN" => 87.74397
"ALL" => 121.002609
"AMD" => 534.279745
"ANG" => 2.001014
]
]
I want this=> But How do I get quote and rate?
$response = file_get_contents("rate.json");
$datas = json_decode($response, true);
foreach ($datas as $data) {
$rates = new Rate();
$rates->base = $datas['base'];
$rates->quote = 'AED';
$rates->rate = '4.119657';
$rates->save();
}
You're looping over the wrong thing here, you should be looping over the rates and saving the corresponding key and value:
$response = file_get_contents("rate.json");
$data = json_decode($response, true);
foreach ($data['rates'] as $quote => $rate) {
$rates = new Rate();
$rates->base = $data['base'];
$rates->quote = $quote;
$rates->rate = $rate;
$rates->save();
}

Laravel validation rules for JSON

I'm trying to use a custom FormRequest with validation rules for JSON formatted data. If I use same code in controller instead of the FormRequest class then it works fine, see below:
array data (from ajax request):
[
{
"name": "id",
"value": "1"
},
{
"name": "title",
"value": "My fun project"
}
]
Controller:
public function update(Request $request, $id) {
//convert it to readable json
$jsonReq = $request->json()->all();
$jsonData = array();
foreach ($jsonReq as $json) {
$jsonData[$json["name"]] = $json["value"];
}
$rules = [
'id' => 'required|numeric:1',
'title' => 'required|max:255',
];
$validation = Validator::make($jsonData, $rules);
if ($validation->fails()) {
return $validation->errors();
}
}
Above works fine when used in the controller. However, I want to separate my validation in a separate class, extending the FormRequest. This generates some errors, most likely due to the array format.
class UpdateProjectValidationRequest extends FormRequest {
public function rules() {
$jsonReq = $this->json()->all();
$jsonData = array();
foreach ($jsonReq as $json) {
$jsonData[$json["name"]] = $json["value"];
}
return [
'id' => 'required|max:1', //does not work
$jsonData['title'] => 'required|max:255', //does not work
];
}
Controller:
public function update(UpdateProjectValidationRequest $request, $id) {
// validate against rules
$request->rules();
The error message:
{
"message": "The given data was invalid.",
"errors": {
"My fun project": [
"My fun project field is required."
],
"id": [
"The id field is required."
],
Clearly this has to do with the format. Any ideas how to solve this? Note that after the foreach loop the data is formatted to below:
{
"id": "1",
"title": "My Fun project",
}
Ok so i could not solve it using the laravel FormRequest, instead I modified the ajax call itself by serializing it to json instead of an array.
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
//old: var formdata = JSON.stringify(jQuery('#myForm').serializeArray());
var formdata = JSON.stringify(jQuery('#myForm').serializeObject());

Adjust the json response in array and objects

I am working on the web service and json response.
I got this response from the API :
[
[
{
"id":"1",
"unique_id":"579992ffd1",
"contact_name":"qweryyy",
"user_phone_number":"03331524145",
"created_at":"2016-08-01 15:53:59"
},
{
"id":"2",
"unique_id":"579992ffd1",
"contact_name":"qwer",
"user_phone_number":"03331524231",
"created_at":"2016-08-01 16:04:59"
},
{
"id":"3",
"unique_id":"579992ffd1",
"contact_name":"qwer",
"user_phone_number":"0333152111",
"created_at":"2016-08-01 16:05:08"
}
]
]
But i need to show the response like this JSON:
{
"unique_id":"579992ffd1",
"user":[
{
"id":"1",
"contact_name":"qweryyy",
"user_phone_number":"03331524145",
"created_at":"2016-08-01 15:53:59"
},
{
"id":"2",
"contact_name":"qweryyy",
"user_phone_number":"03331524145",
"created_at":"2016-08-01 15:53:59"
},
{
"id":"3",
"contact_name":"qweryyy",
"user_phone_number":"03331524145",
"created_at":"2016-08-01 15:53:59"
}
]
}
Here is my code to get the user array and return it to show the json response:
if ($result) {
$this->conn = new PDO("mysql:host=$servername;dbname=$dbname",
$username, $password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
$stmt = $this->conn->prepare("SELECT * FROM contact WHERE
user_phone_number = '$user_phone_number' ");
//$stmt->bind_param("s", $phone_number);
$stmt->execute();
$user = $stmt->setFetchMode(PDO::FETCH_ASSOC);
$user = $stmt->fetchAll();
//print_r($user);
return $user;
} else {
return false;
}
SHow json response :
if ($user) {
$string = '';
$cart = array();
$response["status"] = TRUE;
for($x=0;$x<count($user);$x++)
{
$string = $user[$x];
array_push($cart, $string);
}
echo json_encode(array($cart));
}
Any help to show the required output ??
$query = 'SELECT * FROM contact WHERE user_phone_number = "'.$user_phone_number.'"';
$result = mysql_query($query) or trigger_error($query.'<br>'.mysql_error(),E_USER_ERROR);
$list = Array();
while($row = mysql_fetch_array($result,MYSQL_ASSOC))
{
$list[] = $row;
}
$cart = Array(
'unique_id' => '579992ffd1';
'user' => $list;
);
echo json_encode($cart);

Array push to multidimensional array for JSON

Can someone pls help me on how to array_push to a multidimensional array.
This is my code for pushing.
$arrDataChart3["categories"] = array();
array_push($arrDataChart3["categories"], array(
"category"=>array ()
)
);
while($row = sqlsrv_fetch_array($myAcc2)) {
array_push($arrDataChart3["categories"]["category"], array(
"label" => $row["position"])
);
}
i want to push $row["position"] to "category" from my database.
Here's what the array should contain.
"categories": [
{
"category": [
{
"label": "Q1"
},
{
"label": "Q2"
},
{
"label": "Q3"
},
{
"label": "Q4"
}
]
}
],
Thanks in advance
i used this solved the problem
$arrDataChart3["categories"] = array();
$arr=array ();
while($row = sqlsrv_fetch_array($myAcc2)) {
array_push($arr, array(
"label"=>$row['position']
)
);
}
array_push($arrDataChart3["categories"], array(
"category"=>$arr
)
);

How to send JSON via JavaScript and decode it in Perl?

I am trying to POST JSON using JavaScript and read the POST results using a Perl script. I have written this code but am unable to get the Perl script to read in the JSON text.
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Testing ajax</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
var d = {
"name": "Bob",
"sex": "Male",
"address": {
"city": "San Jose",
"state": "California"
},
"friends": [
{
"name": "Alice",
"age": "20"
},
{
"name": "Laura",
"age": "23"
},
{
"name": "Daniel",
"age": "30"
}
]
};
$(document).ready(function() {
$("#test").click(function() {
$.ajax({
type: 'POST',
url: '/cgi-bin/Raghav_test/Apollo/read_ajax3.pl',
data: "r=" + d,
success: function(res) { alert("data" + res); },
error: function() { alert("did not work"); }
});
});
});
</script>
</head>
<body>
<button id="test">Testing</button>
</body>
</html>
Perl:
#!/usr/bin/perl -w
use CGI;
#use DBD;
use DBI;
use JSON::PP;
use Data::Dumper;
use DBD::Oracle qw(:ora_types);
use lib "/var/www/cgi-bin/ICE_LIBRARY/";
require '/var/www/cgi-bin/import_scripts/library/common_lib.pl';
require "/var/www/cgi-bin/import_scripts/library/script_log.pl";
use database_conf;
my $db = new database_conf;
#my $EP_dev_conn = $db->db_eportal_dev;
my $EP_prod_conn = $db->db_eportal_prod;
my $cgi = CGI->new;
my $id = $cgi->param("r");
#my $data = $cgi->param('POSTDATA');
print "Content-type:text/html\n\n";
#my $value = $ddata->{'address'}{'city'} ;
# Here I'd like to receive data from jQuery via ajax.
#my $id = $cgi->param('apiKey');
#$json = qq{{"ID" : "$id"}};
#my $method = $cgi->param('method');
#my $ip = $cgi->param('ip');
$json = qq{"$id"};
print $json;
exit;
You need to call JSON.stringify() on your object before making the request:
$.ajax({
type: 'POST',
url: '/cgi-bin/Raghav_test/Apollo/read_ajax3.pl',
data: { "r": JSON.stringify(d) },
success: function(res) { alert("data" + res); },
error: function() { alert("did not work"); }
});
And then you need to call decode_json() on the string to parse it and turn it into a Perl data structure:
my $q = CGI->new;
my $json = $q->param("r");
my $href = decode_json($json);
print Dumper($href);
Output:
$VAR1 = {
'address' => {
'state' => 'California',
'city' => 'San Jose'
},
'name' => 'Bob',
'friends' => [
{
'name' => 'Alice',
'age' => '20'
},
{
'age' => '23',
'name' => 'Laura'
},
{
'name' => 'Daniel',
'age' => '30'
}
],
'sex' => 'Male'
};