Pass object through NodeJS to PHP - php

I´m trying to pass object with two keys/values and I want to read it on the other side when I make Apache connect to it.
My nodejs server looks like so:
var sWeather = {"url1": "something", "url2": "another"};
var oWeather = JSON.stringify(sWeather);
console.log(sWeather);
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(sWeather+'\n');
}).listen(1340, '#');
console.log('Server running at http://###/');
Now I´m really new to nodejs and I have tried alot of thing so I´m not sure if I need to stringify the sWeather before I send it away.
My PHP file is like so:
<?php
$responseFromNode = file_get_contents("IP address");
var_dump($responseFromRuby);
For now I get string '[object Object] on my webpage because of var_dump.
I've tried doing something like
$url1 = $responseFromNode->url1
or
$url1 = $responseFromNode['url1']
I would just like to access both of the urls as a string so I can store it.
Any tips would be highly appreciated.

oWeather is the JSON string. Change
res.end(sWeather+'\n');
To
res.end(oWeather+'\n');
Then the PHP side has to decode the JSON
$responseFromNode = json_decode( file_get_contents("IP address") );
Notes:
You should also change your content type: res.writeHead(200, {'Content-Type': 'application/json'});, as mentioned by Brian Glaz
Your variable names are inverted:
oWeather should be the object
sWeather should be the JSON string

Related

How to read array passed to php in async call

I have the following in a js script:
let skippers = {};
for(let i = 0; i < skipperIds.length;i++){
skippers[skipperIds[i].value] = skipperIds[i].checked;
}
regData.skippers = skippers;
responseData = sendData2('https://sailwbob.com/lagin/public/register.php',regData);
where sendData2 is an async call using axios. skippers looks like
{1:true,20:false}
In my php file I have:
$skippers = ($_POST['skippers']);
$skipperIds = array_keys($skippers);
$skipperValues = array_values($skippers);
but this is not working. I think php converts an array in $_POST to a string but I'm not sure.
two qustions:
how do I convert $skippers back to an array?
I've been trying to use print_r to see the data on the server but as this is an async call it's not working as the print_r results are being sent back to the js script and not printing out on the screen. Is there a way to see the results of print_r?
Update:
I tried $x=json_decode($_POST); but got an error saying it was expecting a string.
here's the call to axios:
function sendData2(url,emailPass){
let bodyFormData = new FormData()
for (const [key, value] of Object.entries(emailPass)) {
//console.log(key,value)
bodyFormData.append(key,value)
}
return axios({
method: 'POST',
url: url,
data: bodyFormData,
headers: {'Content-Type': 'multipart/form-data'}
})
.then(function(response){
return response.data
})
.catch(function(response){
return response
})
}
update2:
$skippers shows $skippers = [object Object]. Is there a way to send this to the server correctly?
As discussed in this article, axios serializes Javascript objects to JSON and becase PHP doesn't support JSON as a data format for populating $_POST, you can retrieve them in PHP like this:
$_POST = json_decode(file_get_contents("php://input"),true);
$skippers = $_POST['skippers'];
While axios does automatically stringify data it apparently doesn't do that for nested arrays. I needed to add:
regData.skippers = JSON.stringify(skippers); in my js
and then in the php file
$skippers = get_object_vars(json_decode($_POST['skippers']));

angular-php: form data is empty in php

