I use VueJS and laravel but now I can't get parameter value, please help me to solve this problem.
my VueJS code:
getTestData:function () {
let config = {
params: {
id: 1
}
};
axios.post('{{ route('get_user_data') }}', config)
.then(function (response) {
console.log(response);
// app.posts=response.data;
})
.catch(error => {
})
},
My Controller code:
public function testData(Request $request)
{
// how to get this value?
}
My route
Route::post('get-user-data','TestController#testData')->name('get_user_data');
You don't actually need a post request to get some values out of database. A get request would be more suitable.
You need to have the param in the route definition
Route::get('get-user-data/{id}','TestController#testData')->name('get_user_data');
//If you want to use post route
Route::post('get-user-data/{id}','TestController#testData')->name('get_user_data');
Then in controller method you can get the value out of the request
public function testData(Request $request)
{
$id = $request->route('id');
}
params are the URL parameters to be sent with the request
You could retrieve input from query string in your controller as:
public function testData(Request $request)
{
$id = $request->query('id');
}
Related
I am making an application in Laravel and I need to retrieve a user from the database from javascript, from its id.
Something like:
User :: find (id);
or:
DB :: table ('users') -> find (id);
but in javascript
I would consider using AJAX.
your other JS code
...
$.ajax({
type: "POST",
url: "to your controller",
data: {
'user_id' : user_id,
},
success: function (data) {
userdata1 = data.data1;
userdata2 = data.data2;
...something
}
});
And the controller would look something like this
class SomeController extends Controller
{
public function somefunction(Request $request)
{
$user = User::find($request->user_id);
... do other stuff
return response()->json([
'data1' => someValue1;
'data2' => someValue2;
]);
}
}
If you only need User's data, you can simply use route model binding and
class SomeController extends Controller
{
public function somefunction(User $user)
{
return response()->json([
'data1' => $user->name;
'data2' => $user->addr;
]);
}
}
There might be a better solution, but it works.
Don't know how exactly your code is, but if User's data has been already sent to view from controller, you can just do
var x = "<?php echo $user->somedata ?>"
in you JS code
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.
I trying to call other route in angular, similar this
$location.path($scope.productPath+"/approveProducts/").search({ids});
I want send the list of ids to other controller but the ids are sending by url
http://localhost:8080/#/product?ids=1130&ids=1132&ids=7428&ids=15574&ids=15579&ids=15580&ids=6798968768697789
I need send ids similar a post requisition, not in a url, because i have a many ids in my call
How i do this in angular, send parameters and change my route to other controller?
I believe a better approach might be to utilize the angularjs service/factory to persist your data.
example:
.service('AngularJsService', function() {
var listOfIds = [];
return {
saveData: function(theIdsToSave) {
listOfIds = theIdsToSave;
},
getData: function () {
return listOfIds;
}
}
}
.controller('OriginatingController', function($location, AngularJsService) {
function navigateToTargetController() {
AngularJsService.saveData([1,2,3,4]);
$location.path('pathToTargetController');
}
}
.controller('TargetController', function($location, AngularJsService) {
function retrieveData() {
var ids = AngularJsService.getData();
// ids = [1,2,3,4]
}
}
You can use $http for send your params and then change your route
var req = {
method: 'POST',
url: 'http://example.com',// address for sending ids
headers: {
'Content-Type': undefined
},
data: { test: 'test' }
}
$http(req).then(function(){
// this you can to change your url
$location.path($scope.productPath+"/approveProducts/");
}, function(){...});
I am having issues with finding the correct way to send an array of objects to my API using AngularJS.
FrontEnd Code
function getPrices(articles) {
return $http.get('http://someurl/api/prices/getprices', { params: { articles: articles } }).then(function (res) {
// do something with prices
}, function (err) {
// handle error
});
}
Articles are of the type
var oneArticle = {
code: 'someCode',
quantity: 1,
stockUnit: 'piece'
}
Api code
[VersionedRoute("getprices")]
[HttpGet]
public IHttpActionResult GetPrices([FromUri]List<Article> articles) {
// do something with input
}
Article class
public class Article {
public string Code {get;set;}
public int Quantity {get;set;}
public string StockUnit {get;set;}
}
Some questions:
1) Why do I not receive any data on my API. Articles is always null
2) Is this the right approach?
Thanks
EDIT 1:
Using a post option I receive following data in my request but I still don't know how to handle it on the API.
I finally got it working.
#Tomo: Thanks for the effort
#Naimad: My apologies, you were right from the beginning.
Here is the working solution:
Frontend:
function getPrices(articles) {
return $http.get('http://someurl/api/prices/getprices', articles).then(function (res) {
// do something with prices
}, function (err) {
// handle error
});
}
Backend
[VersionedRoute("getprices")]
[HttpPost]
public IHttpActionResult GetPrices([FromBody]List<Article> articles) {
// do something with code
}
.controller('LoginController', ['$scope', '$http', function ($scope, $http) {
function getPrices(articles) {
$http.get('http://someurl/api/prices/getprices')
.success(function (data) {
articles: data
}
}
}])
Have u tried
return $http({
url: '/api/SomeCtrl/GetPrices',
method: 'POST',
data: JSON.stringify({ Article : articles }),
headers: { 'Content-Type': 'application/json' }
});
and
public IHttpActionResult GetPrices([FromUri]Article articles) {
or
[HttpPost]
public void GetPrices(Article articles)
where instead of void you put whatever you are returning
?
I want to send two variables id and commentary through an AJAX POST request.
The problem is that I don't get the POST variable but the route is reached.
JS:
$.post(Routing.generate('ajax_savecommentary', { id:id, commentary:commentary }),
function(response)
{
}, "json");
Symfony:
public function saveCommentaryAction()
{
if (!$this->get('session')->get('compte'))
return $this->redirect($this->generateUrl('accueil'));
$request = $this->container->get('request_stack')->getCurrentRequest();
$isAjax = $request->isXMLHttpRequest();
if ($isAjax)
{
$information = $this->getDoctrine()->getManager()->getRepository('CommonBundle:Information')->find($_POST['id']);
$information->setCommentaire(str_replace('\n', '\\n', $_POST['commentary']));
$this->getDoctrine()->getManager()->flush();
$response = array("code" => 100, "success" => true, 'commentary' => $_POST['commentary']);
return new Response(json_encode($response));
}
$response = array("code" => 0, "success" => false);
return new Response(json_encode($response));
}
The error:
http://localhost/MyProject/web/app_dev.php/ajax/save/commentary/?id=61&commentary=MyCommentary.
{"code":0,"success":false}
More Symfony error:
GET Parameters
Key/Value
commentary/MyCommentary
id/61
And the routing is case needed:
ajax_savecommentary:
defaults: { _controller: CommonBundle:Default:saveCommentary }
path: /ajax/save/commentary/
options:
expose: true
Try using the request passed to the Controller Action instead of retrieve it from the container. So try this:
use Symfony\Component\HttpFoundation\Request;
...
public function saveCommentaryAction(Request $request)
{
if (!$this->get('session')->get('compte'))
return $this->redirect($this->generateUrl('accueil'));
$isAjax = $request->isXMLHttpRequest();
instead of this:
public function saveCommentaryAction()
{
if (!$this->get('session')->get('compte'))
return $this->redirect($this->generateUrl('accueil'));
$request = $this->container->get('request_stack')->getCurrentRequest();
$isAjax = $request->isXMLHttpRequest();
UPDATE:
You can restrict your routing with Customized Route Matching with Conditions, as example on your case as follow:
ajax_savecommentary:
defaults: { _controller: CommonBundle:Default:saveCommentary }
path: /ajax/save/commentary/
options:
expose: true
condition: "request.isXmlHttpRequest()"
methods: [POST]
UPDATE:
There is a typo in the routing generation in the JS side:
$.post(Routing.generate('ajax_savecommentary', { id:id, commentary:commentary }),
function(response)
{
}, "json");
you pass the data as argument of the routing.generate function so it concatenate the params as query string. so try this:
$.post(Routing.generate('ajax_savecommentary'), { id:id, commentary:commentary },
function(response)
{
}, "json");
Another advice is about to use the $request object for obtain the data instead of the superglobal PHP attribute, so use:
$request->request-get('commentary');
instead of:
$_POST['commentary']
More info here in the doc.
Hope this help