How to receive formData in laravel? [duplicate] - angularjs

This question already has answers here:
How to make POST requests with the FormData API
(2 answers)
Closed 3 years ago.
I've seen many posts similar to this questions, but I can't find the solution.
This is the request in frontend(angularjs).
formData = new FormData();
let blob = dataURLtoBlob(canvas.toDataURL('image/png'));
console.log("blob", blob);
formData.append("cropped_image[]", blob);
formData.append("title", $('#title').val());
console.log($('#title').val());
console.log(formData.has('title'));
console.log(formData.has('cropped_image[]'));
console.log("formData", formData);
var req = {
method: 'POST',
url: '/admin/logos/save',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: formData,
contentType: false,
cache: false,
processData: false
}
$http(req).then(function (json) {
console.log('success');
console.log(json.data);
location.href = '/admin/logos';
});
And I've received in laravel backend.
$logo->title = $request->title;
print_r('----------------------------------\n');
print_r($request->all());
count($request->all());
foreach ($request->all() as $x => $value){
print_r($x);
print_r('sldf');
print_r($value);
}
print('-------------');
// $logo->filename = $request->filename;
print_r($request->cropped_image);
I've used several ways to receive, but $request->all() returns empty array().
Please help me.

I've solved and the request should be as follows.
var req = {
method: 'POST',
url: '/admin/logos/save',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
'Content-Type': undefined
},
transformRequest: angular.identity,
data: formData,
cache: false,
processData: false
}

You may add dataType: 'json' to your req variable
var req = {
method: 'POST',
dataType: 'json',
url: '/admin/logos/save',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: formData,
contentType: false,
cache: false,
processData: false
}
Then in your controller
dd($request->input->all());

Related

Getting 415(unsupported media type ) in ajax formdata post resuest to spring

Want to send image data through ajax to the controller .But error 415 gets .I am using angular js and send images to the controller . But error ocurs . Please help
fd= new FormData();
fd.append("image", imageall);
call(fd);
});
}
function call(fd){
$http({
method: 'POST',
contentType: "application/json; charset=utf-8",
url: "./WQF00069/update.app",
data: fd,
processData: false,
enctype:'multipart/form-data',
transformRequest: angular.identity,
cache: false,
timeout: 600000,
headers: { 'Content-Type': undefined},
}).success(function(data) {
Flash.create('info', ' Update Success Fully ', 'large-text');
`enter code here`
}).error(function(response){
console.dir(response);
Flash.create('danger','There is a Problem.Contact With Administrator', 'large-text');
});
}

Error Using Method Post AngularJs

can someone fix it, when i using postman my restfull is good but not from my client side
var req = {
method: 'POST',
url: 'http://localhost:8098/getfiles',
headers: {
'Content-Type': 'multipart/form-data',
},
data: { 'selectedFiles': 'D:\\quadtech\\Intellegent\\AppSpringBoot\\input\\bismillah.txt' }
}
return $http(req).then(function(response){console.log(response); return response;}, function(){});
error in my console is
POST http://localhost:8098/getfiles 500 ()
this is request from postman
Send using formData instead of data:
var req = {
method: 'POST',
url: 'http://localhost:8098/getfiles',
headers: {
'Content-Type': 'multipart/form-data',
},
formData: {
'selectedFiles': fs.createReadStream('D:\\quadtech\\Intellegent\\AppSpringBoot\\input\\bismillah.txt') }
}
return $http(req).then(function(response){console.log(response); return response;}, function(){});
see the docs: https://github.com/request/request#forms

Angularjs http post request - params are not reaching to server

I am trying to create post request with angularjs. This is my code for adding an supplier to server.
SupplierService.addNewSupplier = function(supplier) {
alert (supplier.name);
alert (supplier.mobile);
var Indata = {'name': supplier.name, 'mobile': supplier.mobile};
//var Indata = {'product': $scope.product, 'product2': $scope.product2 };
var req = {
url: SupplierURL,
method: 'POST',
params: Indata,
headers: {'Content-Type': 'application/json'}
};
//$http.post(SupplierURL, Indata)
$http(req)
.then(function(success){
console.log(success);
//SupplierList.push({id: data, name: supplier.name, mobile: supplier.mobile});
supplier.name = "";
supplier.mobile = "";
},function (error){
console.log(error);
alert ('Supplier add error.');
});
};
After making the request, callback is coming to error part and in console log i can see.
{error: true, message: "Failed to create supplier. Please try again", name: null, mobile: null}
Why name and mobile is not reaching to server. Same request works fine with postman(api testing tool). So i don't thing there can be anu issue in server side code. Any help will be appreciated.
From the $http documentation you can clearly see request parameters:
https://docs.angularjs.org/api/ng/service/$http
var req = {
method: 'POST',
url: 'http://example.com',
headers: {
'Content-Type': undefined
},
data: { test: 'test' }
}
$http(req).then(function(){...}, function(){...});
So, in your case you need to switch params with data:
var req = {
url: SupplierURL,
method: 'POST',
data: Indata,
headers: {'Content-Type': 'application/json'}
};

Accessing API with $http POST Content-Type application/x-www-form-urlencoded

