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

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'
};

Related

Get record by post title in Wordpress

Im trying to figure out the endpoint i need to get a record by its post title in word press. here is how i did it using id
var axios = require('axios');
var data = JSON.stringify({
"acf": {
"twitter": "hello"
}
});
var config = {
method: 'get',
url: URL/wp-json/wp/v2/team/9950', //how can i replace id with post title here
headers: {
'Authorization': 'Basic auth',
'Content-Type': 'application/json'
},
data : data
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
below is how the post title json looks
{
"id": 9950,
"date": "2021-11-11T03:20:35",
"date_gmt": "2021-11-11T03:20:35",
"guid": {
"rendered": "URL/team/john-doe/"
},
"modified": "2022-08-19T14:53:46",
"modified_gmt": "2022-08-19T14:53:46",
"slug": "john-doe",
"status": "publish",
"type": "team",
"link": "URL/team/john-doe/",
"title": {
"rendered": "John Doe" //how do i search for john doe record using title
},
how can i make a get request using title instead of ID
Unfortunately it is not possible by default to search by title.
Though, you can add it to rest api like this:
add_filter( 'rest_team_query', function( $args, $request ){
if ( $title = $request->get_param( 'title' ) ) {
$query = array(
array(
'key' => 'post_title',
'value' => $title,
'compare' => 'LIKE'
));
$args['meta_query'] = $query:
}
return $args;
}, 10, 2 );
Then you can search the title like this in your api call:
/wp-json/wp/v2/team?title=john%20doe

how to create json response status in codeigniter

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;

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();
}

Google Slides Batch Update Errors - "Invalid JSON payload received. Unknown name" & " Cannot bind query parameter"

I'm trying to write to a slide element.
I keep getting the error responses of "Invalid JSON payload received. Unknown name" and " Cannot bind query parameter. Field"
My request is
{
"requests": [
{
"deleteText": {
"objectId": "g33c4ea3b90_0_9",
"textRange": {
"type": "FROM_START_INDEX",
"startIndex": 0
}
}
},
{
"insertText": {
"objectId": "g33c4ea3b90_0_9",
"text": "$8.23",
"insertionIndex": 0
}
}
]
}
I am posting to: https://slides.googleapis.com/v1/presentations/PRESENTATION_ID:batchUpdate?access_token=ACCESS_TOKEN
I am manually cURLing the request in PHP:
$params = '
{
"requests": [
{
"deleteText": {
"objectId": "'.$page_object_id.'",
"textRange": {
"type": "FROM_START_INDEX",
"startIndex": 0
}
}
},
{
"insertText": {
"objectId": "'.$page_object_id.'",
"text": "$8.23",
"insertionIndex": 0
}
}
]
}
';
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => false, // don't return headers
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
CURLOPT_ENCODING => "", // handle compressed
CURLOPT_AUTOREFERER => true, // set referrer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // time-out on connect
CURLOPT_TIMEOUT => 120, // time-out on response
CURLOPT_CUSTOMREQUEST => 'POST' ,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false ,
CURLINFO_HEADER_OUT => true ,
CURLOPT_VERBOSE => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $params
);
$ch = curl_init($url);
curl_setopt_array($ch, $options);
$content = curl_exec($ch);
curl_close($ch);
$obj = json_decode($content, true);
print_r( $obj );
When I call it from the API Explorer it works perfectly, but not from my server.
So the problem was the use of double quotes instead of single quotes in the request parameter json string.
So the following works:
{
'requests': [
{
'deleteText': {
'objectId': 'g33c4ea3b90_0_9',
'textRange': {
'type': 'FROM_START_INDEX',
'startIndex': 0
}
}
},
{
'insertText': {
'objectId': 'g33c4ea3b90_0_9',
'text': '$44.23',
'insertionIndex': 0
}
}
]
}
I had been working on this for two days.

DataTable Populate Ajax

I have a datatable js and I fill in with ajax (json), in my json, its return is several entries, I see this through the console, but, the datatable is only populated with the first json record.
My Code
$(document).ready(function()
{
$.ajax({
type : 'POST',
url : 'view/list/clients_1.php',
dataType: 'json',
cache: false,
success : function(result)
{
//pass data to datatable
console.log(result); // just to see I'm getting the correct data.
$('#my_table').DataTable({
"searching": false, //this is disabled because I have a custom search.
"bAutoWidth": false,
"bFilter": true,
"bLengthChange": false,
"responsive": true,
"aaData": [result], //here we get the array data from the ajax call.
"aoColumns": [
{ "sTitle": "#" },
{ "sTitle": "Name" },
{ "sTitle": "Work" }
]
});
}
});
Code of file: clients_1.php
$clients_sql =
"
SELECT
*
FROM
client
";
$result = mysqli_query($mysqli, $clients_sql);
$dataArray = array();
while( $row = mysqli_fetch_array($result) )
{
$dataArray[] = $row["client_id"];
$dataArray[] = $row["client_name"];
$dataArray[] = $row["client_work"];
}
echo json_encode($dataArray);
resolved
var table = $('#my_table').dataTable({
serverSide: true,
searching: false,
bAutoWidth:false,
bFilter: true,
bLengthChange: false,
responsive: true,
ajax: "view/lista/clientes_1.php",
dataSrc: 'data',
columns: [
{sTitle: "#", data: 'client_id' },
{sTitle: "Name", data: 'client_nome' },
{sTitle: "Work", data: 'client_work' }
]
}); // End: DataTable
$('#search-table').unbind();
$('#search-table').bind('keyup', function(e) {
//if(e.keyCode == 13) {
table.fnFilter(this.value);
// }
});
PHP
$result = mysqli_query($mysqli, $clients_sql);
while($row = $result->fetch_array(MYSQLI_ASSOC))
{
$data[] = $row;
}
$results = [
"sEcho" => 1,
"iTotalRecords" => count($data),
"iTotalDisplayRecords" => count($data),
"aaData" => $data
];
echo json_encode($results);
I recommend adding to the answer given by sNniffer
$data = [];
just above the while loop.
Otherwise, when there are no rows in the query (and the while loop is not executed), you get this warning from datatables