I am using angular as frontend and php as backend here is the code of angular.
$scope.processForm = function($scope.formData) {
console.log($scope.formData);
$http({
method : 'POST',
url : 'process.php',
data : {'data': $scope.formData,'uid':uid}, // no need to use $.param, even never see it in angular
headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
})
here is the process.php
$postContent= file_get_contents("php://input");
$req= json_decode($postContent);
$formData= $req->formData;
$uid= $req->uid;
problem is $formData is empty in php. however $uid is showing value.
in form i have two entry email and password but i don't know how can i use that in php because formdata is empty.
I checked in firebug and found data is posting.
{"formData":{"password":"ff","cpassword":"errgreg"},"uid":"75"}:""
But nothing is coming response tab of firebug.
Assuming you call your function with something like ng-submit="processForm(formData)" then this is all you actually need
$scope.processForm = function(formData) {
$http.post('process.php', {
formData: formData, // note the key is "formData", not "data"
uid: uid // no idea where uid comes from
});
};
Where you have
$scope.processForm = function($scope.formData) {
isn't even valid JavaScript. You cannot use object dot notation in function argument names. That should have been throwing an error in your console.
You also appeared to be incorrectly setting your request content-type. You are sending JSON, not application/x-www-form-urlencoded formatted data. Angular's default POST content-type (application/json) is sufficient.
Try like this..
$json='{"formData":{"password":"ff","cpassword":"errgreg"},"uid":"75"}';
$req= json_decode($json);
$formData= $req->formData;
$uid= $req->uid;
$password = $req->formData->password;
$cpassword = $req->formData->cpassword;
OR convert into array using json_decode() with second argument as true.
$json='{"formData":{"password":"ff","cpassword":"errgreg"},"uid":"75"}';
$req= json_decode($json,true);//converts into array format
$formData= $req['formData'];
//print_r($formData);
echo $formData['password'];

AJAX request to PHP - Handling response data

Im working on some AJAX login function, making a request via PHP.
I am wondering how do I return data via the PHP so that I can handle it like the code mentioned below. I only worked on the javascript side and not the PHP server side so I am confused now.
I want to get a value/values stored in the response like data.name , data.sessionID , data.listOfnames
Is the data a JSON Object by itself?
Thanks!
The code below was used before and has been verified to work.
function retrieveVersion(){
var URL = RSlink + "/updates";
$.ajax({
headers : {
"Content-Type" : "application/json; charset=UTF-8",
"sessionid" : result
},
type : "GET",
url : vURL,
statusCode : {
0 : function() {
hideLoadingMsg();
showError(networkError, false);
},
200 : function(data) {
currentVersion = String(data.version);
updatesArray=data.updates;
});
}
}
});​
Suppose you have a php file for handling ajax calls. It should be available by this url - vURL.
In this file you need to create an array.
Something like this:
$data = array('data' => array('version' => yourversion, 'updates' => yourupdates));
Then you need to convert this object into json string. You can do this using json_encode() function
echo json_encode($data);
One thing to keep in mind: You need to echo your data and only. If somewhere in your file you will have some other echo-es, the result string returning to your ajax-funtion might be broken.

JSON with PHP Slim and AngularJS

I am trying to send some data from my AngularJS Project to a PHP Server where I am using PHP Slim but I have tried everything I know and nothing seems to work.
SERVER PHP SLIM
$app->get('/create',function() use ($app) {
$data = $app->request()->params();
response_json(200,"DB: User Created",$data);
});
It works if I type directly from the browser
http://localhost:8888/core/users/create?login=test&password=123&name=Test&email=test#test.com&phone=12313
But if I try to send from the app using $http or $resource
var obj = { name:"Hello",email:"hello#email.com"};
$http.get('/core/users/create?',obj).success(function(data){console.log(data); });
I get an empty Array[0].
And if I try to use $resource I got an obj but not how I expected.
.factory('qServer',function($resource){
return $resource('/core/users/create?:data',{data: '#data'});
});
var obj = { name:"Hello",email:"hello#email.com"};
var send = JSON.stringify(obj);
//console.log(lol);
qServer.get({data:send},function(data) { console.log(data) });
With this code I get an Object like that:
data: Object
{"name":"Hello","email":"hello#email_com"}: ""
Anyone could tell me what I am doing wrong?
The second argument of $http.get method is not GET params but a request config.
You want to use something like this (notice the params key in config argument and lack of ? at the end of URL):
var obj = { name:"Hello",email:"hello#email.com"};
$http.get('/core/users/create', {params: obj})
.success(function(data){console.log(data); });
See also: Q: $http get parameters does not work and config argument docs.

searching within text of api

I'm trying to use an api and I'm just learning how to actually implement an api using php, hopefully I'll learn to incorporate jquery. I know how to create a simple search feature through mysql and its data with php, but is there a way to create search within the api? with API, there's json/xml responses, and they're all strings, so I was wondering if the user was able to search those strings?
Thanks
First you have to send the json data to php via AJAX. Something like this:
var request;
function runAjax(JSONstring)
{
// function returns "AJAX" object, depending on web browser
// this is not native JS function!
request = getHTTPObject();
request.onreadystatechange = sendData;
request.open("GET", "parser.php?json="+JSONstring, true);
request.send(null);
}
// function is executed when var request state changes
function sendData()
{
// if request object received response
if(request.readyState == 4)
{
// parser.php response
var JSONtext = request.responseText;
// convert received string to JavaScript object
var JSONobject = JSON.parse(JSONtext);
// notice how variables are used
var msg = "Number of errors: "+JSONobject.errorsNum+
"\n- "+JSONobject.error[0]+
"\n- "+JSONobject.error[1];
alert(msg);
}
}
You then can call the variable that javascript creates by calling the $_GET['json'] variable.
strstr($_GET['json'] , $whatEverYourSearchingFor);

Categories