Angular.js: get post-data in $_POST variable - php

I'm quite new to angular.js. Now I try to post some data to a PHP-Script.
angular.js:
var app = angular.module('app', []);
app.controller('sendData', function($scope, $http) {
$http.post("script.php", {'value': 'one'} )
.success(function (response) {
console.log(response);
});
});
PHP:
$data = json_decode(file_get_contents("php://input"));
So I would get the data in $data->value.
Is it possible to modify the script (without using $.param of JQuery), so I could access the post-data with $_POST['value'] - as I would normally do that in PHP?

$_POST is for using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request
See: http://php.net/manual/en/reserved.variables.post.php
So, in order to use x-www-form-urlencoded (and $_POST), you must serialize your data properly whether you are using the $.param function or another serialize method.
This is how we do it, although like I said, you can use a different function than $.param if you need to.
$http({
method: "post",
url: url,
data: $.param(data),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
Here is a vanilla js method of serialization:
https://stackoverflow.com/a/1714899/580487

Related

Angular http get params aren't getting through

I notice my get-data isn't passed through in my GET request. I've stripped it down to:
$http({
url: "http://www.myurl.com/somefolder/demo.php",
method: "GET",
data: { info: "lala"},
timeout: 5000
})
.then(function (res) {
var data = res.data;
console.log((data));
},function (error) {
alert("Something went wrong");
})
demo.php only contains:
<?php var_dump($_GET) ?>
It does work when I visit the URL with my browser, but via the http-get, everything seems fine but the data is never past.
console.log(data) always returns array(0) {} as if I didn't send any data.
Don't know if this is relevant, but I'm using this in an Angular based Ionic-app, and I'm testing it in my browser.
It's puzzling me for hours now...
In the configuration object, data represents the body of the request (Used by a POST request for example). It seems that you want to add parameters to the URL. You should use params key instead.
$http({
url: "http://www.myurl.com/somefolder/demo.php",
method: "GET",
params: { info: "lala"},
timeout: 5000
})
More details here: https://docs.angularjs.org/api/ng/service/$http#usage

Can't find variables with $http.post AngularJS

I'm having some trouble using $http.post() with angularJS.
When I use the "post" method with a form, I can find the data in my php file using $_POST, and it works fine.
But when I do, for example:
$http.post(myUrl, {data: "test data"})
.success(function(){
console.log("ok");
});
How can I get the data and use it in my php file?
Thanks
By default, Angular $http will use the header Content-type: application/json and send the request body as JSON. You can get this in PHP using:
json_decode(file_get_contents("php://input"));
More information about php://input
If you don't want this and you want to use $_POST you will have to send the data as x-www-form-urlencoded which requires changing the header and sending the data as an x-www-form-urlencoded string. For example:
$http({
url: myUrl,
data: "data=" + encodeURIComponent("test data"),
method: "POST",
headers: {"Content-type": "application/x-www-form-urlencoded"}
});
If you want these settings to be global, you can configure them with $httpProvider.defaults

Angular $http post not posting variable correctly for PHP

I have a PHP service at api/add in my application, and you can pass it rq and name via POST. rq tells the service what function to perform, so in my example addCity is defined, and it inserts a city into the database, and name is the name of the city.
So, with that being said, here is my angular code. I'm defining an angular module above with ngRoute.
whereApp.controller('AddCityCtrl', function($scope, $http) {
$scope.addCity = function() {
$http({
method: "POST",
url: '/api/add/',
data: { rq:'addCity', name: $scope.name },
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function (data, status, headers, config) {
console.log(data);
});
/*
$.ajax({
url: "/api/add/",
type: "POST",
data: { rq: 'addCity', name: $scope.name },
dataType: "json"
})
.success(function(data) {
console.log(data);
});
*/
}
});
Here's the problem. The ajax request (jQuery style that is commented out) works. I'm wanting to use the angular style since, well, it's what I'm using and what I'm trying to learn a little bit more about. The jQuery ajax call gives me back the success message that I have from server-side, and the $http method says that the rq variable is not defined, which I'm accessing via $_POST['rq'].
I've done some research already on Google, but so far have only come up with adding headers: {'Content-Type': 'application/x-www-form-urlencoded'} like this post says.
Can anyone tell me what the difference is between these two ajax calls (or if there is something else I haven't considered)?
Since it is json data that is being sent in php you cant get it by simple $_POST you need to do this kind of stuff to get this posted data
$data=file_get_contents('php://input');
$dataobj= json_decode($data);
Here you get data first then decode it from json to normal object

POST json data via ajax sends an empty array

I'm trying to post data via ajax, this is my info:
var jsondata =
{"address" : [
{ "id": addid, "streetaddress": streetaddress, "city": city, "state": state, "zipcode": zipcode, "latitude": latitude},
]
};
var jsontosend = JSON.stringify(jsondata, null, 2);
ajax function:
$.ajax({
type: "POST",
url: "process.php",
contentType: "application/json; charset=utf-8",
dataType: "JSON",
data: jsontosend,
success: function(msg){
alert(msg);
}
});
return false;
alert('Data sent');
}
on the php end, when i print_r($_POST) it just says
array(0) {
}
I'm alerting (jsontosend) and its showing me everything perfectly, as well as in firebug using post mothod, its showing all the params sent in a perfect clean manner.
The only way it passes any data is if I use GET method.
Any advice is greatly appreciated!
EDIT: adding POST data from firebug.
this is whats being alerted from the alert function:
{"address":[{"id":1473294,"streetaddress":"3784 Howard Ave","city":"Washington DC","state":"DC","zipcode":20895,"latitude":39.027820587}]}
this is what firebug is showing as whats being passed when using POST method:
myData=%7B%0A++++%22address%22%3A+%5B%0A++++++++%7B%0A++++++++++++%22id%22%3A+76076%2C%0A++++++++++++%22streetaddress%22%3A+%223784+Howard+Ave%22%2C%0A++++++++++++%22city%22%3A+%22Washington+DC%22%2C%0A++++++++++++%22state%22%3A+%22DC%22%2C%0A++++++++++++%22zipcode%22%3A+20895%2C%0A++++++++++++%22latitude%22%3A+39.027820587%0A++++++++%7D%0A++++%5D%0A%7D
and this is the response for var_dump of $_POST:
array(0) {
}
this is a var_dump of $_POST['myData']
NULL
I'm skeptical of the way you're using the contentType property. Try taking out contentType. The default content type is
application/x-www-form-urlencoded (http://api.jquery.com/jQuery.ajax/).
Also, use something like {mydata: jsontosend} for your data property.
$.ajax({
type: "POST",
url: "process.php",
//contentType: "application/json; charset=utf-8",
dataType: "JSON",
data: {mydata: jsontosend},
success: function(msg){
alert(msg);
}
});
Use
data:{myData: jsontosend}
It should send myData as a parameter in your request.
PHP doesn't understand application/json requests (by default).
See this question: How to post JSON to PHP with curl
I found that the comment provided by dkulkarni was the best solution here. It is necessary to read directly from the input stream to get POST data of any complexity. Changing the value of $.ajax({contentType: ''}) did not work for me..
In order to troubleshoot this problem I had set up a controller method to echo back the JSON I was posting to my server. Changing the ContentType header made no difference.
But after reading dkulkarni's comment I changed my server code from this:
return $_POST;
to this:
$data = file_get_contents('php://input');
return json_decode($data);
It worked perfectly.
As dkulkarni commented in his post (Jan 24 at 7:53), the only way to retrieve JSON sent with Content-Type application/json seems to be to retrieve it directly from the input stream.
I made a lot of tests with different approaches, but always when I set Content-Type to JSON, the $_POST in PHP is empty.
My problem is I need to set Content-Type to JSON, because the server (where I don't have access) expects it, otherwise it returns unsupported datatype. I suppose they are retrieving directly from input stream.
Why I have to reproduce that in own PHP file? Because I need to make a proxy for testing issues, but thats not the point of this thread.
Taking contentType out is not a good idea. You DO want to send this data in JSON format. Key is to do what has been mentioned above, instead of trying to access the data on the receiving end (the target php file) with $data= $_POST it is critical to use $data = file_get_contents('php://input');
Here is an example of the entire round trip for a scenario with php and knockout.js:
JS (on requesting page):
function() {
var payload = ko.toJSON({ YOUR KNOCKOUT OBJECT });
jQuery.ajax({
url: 'target.php',
type: "POST",
data: payload,
datatype: "json",
processData: false,
contentType: "application/json; charset=utf-8",
success: function (result) {
alert(result);
}
});
};
And then in target.php (the page receiving the request):
$data = file_get_contents('php://input');
$payload_jsonDecoded = json_decode($data
Try removing ' dataType: "JSON" ' from the ajax request and check.

why can't we access values on server side in POST request?

I tried to send the request from jquery ajax with contentType as 'text/plain'. I am unable to access the values on the server side. I am accessing the values using $_POST array in php file. Why is this happening.
jQuery AJAX code:
$.ajax({
type: "POST",
data: {o_pass:o_pass,n_pass:n_pass},
url: "changepass",
success: function(response) { alert(response); }
});
Server side:
$old_pass = $_POST['o_pass'];
$new_pass = $_POST['n_pass'];
Because POST requests should have a content type of application/x-www-form-urlencoded or multipart/form-data so that the server knows what it is dealing with.
What is the reason for sending the request as plain text?
You shouldn't have to worry about the content type, when doing a standard post request.
Try changing your url: changepass to changepass.php. You probably have an html or htm file named changepass that your server is processing your post request.

Categories