Angular JS issues sending JSON with $ http - json

I am having issue sending post json data with angular, from PHP I need to access $_POST['action']
This works
$http({
method: 'POST',
url: ajaxurl,
data: "action=get_employer_jobs",
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function (data) {
console.log(data);
$scope.jobs = data;
});
This does not work
app.controller('MainController', ['$scope', '$http', function ($scope, $http) {
console.log('MainController Running');
$http({
method: 'POST',
url: ajaxurl,
data: JSON.stringify({action:"get_employer_jobs"}),
headers: {'Content-Type': 'application/json'}
}).success(function (data) {
console.log(data);
$scope.jobs = data;
});
}]);

You need to process your json on the server side differently.
in PHP, I do it like this:
$_REQUEST = json_decode(file_get_contents("php://input"));
The way Angular sends POST data as json strings, you need to take the whole request string, parse it, then you can use it. It won't automatically be in $_POST or $_REQUEST as a nice array until you do this parsing.

I´d the same problem, it looks like PHP doesn´t fill the $_POST array when it´s passed by the $http service.
Instead of using $_POST, try to parse directly the php://input.
php
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
var_dump($request)
Then you can access using the object notation $request->my_var

Related

How to get a value from returned JSON in HTML?

My client side looks like this:
filename="random_filename.docx"
var response = await fetch("https://backend.wl.r.appspot.com/scriptstuff", {
method: 'POST',
mode: 'cors',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({ file: filename })
});
var data = response.json();
console.log(data);
and my backend return looks like this
response = jsonify({'prediction': str(prob)})
response.headers['Access-Control-Allow-Origin'] = '*'
return response, 200
I receive a promise with the value of 'prediction', but I'm not sure how to access that or why the current code isn't working.
EDIT: adding await before response.json() works
You can execute a function upon a promise being fulfilled by appending a .then() to the fetch request. If you're already receiving the JSON object then the values can be accessed by data.some_key.
I'm not an expert but first store str(prob) into a variable and then create an object with it. I think jsonify() takes things very literally.

Json handling in angular $http post to express

I am trying to post json data to express server using angular $http,
$scope.createTravel = function(){
$http({
url: '/api/travels',
method:"POST",
data: $scope.formData
// headers: {'Content-Type': 'application/json'}
})
};
the post is reaching the server in this console log statement
app.post("/api/travels", function(req, res){
console.log(req);
});
without the json data.

Requesting a JSON using Request module (encoding issue) - Node.js

Im trying to request a Json file from a server different from mine but i cant set the right encoding.
I tried using HTTP module and failed.
Now im trying to do this using the 'Request' module.
The response i get is encoded to i dont know what. maybe utf 16 and is not readable at all.
Note: The json has some Hebrew chars in it.
I added the following to try and fix it but also failed:
headers: {'Content-Type': 'application/json; charset=utf-8'}
My code:
var http = require('http');
var request = require('request');
var express = require('express');
var app = express();
var url = 'http://www.oref.org.il/WarningMessages/alerts.json?v=1';
app.listen(process.env.PORT || 8080);
app.get('/', function(req,res){
res.send("Red color");
});
// get Alerts from web-service
app.get('/getAlerts', function(req,res){
request({
url: url,
json: true,
headers: {'Content-Type': 'application/json; charset=utf-8'}
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
console.log(response.headers) // Print the json response
res.set({
'content-type': 'application/json'
}).send(body);
}
})
});
That API returns a JSON response encoded in UTF-16-LE, so you'll have to tell request to use that encoding instead.
However, since you're trying to query Pikud Haoref's alerts API, check out pikud-haoref-api on npm to do the heavy lifting for you:
https://www.npmjs.com/package/pikud-haoref-api

Reading data from res.end()

I'm sending a simple data back from the server to the client.
app.post('/user', function (req, res) {
var userName = "John";
res.end(JSON.stringify({"error":"", "user": userName}));
});
$.ajax({
type: "POST",
...
contentType : 'application/json',
dataType: "json"
})
.done(function(data) {
// send join message
var resData = JSON.parse(data);
alert("hello"); // this doesn't show up
});
});
});
But in the browser console, I get this error - "Uncaught SyntaxError: Unexpected token o".
If I do JSON.stringify and JSON.parse on the content, it works fine.
alert(JSON.parse (JSON.stringify({"error":"", "user": userName})).user);
And also, .done works fine without a data payload from the server i.e. the alert("hello") works.
So, I'm guessing something fishy is happening while sending data within res.end(). Please help.
While at it, it would be nice if you can also tell me how to do the same using res.json() and which one is preferable.
The problem here is that you set dataType: 'json' in your jQuery request. This causes the response from the server to be automatically parsed as JSON, so it will return the object rather than the raw server response.

How do I access HTTP POST data from meteor?

I have an Iron-router route with which I would like to receive lat/lng data through an HTTP POST request.
This is my attempt:
Router.map(function () {
this.route('serverFile', {
path: '/receive/',
where: 'server',
action: function () {
var filename = this.params.filename;
resp = {'lat' : this.params.lat,
'lon' : this.params.lon};
this.response.writeHead(200, {'Content-Type': 'application/json; charset=utf-8'});
this.response.end(JSON.stringify(resp));
}
});
});
But querying the server with:
curl --data "lat=12&lon=14" http://127.0.0.1:3000/receive
Returns {}.
Maybe params doesn't contain post data? I tried to inspect the object and the request but I can't find it.
The connect framework within iron-router uses the bodyParser middleware to parse the data that is sent in the body. The bodyParser makes that data available in the request.body object.
The following works for me:
Router.map(function () {
this.route('serverFile', {
path: '/receive/',
where: 'server',
action: function () {
var filename = this.params.filename;
resp = {'lat' : this.request.body.lat,
'lon' : this.request.body.lon};
this.response.writeHead(200, {'Content-Type':
'application/json; charset=utf-8'});
this.response.end(JSON.stringify(resp));
}
});
});
This gives me:
> curl --data "lat=12&lon=14" http://127.0.0.1:3000/receive
{"lat":"12","lon":"14"}
Also see here:
http://www.senchalabs.org/connect/bodyParser.html