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
Related
I'm building API with the following structure:
method POST
uri /words.
body {"word":"example"}.
This request should add word to database and if I testing it by httpie everything is ok.
$ http POST localhost:8000/words word="new word2"
HTTP/1.1 200 OK
Access-Control-Allow-Headers: application/json
Access-Control-Allow-Origin: http://localhost:8080
Connection: close
Content-Type: application/json
Host: localhost:8000
X-Powered-By: PHP/7.0.12-1+deb.sury.org~xenial+1
{
"test": {
"method": "POST",
"input": {
"word": "new word2"
},
"post": []
},
"words": {
"id": "581f2f118b0414307476f7b3",
"word": "new word2"
}
}
In test I placed variable obtained in php by:
$method = $_SERVER['REQUEST_METHOD'];
$input = json_decode(file_get_contents('php://input'),true);
$post = $_POST;
We can see that $_POST is empty. If I use javascript:
$(form).submit(function(e) {
var url = "http://localhost:8000/words";
var data = {"word" : form.elements["word"].value };
$.ajax({
type: "POST",
url: url,
data: data,
dataType: 'json',
success: function(data)
{
console.log(JSON.stringify(data));
}
});
e.preventDefault();
});
I obtain the following console log:
{
"test":{
"method":"POST",
"input":null,
"post":{
"word":"word from form"
}
},
"words":{
"id":"581f34b28b0414307476f7b6",
"word":null
}
}
Now input is empty. Word is null because I am processing $input["word"], from php://input. My questions:
Should I process $_POST, or check both variable?
How about best practices of using these methods?
Can I send php://input from browser or $_POST from command line toll like httpie?
Your manually constructed example and your JavaScript example are not equivalent.
In the first you are sending JSON encoded data with an application/json content-type.
In the second, you are passing a JavaScript object to jQuery and allowing it to follow it's default behaviour, which is to encod it using the application/x-www-form-urlencoded format and use that as the content type (just like submitting a regular HTML form would do).
PHP supports application/x-www-form-urlencoded data in POST requests, but not JSON.
Should I process $_POST, or check both variable?
If you are sending application/x-www-form-urlencoded data or another format supported by PHP, then use $_POST. Otherwise you need to get the raw data from php://input and parse it yourself.
Can I send php://input from browser
See POST data in JSON format
$_POST from command line toll like httpie?
See the httpie documentation:
http --form POST api.example.org/person/1 name='John Smith'
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
I have an ajax call, that sends form data to a php function. Since I read a lot that using contentType: 'application/json' is best practice I wanted to give it a try as well. But unfortunately my script doesn't return anything when I use it. If I remove it, the script does what it is supposed to do.
Do you have any idea what the reason might be and why? Thank you!
$('#Form').submit(function(e) {
e.preventDefault();
var content = $(this).serialize() + "&ajax=1";
$.ajax('app/class/controller/contactForm.php', {
type: "POST",
//contentType: 'application/json',
dataType: 'json',
data: content,
success: function(result) {
console.log(result);
}
});
})
and my PHP:
if(isset($_POST['ajax']) && $_POST['ajax'] === '1') {
echo json_encode(validateForm($_POST));
}
When using contentType: 'application/json' you will not be able to rely on $_POST being populated. $_POST is only populated for form-encoded content types.
As such, you need to read your data from PHP raw input like this:
$input = file_get_contents('php://input');
$object = json_decode($input);
Of course if you want to send application/json you should actually send JSON, which you are not doing. You either need to build the object serialization to JSON directly, or you need to do something like this - Convert form data to JavaScript object with jQuery - to serialize the object from the form.
Honestly in your case, since you are dealing with form data, I don't quite think the use case for using application/json is there.
The best practice you refer to is about the server script setting the Content-Type for JSON to "application/json":
Header('Content-Type: application/json; charset=UTF8');
This is because otherwise a default Content-Type will be sent, often a catch-all text/html, and this could lead to an incomprehension with the client.
If you do not specify yourself a Content-Type in the jQuery request, jQuery will determine the most appropriate one. The problem here is that you were sending a POST form, for which the default Content-Type set by jQuery is application/x-www-form-urlencoded, which tells PHP to decode the data as POST fields and populate $_POST. Your script would have then recovered its parameters from $_POST (or maybe $_REQUEST).
By changing it to application/json, $_POST will no longer be populated, the receiving script operation won't receive the parameters where it was expecting to, and the operation breaks.
So you either need to:
not specify the Content-Type yourself (better, IMHO)
set a Content-Type of application/x-www-form-urlencoded; charset=UTF-8
set a Content-Type of application/json; charset=UTF-8 and modify the script to parse the POST stream and decode the JSON data; see this answer.
The third option requires proper handling of php://input.
The PHP script should be setting the Content-Type header.
if(isset($_POST['ajax']) && $_POST['ajax'] === '1') {
header('Content-Type: application/json');
echo json_encode(validateForm($_POST));
}
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.
I am making an ajax request from a jquery script to one of my ajax controllers in codeigniter. This process works fine when using data type json. However, when I want to send xml back from the server, the jquery documentation says that the server must specify a MIME type of text/xml. How do I do this with codeigniter.
My ajax call looks like this:
$.ajax({
type: "POST",
url: siteUrl + "index.php/ajax_controller/test",
dataType: "xml",
success: testSuccess
});
You can specify a content type header using the following code. You could put it at the top of your controller method in CI:
header("Content-Type: text/xml");
It must be before any output starts, so use it before you call your first $this->load->view().