Vue Resource Post Request Content-Type - php

Vue-Resource Post Request:
this.$http.post(form.action, new FormData(form)).then(function (response) {
FetchResponse.fetch(this, response.data)
})
Request are Send as Content-Type:"application/json;charset=utf-8" But No data can be displayed by PHP Post.
Set Up Header Vue-Resource:
request.headers.set('Content-Type', '');
But Request Content-Type:", multipart/form-data; boundary=----WebKitFormBoundaryTsrUACAFB1wuhFOR"
there is a comma at the beginning of the query.
Jquery Post Request:
$.ajax({
url : form.action,
type : 'POST',
data : new FormData(form),
success : function (reqData) {
FetchResponse.fetch(ss, reqData)
},
});
The same query works seamlessly with jQuery. jQuery Content-Type: "multipart/form-data; boundary=----WebKitFormBoundaryTsrUACAFB1wuhFOR"
Issue:
https://github.com/vuejs/vue-resource/issues/398

Please try instead to post a simple JSON object and enable the 'emulateJSON' vue-resource option:
const formData = {
someProp: this.someProp,
someValue: 'some value'
};
this.$http.post(this.postUrl, formData, {emulateJSON: true})
.then(response => {
console.log(response.body);
}, response => {
console.error(response.body);
});

Related

$_FILES is empty when sending a POST request using axios in ReactJs

