I am trying to update a database record with ajax. The code below is returning a 404 error code.
Javascript
data = {
id: item_id,
our_cost: new_price,
_token: "{{csrf_token()}}",
};
$.ajax({
url: '/change_item_price/{id}/{our_cost}',
data: data,
type: 'POST',
success: function( data ) {
console.log(data);
}
});
Route
Route::post('/change_item_price/{id}/{our_cost}',[itemController::class, 'change_item_price'])->name('change_item_price');
Controller
public function change_item_price($id, $our_cost){
$get_id = Item::findOrFail($id);
DB::table('items')
->where('id', $get_id)
->update([
'our_cost' => $our_cost
]);
return Item::where('id',$id)->first();
}
2
Answers
@Olumuyiwa Thank you for your input. Your comment about the variables not being set was spot on. I changed the Ajax call as you suggested. I included the whole function:
My assumption is the id and our_cost variables weren’t set before the Ajax call except on the data object. In that case, you might want to change how you construct your url in your Ajax call. If item_id and new_price are variables also, then your url can be
But, if the item_id and new_price are hardcoded values , then you might want to make the id and our_cost variables first before calling them in your url.