Why does axios always send empty object? - javascript

I'm trying to figure this out and it's driving me mad. I am trying to send an object of data using an axios post request. It goes to the file okay but the object is always empty. So when I use this code:
axios.post('php/send_email.php', {
params: {
name: 'niall'
}
})
.then(function (result) {
console.log(result)
});
And then use the php below:
<?php
echo $_POST['name'];
?>
It will always output an error of name being undefined for the result from the http request.Can anyone shed some light on this and where I am going wrong?
Also I noticed that this seems to be a problem with sending an object because when I try:
axios.post('php/send_email.php', 'niall' )
.then(function (result) {
console.log(result)
});
And then print out the array using:
<?php
print_r($_POST);
?>
It will show:
Object {data: "Array↵(↵ [niall] => ↵)↵", status: 200, statusText: "OK", headers: Object, config: Object…}

Try sending like this
axios.post('php/send_email.php', { name: 'niall' }})
instead of wrapping parameters in an extra params object.

Related

How to get JSON in Laravel from vue.js axios POST?

I have some problem with receiving JSON data from vuex with axios in my Laravel Backend.
I have vuex store like this, and I want to send it to backend on click.
order: {
delivery_id: null,
user_id: null,
is_active: true,
bill: null,
name: null,
surname: null,
father_name: null,
phone: null,
payment_type: 'cash',
delay: null,
cashback_paid: null,
card: null,
payment_screenshot: null,
cart: null,
}
In vue component I have this method:
sendOrder() {
let order = this.$store.state.order.order;
console.log(order)
axios
.post('/api/products', order, {
header: {
'Content-Type': 'application/json'
}
})
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
})
}
And this is my pretty simple Laravel Controller:
$test = json_decode($request->getContent(), true);
$test = $test['payment_type'];
return response($test);
But when I'm doing this POST request, I'm receiving empty data in response.
Also, I've tried to check my API with Postman, and it's working fine. I just send request, then go to F12 > Network > find my request and copy Request Payload source data. Then I've pasted it into Postman body (raw, json) and make request with this data to same url (http://localhost:8000/api/orders), and its return 'cash' as expected. So I decided, that it's vue.js or axios problem, but I have no idea how to fix that. Thank you!
UPDATED
I already have tried to remove Content-Type from axios, JSON.stringify order and had the same result - empty data on response.
I think, before you use order in axios you should stringify the JSON data:
let order = JSON.stringify(this.$store.state.order.order);
Second part of the answer after some comments:
Are you sure about the routes file? I would call the controller from the web.php file (same folder) with a declared function (for example mytest), like this:
Route::post('/api/products', 'ProductController#mytest');
and put your controller logic in that function:
public function mytest()
{
$test = json_decode($request->getContent(), true);
$test = $test['payment_type'];
return response($test);
}
If that doesn't work (also in combination with JSON.stringify), my only idea is a typo in your "pretty simple Laravel Controller" ;)...

Send data from Ajax to Laravel controller. Vuejs

I have a little moment that I don't understand because I'm new to development.
I'm collecting data from multi step form and want to handle all form inputs at one ajax request on my controlle. I did it successfully, but can't figure out how to use data from $request if it's an array from ajax.
I can use if it $request->input('name') but in my case I need something like $request->input('firstGrant.issue_date') because of my data format. Please tip me which way to dig.
My method:
submitCompany() {
axios.post('/onboarding', {
name: this.step1.name,
type: this.step1.type,
shares_amount: this.step2.shares_amount,
par_value: this.step2.par_value,
firstGrant: {
issue_date: this.step3.firstGrant.issue_date,
certificate: this.step3.firstGrant.certificate,
share_price: this.step3.firstGrant.share_price,
shares_amount: this.step3.firstGrant.shares_amount
}
})
.then(function (response) {
console.log(response);
alert('Information saved!');
})
.catch(function (error) {
console.log(error);
alert('Wrong!');
});
}
My Controller:
public function store(Request $request)
{
$userId = Auth::user()->id;
$issueDate = $request->input('firstGrant.issue_date'); //How to do it right way?
$certificate = $request->input('firstGrant.certificate');//How to do it right way?
$sharePrice = $request->input('firstGrant.share_price');//How to do it right way?
$sharesAmount = $request->input('firstGrant.shares_amount');//How to do it right way?
$equityGrant = EquityGrant::create([
'user_id' => $userId,
'share_id' => 91,
'vesting' => 0,
'status' => 'active',
'issue_date' => $issueDate,
'certificate' => $certificate,
'share_price' => $sharePrice,
'shares_amount' => $sharesAmount,
]); }
You might have to configure axios to send a header along with every request that will make Laravel recognize the request as being XHR. Once it does, the $request->input('x.y') statements should work.
Object.assign(axios.defaults.headers, {
'X-Requested-With': 'XMLHttpRequest',
});
If this still does not work you might also want to check whether axios properly includes the CSRF-token in a request header.