I have an array of Files that i want to retrieve in php along with some other string params, When i send the file(s) from the FormData in React they're being received as json in php :
"{"dataForm":{"Files":[{"path":"aust.jpeg"}]},"headers":{"content-type":"multipart/form-data"}}"
I want to receive them in $_FILES instead for obvious reasons, is it possible to do that and read the rest of the params as json in php ? Also my php.ini is fully configured to allow file uploads
Here is the Reactjs code :
import axios from 'axios';
const sendMail = (data, uploadedFiles) => {
const dataForm = new FormData();
dataForm['Files'] = uploadedFiles; // Here uploadedFiles is an array of files
console.log(dataForm['Files'])
axios.post('http://localhost/bickdata/mail/SendMail.php', {
dataForm,
headers: {
'content-type': 'multipart/form-data'
}
}) .then(function (response) {
console.log(response);
});
}
Thanks in advance !
This is how you upload multiple files in React
const dataForm = new FormData();
uploadedFiles.map(file =>
dataForm.append("Files[]", file);
}
Turns out axios.post() sends all the data as JSON by default which is why the files are not being interpreted as File objects in php, I did some minor changes with the post request and i finally received my files, here's the updated code :
(i'm only sending one file from the array for now, but i'm pretty sure it's the same procedure for an array of files)
dataForm.append(
"potato",
uploadedFiles[0],
uploadedFiles[0].name
);
axios({
method: 'post',
url: 'http://localhost/bickdata/mail/SendMail.php',
data: dataForm,
headers: {'Content-Type': 'multipart/form-data' }
})
.then(function (response) {
//handle success
console.log(response);
})
.catch(function (response) {
//handle error
console.log(response);
});
In my case, it was 2MB upload_max_filesize in php.ini. Please see
PHP - empty $_POST and $_FILES - when uploading larger files
I pulled out my hair for 2 hours. Nothing wrong with Axios. I didn't need to specify headers.
Ref MDN Web Docs, the FormData's encoding type were set to multipart/form-data. Taking the sample code cue, I managed to upload a file with this:
const api = axios.create({ baseURL: '<?php $this->getUrl() ?>' })
editPost = function(e) {
// target is the input element
const target = typeof e === 'string' ? document.querySelector(e) : e.target;
let form = new FormData();
form.append(target.name, target.type == 'file' ? target.files[0] : target.value);
form.append('sid', '<?php echo $this->getSessionId() ?>');
api.post('/editPost', form)
.then((response) => {
//...
})
.catch(() => {
//...
};

angularjs $http post request making string data into an object

When I send data into PHP file using AngularJS $http post, the data type is supposed to be a string. But when I try to get the output data from PHP file (I just simply echo $_POST['string']) by the then function, it automatically changes to [object Object] type somehow.
Here is the code:
JS:
$http({
method:"POST",
type:"json",
url:"./forms/crud.php",
data:{id:cId}
}).then(function (d) {
alert(d.config.data.id);
console.log(d);
})
PHP:
if(is_post_quest()){
echo $_POST['id'];
}
Output on console:
{data: "", status: 200, headers: ƒ, config: {…}, statusText: "OK", …}
The way I can access the id data is by typing d.config.data.id which is not exactly what I want.
I think the problem is that get data from AngularJs in PHP file is kinda different from that using AJAX.
For AJAX, geting data literally just need to use $_POST['id'].
However, for AngularJS HTTP POST request, need to type something like:
$data = json_decode(file_get_contents("php://input"));
echo $data->id;
And here is how it look right now.
{data: "568", status: 200, headers: ƒ, config: {…}, statusText: "OK", …}
You should do it like this
$http({
method:"POST",
type:"json",
url:"./forms/crud.php",
data:JSON.stringify({id:cId})
}).then(function (d) {
alert(d.config.data.id);
console.log(d);
})
I will do an example for requesting data from angular and getting into php code, then getting result back.
//Angular code
var url = 'your url';
var data = {
"type": "json",
};
//Ajax call
$http.post(url, data).success(function (data, status, headers, config) {
var result = angular.fromJson(data);
}).error(function (data, status, headers, config) {
$scope.preloader=false;
});
//PHP Code
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
echo json_encode(['data' => $this->request->data, 'status' => true, 'error' => '']);

Passing an array trought $_POST to my php then trying to recover and use it in a foreach [duplicate]

In the code below, the AngularJS $http method calls the URL, and submits the xsrf object as a "Request Payload" (as described in the Chrome debugger network tab). The jQuery $.ajax method does the same call, but submits xsrf as "Form Data".
How can I make AngularJS submit xsrf as form data instead of a request payload?
var url = 'http://somewhere.com/';
var xsrf = {fkey: 'xsrf key'};
$http({
method: 'POST',
url: url,
data: xsrf
}).success(function () {});
$.ajax({
type: 'POST',
url: url,
data: xsrf,
dataType: 'json',
success: function() {}
});
The following line needs to be added to the $http object that is passed:
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
And the data passed should be converted to a URL-encoded string:
> $.param({fkey: "key"})
'fkey=key'
So you have something like:
$http({
method: 'POST',
url: url,
data: $.param({fkey: "key"}),
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
})
From: https://groups.google.com/forum/#!msg/angular/5nAedJ1LyO0/4Vj_72EZcDsJ
UPDATE
To use new services added with AngularJS V1.4, see
URL-encoding variables using only AngularJS services
If you do not want to use jQuery in the solution you could try this. Solution nabbed from here https://stackoverflow.com/a/1714899/1784301
$http({
method: 'POST',
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: xsrf
}).success(function () {});
I took a few of the other answers and made something a bit cleaner, put this .config() call on the end of your angular.module in your app.js:
.config(['$httpProvider', function ($httpProvider) {
// Intercept POST requests, convert to standard form encoding
$httpProvider.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
$httpProvider.defaults.transformRequest.unshift(function (data, headersGetter) {
var key, result = [];
if (typeof data === "string")
return data;
for (key in data) {
if (data.hasOwnProperty(key))
result.push(encodeURIComponent(key) + "=" + encodeURIComponent(data[key]));
}
return result.join("&");
});
}]);
As of AngularJS v1.4.0, there is a built-in $httpParamSerializer service that converts any object to a part of a HTTP request according to the rules that are listed on the docs page.
It can be used like this:
$http.post('http://example.com', $httpParamSerializer(formDataObj)).
success(function(data){/* response status 200-299 */}).
error(function(data){/* response status 400-999 */});
Remember that for a correct form post, the Content-Type header must be changed. To do this globally for all POST requests, this code (taken from Albireo's half-answer) can be used:
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
To do this only for the current post, the headers property of the request-object needs to be modified:
var req = {
method: 'POST',
url: 'http://example.com',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: $httpParamSerializer(formDataObj)
};
$http(req);
You can define the behavior globally:
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
So you don't have to redefine it every time:
$http.post("/handle/post", {
foo: "FOO",
bar: "BAR"
}).success(function (data, status, headers, config) {
// TODO
}).error(function (data, status, headers, config) {
// TODO
});
As a workaround you can simply make the code receiving the POST respond to application/json data. For PHP I added the code below, allowing me to POST to it in either form-encoded or JSON.
//handles JSON posted arguments and stuffs them into $_POST
//angular's $http makes JSON posts (not normal "form encoded")
$content_type_args = explode(';', $_SERVER['CONTENT_TYPE']); //parse content_type string
if ($content_type_args[0] == 'application/json')
$_POST = json_decode(file_get_contents('php://input'),true);
//now continue to reference $_POST vars as usual
These answers look like insane overkill, sometimes, simple is just better:
$http.post(loginUrl, "userName=" + encodeURIComponent(email) +
"&password=" + encodeURIComponent(password) +
"&grant_type=password"
).success(function (data) {
//...
You can try with below solution
$http({
method: 'POST',
url: url-post,
data: data-post-object-json,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for (var key in obj) {
if (obj[key] instanceof Array) {
for(var idx in obj[key]){
var subObj = obj[key][idx];
for(var subKey in subObj){
str.push(encodeURIComponent(key) + "[" + idx + "][" + encodeURIComponent(subKey) + "]=" + encodeURIComponent(subObj[subKey]));
}
}
}
else {
str.push(encodeURIComponent(key) + "=" + encodeURIComponent(obj[key]));
}
}
return str.join("&");
}
}).success(function(response) {
/* Do something */
});
Create an adapter service for post:
services.service('Http', function ($http) {
var self = this
this.post = function (url, data) {
return $http({
method: 'POST',
url: url,
data: $.param(data),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
}
})
Use it in your controllers or whatever:
ctrls.controller('PersonCtrl', function (Http /* our service */) {
var self = this
self.user = {name: "Ozgur", eMail: null}
self.register = function () {
Http.post('/user/register', self.user).then(function (r) {
//response
console.log(r)
})
}
})
There is a really nice tutorial that goes over this and other related stuff - Submitting AJAX Forms: The AngularJS Way.
Basically, you need to set the header of the POST request to indicate that you are sending form data as a URL encoded string, and set the data to be sent the same format
$http({
method : 'POST',
url : 'url',
data : $.param(xsrf), // pass in data as strings
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
});
Note that jQuery's param() helper function is used here for serialising the data into a string, but you can do this manually as well if not using jQuery.
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
Please checkout!
https://uncorkedstudios.com/blog/multipartformdata-file-upload-with-angularjs
For Symfony2 users:
If you don't want to change anything in your javascript for this to work you can do these modifications in you symfony app:
Create a class that extends Symfony\Component\HttpFoundation\Request class:
<?php
namespace Acme\Test\MyRequest;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\ParameterBag;
class MyRequest extends Request{
/**
* Override and extend the createFromGlobals function.
*
*
*
* #return Request A new request
*
* #api
*/
public static function createFromGlobals()
{
// Get what we would get from the parent
$request = parent::createFromGlobals();
// Add the handling for 'application/json' content type.
if(0 === strpos($request->headers->get('CONTENT_TYPE'), 'application/json')){
// The json is in the content
$cont = $request->getContent();
$json = json_decode($cont);
// ParameterBag must be an Array.
if(is_object($json)) {
$json = (array) $json;
}
$request->request = new ParameterBag($json);
}
return $request;
}
}
Now use you class in app_dev.php (or any index file that you use)
// web/app_dev.php
$kernel = new AppKernel('dev', true);
// $kernel->loadClassCache();
$request = ForumBundleRequest::createFromGlobals();
// use your class instead
// $request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
Just set Content-Type is not enough, url encode form data before send.
$http.post(url, jQuery.param(data))
I'm currently using the following solution I found in the AngularJS google group.
$http
.post('/echo/json/', 'json=' + encodeURIComponent(angular.toJson(data)), {
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
}).success(function(data) {
$scope.data = data;
});
Note that if you're using PHP, you'll need to use something like Symfony 2 HTTP component's Request::createFromGlobals() to read this, as $_POST won't automatically loaded with it.
AngularJS is doing it right as it doing the following content-type inside the http-request header:
Content-Type: application/json
If you are going with php like me, or even with Symfony2 you can simply extend your server compatibility for the json standard like described here: http://silex.sensiolabs.org/doc/cookbook/json_request_body.html
The Symfony2 way (e.g. inside your DefaultController):
$request = $this->getRequest();
if (0 === strpos($request->headers->get('Content-Type'), 'application/json')) {
$data = json_decode($request->getContent(), true);
$request->request->replace(is_array($data) ? $data : array());
}
var_dump($request->request->all());
The advantage would be, that you dont need to use jQuery param and you could use AngularJS its native way of doing such requests.
Complete answer (since angular 1.4). You need to include de dependency $httpParamSerializer
var res = $resource(serverUrl + 'Token', { }, {
save: { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
});
res.save({ }, $httpParamSerializer({ param1: 'sdsd', param2: 'sdsd' }), function (response) {
}, function (error) {
});
In your app config -
$httpProvider.defaults.transformRequest = function (data) {
if (data === undefined)
return data;
var clonedData = $.extend(true, {}, data);
for (var property in clonedData)
if (property.substr(0, 1) == '$')
delete clonedData[property];
return $.param(clonedData);
};
With your resource request -
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
This isn't a direct answer, but rather a slightly different design direction:
Do not post the data as a form, but as a JSON object to be directly mapped to server-side object, or use REST style path variable
Now I know neither option might be suitable in your case since you're trying to pass a XSRF key. Mapping it into a path variable like this is a terrible design:
http://www.someexample.com/xsrf/{xsrfKey}
Because by nature you would want to pass xsrf key to other path too, /login, /book-appointment etc. and you don't want to mess your pretty URL
Interestingly adding it as an object field isn't appropriate either, because now on each of json object you pass to server you have to add the field
{
appointmentId : 23,
name : 'Joe Citizen',
xsrf : '...'
}
You certainly don't want to add another field on your server-side class which does not have a direct semantic association with the domain object.
In my opinion the best way to pass your xsrf key is via a HTTP header. Many xsrf protection server-side web framework library support this. For example in Java Spring, you can pass it using X-CSRF-TOKEN header.
Angular's excellent capability of binding JS object to UI object means we can get rid of the practice of posting form all together, and post JSON instead. JSON can be easily de-serialized into server-side object and support complex data structures such as map, arrays, nested objects, etc.
How do you post array in a form payload? Maybe like this:
shopLocation=downtown&daysOpen=Monday&daysOpen=Tuesday&daysOpen=Wednesday
or this:
shopLocation=downtwon&daysOpen=Monday,Tuesday,Wednesday
Both are poor design..
This is what I am doing for my need, Where I need to send the login data to API as form data and the Javascript Object(userData) is getting converted automatically to URL encoded data
var deferred = $q.defer();
$http({
method: 'POST',
url: apiserver + '/authenticate',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
transformRequest: function (obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: userData
}).success(function (response) {
//logics
deferred.resolve(response);
}).error(function (err, status) {
deferred.reject(err);
});
This how my Userdata is
var userData = {
grant_type: 'password',
username: loginData.userName,
password: loginData.password
}
The only thin you have to change is to use property "params" rather than "data" when you create your $http object:
$http({
method: 'POST',
url: serviceUrl + '/ClientUpdate',
params: { LangUserId: userId, clientJSON: clients[i] },
})
In the example above clients[i] is just JSON object (not serialized in any way). If you use "params" rather than "data" angular will serialize the object for you using $httpParamSerializer: https://docs.angularjs.org/api/ng/service/$httpParamSerializer
Use AngularJS $http service and use its post method or configure $http function.

Angularjs - Cannot pass parameter

I'm using Angularjs for my mobile app project. My problem is I can't pass my all my parameters to my own API. My API can't detect any post parameters that my app send to it.
$http.post("http://xxxxxxxx/api/verify_login.php", {
"username": "admin",
"password": "12345678",
"secret_key": "123456789"
}).success(function(data, status, headers, config) {
alert(JSON.stringify(data));
}).error(function(data, status, headers, config) {
alert(JSON.stringify(status));
});
If using Postman it works.
how about this :
var postData = '{"username":"'+varUsername+'", "password" : "'+varPassword+'", "secret_key" : "'+varSecretyKey+'"}';
$http({
method: 'POST',
url: 'http://xxxxxxxx/api/verify_login.php',
data: postData,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(response) {
$scope.result = response;
alert(JSON.stringify(data));
});
This will post data as :
username=hisname&password=hispassword&secret_key=hiskey
keep in mind that, angularjs will automatically convert your postdata as JSON.
Looks like this StackOverflow answer helps solve half the problem. Look at the accepted answer. To paraphase the quote on this post:
By default, jQuery transmits data using Content-Type: x-www-form-urlencoded and the familiar foo=bar&baz=moe serialization. AngularJS, however, transmits data using Content-Type: application/json and { "foo": "bar", "baz": "moe" } JSON serialization, which unfortunately some Web server languages—notably PHP—do not unserialize natively.
There is a nice way to get it do this - override the default transformRequest - this is show in a nice post by Ben Nadel here - Here's a snippet:
var request = $http({
method: "post",
url: "process.cfm",
transformRequest: transformRequestAsFormPost,
data: {
id: 4,
name: "Kim",
status: "Best Friend"
}
});
He has a fairly simple implementation - if you find that this doesn't work for you, you can use the a detailed version here - you can inject this factory in your controller.
.factory("transformRequestAsFormPost", function() {
function transformRequest(data, getHeaders) {
var headers = getHeaders();
headers["Content-type"] =
"application/x-www-form-urlencoded; charset=utf-8";
return (serializeData(data));
}
return (transformRequest);
function serializeData(data) {
if (!angular.isObject(data)) {
return ((data === null) ? "" : data.toString());
}
var buffer = [];
for (var name in data) {
if (!data.hasOwnProperty(name)) {
continue;
}
var value = data[name];
buffer.push(encodeURIComponent(name) + "=" + encodeURIComponent((value ===
null) ? "" : value));
}
var source = buffer.join("&").replace(/%20/g, "+");
return (source);
}
});

Sending XML through AJAX

I create a xml document in jQuery as following
var xmlDocument = $('<xml/>');
var foo = $('<foo/>');
var bar = $('<bar/>');
foo.append(bar);
xmlDocument.append(foo);
and try to forwards it to the server.
$.ajax({
url : 'js/foobar.php',
type : 'POST',
precessData : false,
contentType : 'text/xml',
data : xmlDocument,
sucess : function( data ) {
alert('success');
},
error : function() {
alert('failed to send ajax request');
},
complete : function() {
alert('ajax request completed');
}
});
Even if the server echos a 'foo' only, I get the alert('ajax request completed') and not the alert('success'). What am I doing wrong? Is it the way I'm creating the xml document or is it the way I forward it to the server?
An ajax request without a xml document works fine and I get the 'foo' back.
UPDATE #1
After changing precessData to processData and sucess to success i get the failed to send ajax request dialog.
When I change the data parameter in the ajax method to
$.ajax({
...
data : {
data: xmlDocument
},
...
});
I also get the failed to send ajax request dialog.
The code on the server side should be fine cause it's only
<?php
echo 'foo';
?>
UPDATE #2
I converted my string as in AndreasAL's answer
// Convert to string instead of DOM Elements
xmlDocument = $("<wrap/>").append(xmlDocument).html();
// Url encode the string
xmlDocument = encodeURIComponent(xmlDocument);
but i still get the same dialog box (failed to send the ajax request). So i thought the error could be in my xml document and overwrote my xml document by using the code snipplet from AndreasAL's answer.
xmlDocument = $('<xml/>');
foo = $('<foo/>').appendTo(xmlDocument);
bar = $('<bar/>').appendTo(foo);
Still the same behaviour.
So I checked my xml document again and printed it in a dialog box and it looks fine.
I'm running out of ideas where the error could be ...
EDIT:
You have a typo - it's not precessData it's processData
$.ajax({
url : 'js/foobar.php',
type : 'POST',
precessData : false, // change to processData
and again in sucess which should be success
Try:
var xmlDocument = $('<xml/>'),
foo = $('<foo/>').appendTo(xmlDocument),
bar = $('<bar/>').appendTo(foo);
// Convert to string instead of DOM Elements
xmlDocument = $("<wrap/>").append(xmlDocument).html();
// Url encode the string
xmlDocument = encodeURIComponent(xmlDocument);
$.ajax({
url : 'js/foobar.php',
type : 'POST',
processData : false,
contentType : 'text/xml',
data : xmlDocument,
success : function( data ) {
alert('success');
},
error : function() {
alert('failed to send ajax request');
},
complete : function() {
alert('ajax request completed');
}
});
You are using jQuery Object through the entire process.
Write your XML like this, concatenating the string together. Not making them as DOM Object.
var xmlDocument = '<xml/>';
xmlDocument += '<foo/>';
xmlDocument += '<bar/>';
Then post it, like this
$.ajax({
url : 'js/foobar.php',
type : 'POST',
precessData : false,
contentType : 'text/xml',
data : {
data: xmlDocument //wrapped inside curly braces
},
// Here is your spelling mistake
success : function( data ) {
alert('success');
},
error : function() {
alert('failed to send ajax request');
},
complete : function() {
alert('ajax request completed');
}
});
Finally, I decided to convert the xml document and send it as a string to the server.
$xmlString = $(xmlDocument).html();
Due to the fact, that I only have to store the recieved data, it makes no difference if I'm revieving it as string or xml.
I only had to change my ajax request at everything works fine now.
$.ajax({
url : 'js/foobar.php',
type : 'POST',
data : 'data=' + xmlString,
success : function( data ) {
alert(data);
},
error : function() {
alert('failed to send ajax request');
},
complete : function() {
alert('ajax request completed');
}
});
I think you have a bug on your code on success
$.ajax({
url : 'js/foobar.php',
type : 'POST',
precessData : false,
contentType : 'text/xml',
data : xmlDocument,
success : function( data ) {
alert('success');
},
error : function() {
alert('failed to send ajax request');
},
complete : function() {
alert('ajax request completed');
}
});
use $.parseXML to manipulate XML , you are treating the xml as if it is html
http://api.jquery.com/jQuery.parseXML/
use this:
data : { xml: xmlDocument }
Post values need a key

Categories