I am trying to access this REST API, which accepts three parameters:
stationId, crusherId, monthYear
I am doing it like this in AngularJS as:
$http({
//headers: {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'},
//headers: {'Content-Type': 'application/json; charset=UTF-8'},
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'Accept': 'application/json'
},
url: 'https://myurl../api/getHPData',
method: 'POST',
data: {
stationId: 263,
crusherId: 27,
monthYear: '2016-4'
}
})
.then(function(data, status, headers, config) {
//console.log(JSON.stringify(response));
console.log(data);
})
.catch(function(error){
//console.log("Error: " + JSON.stringify(error));
console.log(error);
})
But I am always getting this:
Object {data: "{"result":"false"}", status: 200, config: Object, statusText: "OK", headers: function}
OR
{"data":"{\"result\":\"false\"}","status":200,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"headers":{"Content-Type":"application/x-www-form-urlencoded;
charset=UTF-8","Accept":"application/json"},"url":"https://myurl../api/getHPData","data":{"stationId":263,"crusherId":27,"monthYear":"2016-4"}},"statusText":"OK"}
If I change header Content-Type to:
headers: {'Content-Type': 'application/json; charset=UTF-8'},
It gives:
Object {data: null, status: -1, config: Object, statusText: "",headers: function}
OR
{"data":null,"status":-1,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"headers":{"Content-Type":"application/json;
charset=UTF-8","Accept":"application/json, text/plain,
/"},"url":"https://myurl../api/getHPData","data":{"stationId":263,"crusherId":27,"monthYear":"2016-4"}},"statusText":""}
What I am doing wrong, Please help me.
Plunker is here:
https://plnkr.co/edit/57SiCdBZB2OkhdR03VOs?p=preview
(Edit)
Note:
I can do it in jQuery as:
<script>
$(document).ready(function() {
get_homepage_data(263, 27, '2016-04');
function get_homepage_data(stationIds, crusherIds, date) {
var url = "https://myurl../api/getHPData";
var data_to_send = {
'stationId': stationIds,
'crusherId': crusherIds,
'monthYear': date
};
console.log("Value is: " + JSON.stringify(data_to_send));
//change sender name with account holder name
// console.log(data_to_send)
$.ajax({
url: url,
method: 'post',
dataType: 'json',
//contentType: 'application/json',
data: data_to_send,
processData: true,
// crossDomain: true,
beforeSend: function () {
}
, complete: function () {}
, success: function (result1) {
var Result = JSON.parse(result1);
var value_data = Result["valueResult"];
var foo = value_data["gyydt"];
console.log("Log of foo is: " + foo);
var foo2 = 0;
// 10 lac is one million.
foo2 = foo / 1000000 + ' million';
console.log(JSON.stringify(value_data["gyydt"]) + " in million is: " + foo2);
}
, error: function (request, error) {
return false;
}
});
}
}); // eof Document. Ready
</script>
Output of above script is script is:
Value is: {"stationId":263,"crusherId":27,"monthYear":"2016-04"}
XHR finished loading: POST
"https://myurl../api/getHPData".
Log of foo is: 26862094
"26862094" in million is: 26.862094 million
Which is perfect. :)
When posting form data that is URL encoded, transform the request with the $httpParamSerializer service:
$http({
headers: {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'},
url: 'https://fnrc.gov.ae/roayaservices/api/getHPData',
method: 'POST',
transformRequest: $httpParamSerializer,
transformResponse: function (x) {
return angular.fromJson(angular.fromJson(x));
},
data: {
"stationId": 263,
"crusherId": 27,
"monthYear": '2016-04'
}
})
.then(function(response) {
console.log(response);
$scope.res = response.data;
console.log($scope.res);
});
Normally the $http service automatically parses the results from a JSON encoded object but this API is returning a string that has been doubly serialized from an object. The transformResponse function fixes that problem.
The DEMO on PLNKR
The documentation says that the stationId and crusherId parameters should be arrays of strings. Also, it looks like you are sending JSON data, so make sure to set that header correctly.
$http({
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
url: 'https://fnrc.gov.ae/roayaservices/api/getHPData',
method: 'POST',
data: {
stationId: ['263'],
crusherId: ['27'],
monthYear: '2016-4'
}
})
When I change the code in your plunkr to use the corrected code above, I get the following response: "The requested resource does not support http method 'OPTIONS'."
As the other (now deleted) answer correctly mentioned, this means that there is a CORS issue. The browser is trying to send a "preflight" request before making the cross-origin request, and the server doesn't know what to do with it. You can also see this message in the Chrome console:
XMLHttpRequest cannot load
https://fnrc.gov.ae/roayaservices/api/getHPData. Response for
preflight has invalid HTTP status code 405

Post data from angular to node js route not working

I am trying to send array subjectAverage to nodejs route. I am using express route, its showing unidentified when trying to print on console.
var app = angular.module("myapp", [])
app.controller("ListController2", ['$scope','getAverage','$http',function($scope, getAverage,$http) {
$scope.subjectAverages = [{
'subjectName': '',
'yearSem': '',
'studentsAppeared': '',
'studentsPassed':'',
'percentage':'',
'average':'',
'facultyComment':''
}];
$scope.save=function(){
var data =angular.toJson($scope.subjectAverages)
var objectToSerialize={'object':data};
$http({
url: 'app',
method: "POST",
data: $.param(objectToSerialize),
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
}).success(function(data){
alert("done");
});
}
router.post('/app',function(res,req){
console.log(req.body);
});
Please guide.
Try this :
$scope.save=function(){
var data = {object : $scope.subjectAverages};
$http({
url: '/app',
method: "POST",
data: data,
headers: {
'Content-Type': 'application/json'
}
}).then(function(data){ //.success is deprecated,so use .then
alert("done");
})
.catch(function(err){//using .catch instead of .error as it is deprecated
console.log("Error in request =>", err)
});

Resources