0

I am new to Laravel 8. I have a dropdown list and an input field. I want to save the dropdown list selected item ID and input field data into the database. But this problem occurs :

"The GET method is not supported for this route. Supported methods: POST."

I am using ajax to save data.

This is my form:

<div class="form-group row">
   <label class="col-lg-3 col-form-label">Select City</label>
      <div class="col-lg-9">
          <select class="form-control" id="selectCity">
              <option selected>--- Select City ---</option>
              @foreach ($cities as $city)
              <option value="{{ $city->id }}">{{ $city->city_name }}</option>
              @endforeach
          </select>
       </div>
 </div>
 
 <div class="form-group row">
       <label class="col-lg-3 col-form-label">Add Area</label>
         <div class="col-lg-9">
           <input type="text" id="areaName" placeholder="Enter Area Name" class="form-control">
          </div>
    </div>
    <div>
       <button class="btn btn-sm btn-primary btn-outline float-right m-t-n-xs" id="addArea" type="submit">Add Area</button>
    <label> </label>
    </div>

My ajax code:

$(document).ready(function() {
        $(document).on('click', '#addArea', function(e) {
            e.preventDefault();
            var data = {
                city_id = $('#selectCity').find(":selected").val(),
                area_name = $('#areaName').val()
            }
            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });

            $.ajax({
                type: "POST",
                url: "/addArea",
                data: data,
                dataType: "json",
                success: function(response) {
                    console.log(response);
                }
            });
        });
    });

My web.php

Route::get('area', [AreaController::class, 'index']);
Route::post('addArea', [AreaController::class, 'storeArea']);

My Controller:

public function index()
    {
        $cities = DB::table('locations')
            ->orderBy('city_name', 'asc')
            ->get();

        return view('admin.pages.areas', compact('cities'));
    }

    public function storeArea(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'area_name' => 'required|max:50',
        ]);
        if ($validator->fails()) {
            return response()->json([
                'status' => 400,
                'errors' => $validator->message(),
            ]);
        } else {
            $area = new Area();
            $area->city_id = $request->input('city_id');
            $area->area_name = $request->input('area_name');
            $area->save();
            return response()->json([
                'status' => 200,
                'message' => 'Area added successfully',
            ]);
        }
    }
Atika
  • 973
  • 2
  • 5
  • 16

0 Answers0