From node.js I would like to get JSON data from a PHP file. I thought about using the request package, but I am not sure about what to write in the PHP file in order to send the JSON back to node:
Node:
var request = require('request');
request
.get('http://IP/File.php')
.on('response', function(response) {
data = JSON.parse(data from the php file);
});
PHP:
$data = array('message' => 'HeLLO');
$json = json_encode($data);
when executing this, send $json to node
you need to print a response from your .PHP file:
$data = array('message' => 'HeLLO');
$json = json_encode($data);
print_r($json);
javascript:
var request = require('request');
request('http://IP/File.php', function (error, response, body) {
if (!error && response.statusCode == 200) {
data = JSON.parse(body)[0];
}
})
Related
so we've been making a chatbot in Google Apps Script and one of its functions is to display information from a database (hosted online). The script sends a POST request to a controller function in our CodeIgniter program:
function do_post(name, status, duration) {
// Make a POST request with a JSON payload.
var data = {
'name': name,
'status': status,
'key' : api_key,
'duration' : duration
};
var options = {
'method' : 'post',
'contentType': 'application/json',
'muteHttpExceptions' : true,
// Convert the JavaScript object to a JSON string.
'payload' : JSON.stringify(data)
};
var response = UrlFetchApp.fetch('https://www.domainname.com/bot/index.php/bot/process/', options);
Logger.log(response);
return response;
}
The function above successfully inserts a record into the database using our process() controller in CI, but the problem is in our response variable. It's of HttpResponse type and we don't know how to return that type from our controller. We want our controller to return something like {"Response": "success"} to our chatbot but we don't know how. We've tried returning a JSON-encoded array:
public function process()
{
$_POST = array_replace($_POST, json_decode(file_get_contents('php://input'), true) ?? []);
$name = $_POST["name"];
$status = $_POST["status"];
$api = $_POST["key"];
$duration = $_POST["duration"];
if ($api == api_key){
$result = $this->bot_model->add_log();
}
$res_array = array("response" => $result);
// encode array to json
$json = json_encode($res_array);
return ($json);
}
}
And we try accessing var response in our app script using response.getContentText(), but we get something like "string(39)" and then the value of our api_key. How do we access the json data from the response?
You need to set the mime-type of your page so you can serve JSON data by using the set_content_type() method from the Output class.
Check the code
public function process()
{
$_POST = array_replace($_POST, json_decode(file_get_contents('php://input'), true) ?? []);
$name = $_POST["name"];
$status = $_POST["status"];
$api = $_POST["key"];
$duration = $_POST["duration"];
if ($api == api_key){
$result = $this->bot_model->add_log();
}
// JSON OUTPUT
$this->output
->set_content_type('application/json')
->set_output(json_encode( array("response" => $result)));
}
I noticed that when a function in CodeIgniter is called via post, the return of that function is whatever is printed out by the function in any way, be it echo, print_r, or var_dump. So to return your JSON file to App Script simply do echo $json;.
I'm using an API to send sms in my codeigniter project. After sending, it will return a response array in the form of json to a callback url in my project. And i need to update this response in my database. Here is my code :
the response array will be similar as follows :
{"req_id":"809ff62f-74a9-45a5-9cb5-5e60763289af","status":"0" ,"comment":"OK"}
my callback url redirects to following function in my controller
public function templateCallback() {
$json = file_get_contents('php://input');
$json = urldecode($json);
$obj = json_decode($json, TRUE);
$reqID = $obj->req_id;
$status = $obj->status;
print_r($obj);
$this->db->where('TemplateRequestID', $reqID);
$this->db->set('TemplateApproved', $status);
$this->db->update('templatemaster_tbl');
}
But its never get updated. What is wrong in my code ? I'm not good in json. So i'm not sure is this the correct way to fetch and decode json array in php. Someone please help me.
To test this i have created a view in my project and send this same array through an ajax function like :
var base_url = '<?php echo base_url()?>';
$('#test').click(function() {
var val = $('#testvalue').text();
$.ajax({
type: 'post',
url: base_url + 'API/templateCallback',
data: {
val
},
success: function (response) { console.log(response);
}
});
});
and try to print both $json and $obj in controller function.
$json displays a string like : val=%7B%22req_id%22%3A%228b3eef97-330a-4271-8450-0676fbac8885%22%2C%22status%22%3A%220%22%2C%22comment%22%3A%22OK%22%7D
and $obj displays nothing
If your $json contains encoded value (%7B%22req_id%22%3A%228b3eef97-330a-4271-8450-0676fbac8885%22%2C%22status%22%3A%220%22%2C%22comment%22%3A%22OK%22%7D) you should decode it first with urldecode.
So proper code would be:
...
$jsonEncoded = file_get_contents('php://input');
$json = urldecode($jsonEncoded);
$obj = json_decode($json, TRUE);
...
I've tried all the examples on these SO posts:
How do I send a POST request with PHP?
PHP cURL Post request not working
Always my request.body is undefined yet in the request itself I see "_hasBody":true
The current code for my php post file:
function httpPost($url,$data){
$curl = curl_init($url);
curl_setopt($curl,CURLOPT_POST,true);
curl_setopt($curl,CURLOPT_POSTFIELDS,http_build_query($data));
curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
$response=curl_exec($curl);
curl_close($curl);
return $response;
}
$fields = array(
'name' => 'ben'
, 'foo' => 'bar'
);
echo httpPost("http://localhost:8002", $fields);
Then my node.js listening server code is:
var test=require('http').createServer(function(q,a){//question,answer
console.log(q.body);
console.log(JSON.stringify(q).indexOf('ben'));
a.end(JSON.stringify(q));
});
test.listen(8002,function(e,r){console.log("listening");});
As you can see, in the node.js server I search the request for my name but the console says
undefined//no body
-1//could not find your name in the request
then I hand over the request back to the response and print it to the page so I can see the whole data.
logically it would seem that I am doing the cURL part right as its copied code, so I would say I might be doing something wrong to access the vars
My question is how do I see the request body or where the vars?
To handle a POST request, you have to do the following:
var qs = require('querystring');
var http = require('http');
var test = http.createServer(function(req, res) {
//Handle POST Request
if (req.method == 'POST') {
var body = '';
req.on('data', function(data) {
body += data;
});
req.on('end', function() {
var POST = qs.parse(body);
console.log(body); // 'name=ben&foo=bar'
console.log(POST); // { name: 'ben', foo: 'bar' }
if(POST.name == 'ben')
console.log("I'm ben"); //Do whatever you want.
res.setHeader("Content-Type", "application/json;charset=utf-8");
res.statusCode = 200;
res.end(JSON.stringify(POST)); //your response
});
}
});
test.listen(8002, function(e, r) {
console.log("listening");
});
cURL response:
{"name":"ben","foo":"bar"}
On the Angular side, I'm trying to do a GET http request like the following:
$scope.getQuestion = function() {
//$http.post($scope.url, { src : $scope.question});
var request = $http({
method: "get",
url: $scope.url,
params: 'index =1',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
/* Check whether the HTTP Request is Successfull or not. */
request.success(function (data) {
console.log("GET literally worked");
$scope.loginMessage = data;//angular.fromJson(data);
//console.log($scope.testArray["question2"]);
But am not sure how to retrieve params (index = 1) from it in php. I tried to do it as JSON but it didn't seem to work?
PHP side:
<?php
$data = file_get_contents("php://input");
$src = json_decode($data);
//var_dump($_POST);
//$src = $_POST['src'];
//#$toOut = $src->question;
//file_put_contents("output", $toOut);
/*$arr = array (
0 => "does this work?",
"question2" => "i mean i guess?"
);
$jsonString = json_encode($arr);
echo $jsonString;*/
$numArr = $src -> params;
echo $numArr -> index;
?>
So I'm confused on how the params are being read since we aren't passing it to php as $data?
Use an object as param instead of a string:
params: {index:1},
then in your.php
print_r($_GET['index']);
you can try this
$_GET['index']
params works the same as url after ? when Method is GET
i try to send my datas to php with ajax but there's strange mistake.
this is my ajax script,
function deleteData2()
{
var artistIds = new Array();
$(".p16 input:checked").each(function(){
artistIds.push($(this).attr('id'));
});
$.post('/json/crewonly/deleteDataAjax2',
{ json: JSON.stringify({'artistIds': artistIds}) },
function(response){
alert(response);
});
}
i think this works correctly but in php side, i face 500 internal server error(500).
public function deleteDataAjax2() {
$json = $_POST['json'];
$data = json_decode($json);
$artistIds = $data['artistIds'];
$this->sendJSONResponse($artistIds);
}
Above code is my php. For example, when i try to send $data to ajax,
i print my ids in json mode:
However, when i try to send $artistIds to ajax side, i gives 500 error why?
Selam :)
Right should be:
public function deleteDataAjax2() {
$json = $_POST['json'];
$data = json_decode($json, true);
$artistIds = $data['artistIds'];
$this->sendJSONResponse($artistIds);
}
look at json_decode(). If you wanna use this as an array, you have to set the second parameter to true, otherwise use $data->{'artistIds'}; :)
try something like this and see if you get a response.
$.getJSON('/json/crewonly/deleteDataAjax2',
{ 'artistIds' : artistIds },
function(response){
alert(response);
});
public function deleteDataAjax2() {
$json = $_REQUEST['artistIds'];
$data = json_decode($json);
var_dump($data);die(null);
}