Getting data from POST request - ajax

I'm trying to update some data of my User Entity using AJAX request with VueJS-Ressource.
Here is my AJAX request:
this.$http.post('/profile/edit', {
description: this.description
}).then(response => {
console.log(response);
}, response => {
console.log(response);
});
Here is the controller where I receive this AJAX request:
/**
* #Route("/edit", name="profile_edit")
* #Method({"POST"})
*/
public function profileEditAction(Request $request) {
if ($request->isXmlHttpRequest()) {
/* #var User $user */
$user = $this->getUser();
$description = $request->request->get( 'description');
if (isset($description)) {
$user->setDescription($description);
$this->getDoctrine()->getManager()->flush($user);
return new Response('Updated User description with success !');
}
return new Response('No description parameter found');
}
return $this->redirectToRoute('homepage');
}
My issue is that every time I'm trying to get a parameter from my request using $request->request->get('PARAMETER_NAME'), it return a null value.
Whereas I display my request from my browser, I clearly sees that i'm sending something:
Full AJAX Request: https://i.gyazo.com/825ea438b09e4df8d8287555a1c841a6.png
I hope someone could help me with this, thanks you !

Try posting the data as FromData (so that Content-Type is sent as multipart/form-data).
In VueJS, do this:
var formData = new FormData();
formData.append('description', this.description);
this.$http.post('/profile/edit', formData)
.then(response => {
console.log(response);
}, reason => {
console.log(reason);
});
Make sure in Dev Tools -> Network you see the sent data as Form Data (not as Request Payload ).
On server do var_dump( $request->request->all() ) and see what request contains.

Related

Laravel: return data from server without redirect

What I'm trying to do is call function form server and validate data in javascript function but the return statement from server make redirect before response.complete("success")
button.onclick = async function handlePurchase() {
const payment = new PaymentRequest(methods, details, options);
try {
const response = await payment.show();
// Call server logic here and validate response if OK continue
// But server response redirect here so code not completed
$('#checkout-form').submit();
$.ajax({
url: '{{route("apple-pay")}}',
type: 'post',
data: $('#checkout-form').serialize(),
success: function(data){
console.log('data :>> ', data);
}
});
await response.complete("success");
// redirect to success page
} catch (err) {
console.error("Uh oh, something bad happened", err.message);
}
}
Server function:
public function pay(Request $request)
{
$merchant_id = env('CREDIMAX_MERCHANT_ID');
$password = env('CREDIMAX_INTEGRATION_PASSWORD');
$response = Http::withBasicAuth('merchant.'.$merchant_id, $password)->put
('https://example.com/api/rest/merchant/'.$merchant_id.'/order/1530/transaction/1', $data);
return $respone->json();
}
Seperate the request you are making to the third party app and the response you are sending back to you ajax call. This is how I mean:
public function pay(Request $request)
{
$merchant_id = env('CREDIMAX_MERCHANT_ID');
$password = env('CREDIMAX_INTEGRATION_PASSWORD');
$response = Http::withBasicAuth('merchant.'.$merchant_id, $password)->put
('https://example.com/api/rest/merchant/'.$merchant_id.'/order/1530/transaction/1', $data);
return response()->json([
'success' => $response->ok() ? 1 : 0,
...
]);
}
Check the last line in the controller it says "return $respone->json();" and should be "return $response->json();" -- missing the "s" in response.

Axios GET with params request shows NULL in Laravel

I am sending some data to my laravel controller using axios get request but the laravel controller shows request null.
my axios request:
const data = {
machine_id: machine_id,
}
const api = "http://192.168.0.108:8000/api/"
const params = JSON.stringify(data)
const headers = {
"Content-Type": "application/json",
}
axios.get(api, { params: params }, headers).then((response) => {
consoleLog("response", response.data)
})
controller:
public function index(Request $request)
{
dd($request->all()); // shows null
}
If I return the response instead of dd() it shows me something like below image:
public function index(Request $request)
{
return $request->all(); // shows data
}
How can I catch the data in controller??
I had the same problem with you. This is what I've done to resolve my problem
let config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
}
}
let params = new UrlSearchParam();
params.append('var1', 'val1');
params.append('var2', 'val2');
//Finally
axios.post('gotourl', params, config).then( ( response ) => {
console.log(response.data);
});

I'm getting two session ids in one session with Laravel

I have a controller called CartController.php
In this controller I have two methods:
public function store(Request $request)
{
// we'll check to see if the order is already in db
$productOrderDetails = new \App\Cart;
$productOrderDetails->session_id = session()->getId();
$productOrderDetails->job_name = $request->jobName;
$productOrderDetails->pro_name = $request->productName;
$productOrderDetails->save();
return response()->json($request);
}
public function displayCart()
{
//dd($upsCost);
$currentSessionID = session()->getId();
$displayCart = Cart::where('session_id', $currentSessionID)->get();
dd($currentSessionID);
session(['inCartDetails' => $displayCart]);
return view('layouts.cart')->with('cartDetails', $displayCart);
}
The store method is hit by a fetch api post.
export async function postProductDetails(details) {
const url = 'http://127.0.0.1:8000/api/cartDetails';
let response = await fetch(url, {
method: 'POST',
mode: 'cors',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(details)
})
if(response.ok) {
window.location.href = "/cart";
} else {
alert("HTTP-Error: " + response.status);
}
// return response.json();
}
My problem is that I'm getting two different session ids.
When the method store is hit via the fetch post I get the session id:
HnSxCjSXflzyt4Uks3SGsEZcJEHleSR97N1RNA5l
Then when I run the method displayCart it gives me a different session id:
su8A6E3umTW1XmXf5Yhk3SHU5WUGCEpcJWXlnVIP
It's being accessed from same browser, with in a couple of minutes. Any idea why this is happening?
I would not rely on the session ID for your logic, You could however create a Cart and save the Cart ID to the session and then retrieve it:
public function store(Request $request)
{
$productOrderDetails = new \App\Cart;
$productOrderDetails->job_name = $request->jobName;
$productOrderDetails->pro_name = $request->productName;
$productOrderDetails->save();
session(['cart_id' => $productOrderDetails->id]);
return response()->json($request);
}
public function displayCart()
{
$displayCart = session('cart_id') ? Cart::find(session('cart_id')) : null;
return view('layouts.cart')->with('cartDetails', $displayCart);
}