Vue-Resource upload file to PHP

I am trying to send an image through a resource and recovery in a php file but I have not succeeded, this is my JS file:
//* AJAX *//
startAsyncNews: function(){
if(this.sendimage){
var formdata = new FormData();
formdata.append("file",this.contentnew.imageFile );
console.log(this.contentnew.imageFile);
}
// POST /someUrl
this.$http.post('controllers/newsController.php', {
data:{action : this.accion_new, data_new: this.contentnew , imgf : formdata}
}).then(response => {
}, response => {
console.log("error");
});
},
imageSelect: function($event){
this.sendimage=true;
this.contentnew.imageFile =$event.target.files[0];
}
When I use the console.log = console.log (this.contentnew.imageFile), it shows me the properties of the image correctly, that is, it is sending the file well, but when I receive it in php and I do vardump I get this object ( stdclass) # 3 (0) no properties no properties and with json_decode / encode I get it empty, also try
headers: {
'content-type': 'multipart/form-data'
}
But it generates the following error:
Missing boundary in multipart/form-data POST
You need to add all your data in formdata Object using formdata.append(key,value) function.
Then you simply send formdata
formdata.append('action ',this.accion_new);
formdata.append('data_new',this.contentnew);
this.$http.post('controllers/newsController.php', {
data:formdata
});
// or just if i'm not mistaken
this.$http.post('controllers/newsController.php',formdata);
object in http request data.
I don't know what this.accion_new and this.contentnew are, but this line:
this.$http.post('controllers/newsController.php', {
data:{action : this.accion_new, data_new: this.contentnew , imgf : formdata}
})
should simply be be:
this.$http.post('controllers/newsController.php', formdata)

Showing kartik growl via ajax in yii2

Am using kartik growl and i would like to show the growl via ajax success
I have tried
This is the javascript code:
$.post({
url: "forwardpr", // your controller action
dataType: 'json',
data: {keylist: keys,user:userdata},
success: function(data) {
console.log(data);
//$.pjax.reload({container:'#forward-grid'});
$.growl( data.growl );
},
error: function(err){
alert(err);
console.log("server error");
}
});
This is the controller code:
$growl = [
'title' => "Group members updated.<hr>",
'icon' => 'glyphicon glyphicon-ok-sign',
'message' => "Successifully updated.",
'showSeparator' => true,
];
echo json_encode(['response'=>"Successifully forwarded pr(s)", 'growl' => $growl ]);
If you see TypeError: $.growl is not a function, then it means you have not included required files to AppAsset.php file.
To solve this problem, go to assets/AppAsset.php file and add:
public $css = [
// ... Something else might be here
'css/jquery.growl.css',
];
And
public $js = [
// Something else might be here
'js/core.js',
];
Because of missing .js file, you have that error in console (TypeError: $.growl is not a function). But you also must add .css file as well because without it you will not see growl, even though it works.
I believe you're using the wrong function. Here's offical docs:
"Another important update is since version 3.x you no longer call the
plugin using $.growl(...) you must use $.notify(...)."
In another words, just try using $.notify(...) instead of $.growl(...).

Angular.js Error: Expected response to contain an array but got an object although isArray is set to false

I have an angular resource factory, which returns a JSON object and looks like this:
angular.module('myApp').factory('resourceProvider', function ($resource, $http) {
return {
Attribute: $resource('http://localhost:49980/api/Attribute/:id',
{ id: '#id' }, { query: { method: 'GET', isArray: false } }),
};
});
When I 'query' the resource like this:
resourceProvider.Attribute.query(function (data) {
$scope.variable = data;
});
I get: Error: [$resource:badcfg] Error in resource configuration. Expected response to contain an array but got an object.
This seems really strange to me because I'm setting isArray to false. Furthermore the code is working fine on other pcs. So I would be really thankful if anyone had an idea where the error could come from.
Problem solved. There was a problem with the db authenication and the error message happend to be a JSON object. So there was actually a JSON object returned instead of an array.
Question1: Why are you using angulars $resource-service and not $http-service?
Question2: If you want to use $resource, why you whant to override $resource's default behavior? See Angular Docs
And im not sure but, do you have a typo in
return {
Attribute: $resource('http://localhost:49980/api/Attribute/:id',
{ id: '#id' }, { query: { method: 'GET', isArray: false } }),
};

Categories

Resources