javascriptajaxlaravel

Laravel 9 Ajax Update Record Returning 404 error


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();
    }

Solution

  • 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

    url: `/change_item_price/${item_id}/${new_price}`
    

    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.

    var {id, our_cost} = data;
    url: `/change_item_price/${id}/${our_cost}`