AngularJS 2.0 http.post returns 500 (Internal server error)

I'm trying to use angular 2.0 to add a new hero via my PHP Laravel API and I always get 500 Internal server error response.
My API (laravel): Create a new hero route:
Route::group(array('prefix' => 'api/v1', 'middleware' => ['web']), function()
{
//Add a new hero
Route::post('/heroes/create', 'HeroController#store');
});
HeroController#store method: (Tested and works with a Laravel form)
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$hero = new Hero;
$hero->name = $request->name;
$hero->description = $request->description;
$hero->avatar = "None";
$hero->save();
$heroes = Hero::paginate(5);
return view('/heroes/index', [
'heroes' => $heroes
]);
}
Angular onSubmit() Method: (trying to make it work without a form..)
onSubmit(value: string): void {
let headers = new Headers();
headers.append('Content-type', 'application/x-www-form-urlencoded');
let formPayload = new URLSearchParams();
formPayload.set('name', name.value);
formPayload.set('description', desc.value);
formPayload.set('_token', _token.value);
this.http.post('http://127.0.0.1/heroWorld/public/api/v1/heroes/create',
JSON.stringify({name:'Joe',description:'wonder', _token:'knUS8vUxihTj4YJhjVkqmRBJJkVDDCABIZaRwXhN'}),
{headers:headers})
.map((res: Response) => res.json())
.subscribe(
data => { this.heroes = data;
},
err => console.error(err),
() => console.log('done');
);
What I get:
POST http://127.0.0.1/heroWorld/public/api/v1/heroes/create 500 (Internal Server Error)
What's wrong? I'm trying to fix it for several days, nothing works.
You create a form data using the URLSearchParams class but you use another object in the post method. You could try the following instead:
let formPayload = new URLSearchParams();
formPayload.set('name', name.value);
formPayload.set('description', desc.value);
formPayload.set('_token', _token.value);
this.http.post('http://127.0.0.1/heroWorld/public/api/v1/heroes/create',
formPayload.toString(), // <------
{headers:headers})

Angular $http PUT data not being received by Laravel 4 when using 'multipart/form-data'

Hallo :) I'm using a RESTful API built in Laravel 4 combined with Angular for heavy-lifting on the frontend.
The intention is to be able to create a new 'item' in the database by POSTing form data to an API (including a file). A user can also edit an item using PUT/PATCH in the same way.
For whatever reason, I can POST data (using $http) and that works fine, but if I use PUT, no data is received by Laravel. I've also tried PATCH. The data is definitely sent by $http as you can see here: http://paste.laravel.com/1alX/raw
I can tell that Laravel isn't getting/processing any data by echoing out the $input variable.
I'm not sure if this is an issue with Angular not sending data in the right way, or an Issue with Laravel not receiving/processing it correctly.
The Javascript (Somewhat simplified):
var formdata = new FormData();
// Unfortunately we cant just walk through the data with a FOR because the data is an object, not an array – We have to be explicit
// If data exists THEN add data to FormData ELSE do nothing
formdata.append('title', $scope.item.title);
formdata.append('description', $scope.item.description);
formdata.append('image', $scope.item.image);
formdata.append('tags', $scope.item.tags);
formdata.append('priority', $scope.item.priority);
edititem: function(formdata) {
// Edits a particular list
// id: the ID of the list to edit
// data: the edited list object
var promise = $http({
method: 'PUT',
url: 'http://mamp.local/api/v1/items/64',
headers: { 'Content-Type': undefined },
data: formdata,
transformRequest: angular.identity
})
.error(function(data, status, headers, config) {
debug(data, 'API FAIL - edit item');
return data;
})
.success(function(response){
debug(response.data, 'API Success - edit item');
return response.data;
});
return promise;
},
The PHP:
/**
* Update the specified resource in storage.
*
* #param int $id
* #return Response
*/
public function update($id)
{
// Try and store the new List
$item = $this->itemRepo->updateitem($id, $this->user, Input::all());
// Lets check if we have any validation errors
if (count($item->errors()))
{
return Response::json(['errors' => $item->errors()->all()], 400);
}
// No errors
else
{
return Response::json(['id' => $item->id], 200);
}
}
/**
* Updates the item
*
* #param int $id the item ID
* #param User $user
* #param array $input
*
* #return item the item
*/
public function updateitem($id, User $user, $input)
{
// Grab the item
$item = $this->finditem($id, $user);
// Fill item with new input
$item->fill($input);
// Do we have an image?
if (Input::hasFile('image'))
{
// Handle resizing of the image
$item->image = $this->imageManipulator->resize($this->imageSizes, $this->imageDir, Input::file('image'));
}
// Try and save the item
if ($item->save())
{
// item saved, save the tags
$this->tagRepo->saveTags($input['tags'], $item, $user);
}
// Return the item
return $item;
}
I hope this is enough info, let me know if clarification is needed on anything.
Fankoo! :)
Why are you doing this: headers: { 'Content-Type': undefined } ?
It should be headers: { 'Content-Type': 'application/json' }
If Laravel doesn't see the Content-Type as application/json, it won't properly grab your json post.

Resources