You need to make sure to prevent the default form submission since you are submitting with JavaScript. You haven't shown your html so not sure what it looks like, but use this whereever you handle the on form submission event
event.preventDefault()
I am trying to build an e-commerce site using Laravel 9 with breeze starter kit. And now working on the order process but something I don't understand happening.
On the order page, I sent form data to Controller using Axios. But then after got the result, the page reloaded with the form data as get parameters, like this.
I sent post data on https://my.doman/order/123/4
The page reload like https://my.doman/order/123/4?user_id=someone&phone=1234-5678&amount=500
I don't understand why this is happening.
Here is my source code below.
function saveOrder() {
const form = document.querySelector("form");
const formData = new FormData(form);
const url = `{{ route('order.store') }}`;
axios.post(url, formData)
.then((res) => {
console.log(res);
if (res.status === 200) {
alert("success");
location.href = "/order/shipping/123/4";
}
})
.catch((err) => {
console.log(err);
});
}
public function preCreate($id, $quantity)
{
$product = Product::find($id);
return view('customer-info')->with('product', $product)->with('quantity', $quantity);
}
public function create($id, $quantity)
{
$product = Product::find($id);
return view('shipping-method')->with('product', $product)->with('quantity', $quantity);
}
public function store(Request $request)
{
$data = [
'user_id' => Auth::user()->id,
'phone' => $request->phone_receiver,
'zipcode' => $request->zip,
'address1' => $request->address1,
'address2' => $request->address2
];
$res = UserAddress::create($data);
$data = [
'user_id' => Auth::user()->id,
'user_address_id' => $res->id,
'total_amount' => $request->total_amount
];
$res = Order::create($data);
Log::info(response()->json(['result' => 'success'])); <-- checked here, it was success.
if (empty($res)) return response()->json(['result' => 'fail']);
return response()->json(['result' => 'success']);
}
Route::group(['prefix' => 'order'], function () {
Route::get('/{id}/{quantity}', [OrdersController::class, 'preCreate']);
Route::get('/shipping/{id}/{quantity}', [OrdersController::class, 'create']);
Route::post('/store', [OrdersController::class, 'store'])->name('order.store');
});
I don't understand why all the data is returned as URL parameters.
Which part of my code works like that?
And why the location.href part never works even the res.status part is confirmed 200 successfully.
Please anyone help me to figure out what's wrong here?
You need to make sure to prevent the default form submission since you are submitting with JavaScript. You haven't shown your html so not sure what it looks like, but use this whereever you handle the on form submission event
event.preventDefault()
Please or to participate in this conversation.