简体   繁体   中英

Updating table using form with AJAX

I am new to Laravel and I am trying to update a table of data using an Ajax call. The 'rent' field in the table should be the only field that can be edited, but I have been unable to get the changes to persist to the database as of yet. The error I am receiving at present states that my 'rent' index is undefined, which I don't understand as the current data for the rent field is being displayed in the table - it is only when I try to update this field that the error appears. When using Ajax, the 'rent' field does not appear to be recognised and I receive the error message 'undefined index: 'rent''. When I try to update the table without Ajax the error message I receive is 'SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'rent' cannot be null'. I will include snippets of my code for clarity - any help with this issue, or suggestions of how to better achieve my goal would be greatly appreciated!

Index page (Form for the datatable)

<div class="flex justify-end content-end items-end mt-4">
  <button type="button" class="shadow md:shadow-lg rounded-full mr-4 font-bold px-10 grantors-btn text-white">
    <img class="inline-block mb-2 mt-2 w-4 h-4 mr-2" src="../../img/Icon-plus-white.png" alt="plus icon">
    <a class="no-underline inline-block text-white " onclick="toggleModal('modal-example-small')">New Apparatus Code</a>
  </button>
</div>
<table id="datatable" class="stripe hover dt-responsive display nowrap" style="width:100%; padding-top: 1em;  padding-bottom: 1em;">
      <thead>
        <tr>
          <th>ID</th>
          <th >Apparatus Code</th>
          <th>Description</th>
          <th>Rent</th>
          <th></th>
        </tr> 
      </thead>
<!--start of for loop-->

@foreach ($apparatusCodes as $apparatusCode)

      <tbody>
<form method="POST" action= "{{ route('apparatus_codes.update' , $apparatusCode->id )}}" class="is-readonly" > 
                @csrf
                @method('PUT')


         <tr id="table{{ $apparatusCode->id}}" data-target=".table{{ $apparatusCode->id}}"> 
          <td class="main-bg"> {{ $apparatusCode->id}} </td>
          <td class="main-bg">{{ $apparatusCode->apparatus_code}} </td>  
          <td class="main-bg"> {{ $apparatusCode->description}}</td>
          <td class="data main-bg" id ="rent" name ="rent" value = "{{ $apparatusCode->rent}}">{{ $apparatusCode->rent}}</td>
                        
          <td class="main-bg"> <img class="mb-1 duration-300  h-6 w-6" 
            src="../img/Icon-arrow-dropdown-white.png" data-toggle="collapse" data-target=".table{{ $apparatusCode->id}}" alt="arrow down"/></a>
          </td>
          <td><button type="button" id="edit-button" class="edit"><img class="mb-1 duration-300 ml-4 inset-0 h-6 w-6" src="../img/edit-icon.svg" alt="edit"></button>
          <button id="save-button" class="save"><img class="mb-1 duration-300 ml-4 inset-0 h-6 w-6" src="/../../img/save-icon.svg" alt="save icon"></button>
      </div>
        <div class="row">
            @if ($errors->any()) <span>{{ $errors }}</span> @endif
        </div>
        </td>

      </form>

Index page (Ajax call)

<script>
        $(document).ready(function(){

    $(document).on("click", "#save-button", function() { 
        var url = "{{ route('apparatus_codes.update' , $apparatusCode->id )}}";
        var rent = $("#rent").val();
        console.log(rent);
        $.ajax({
            url: url,
            type: "POST",
            cache: false,
            data:{ 'rent':rent
                

            },
            success: function(dataResult){
                dataResult = JSON.parse(dataResult);
             if(dataResult.statusCode)
             {
                window.location = "{{ route('apparatus_codes.index' , $apparatusCode->id )}}";
             }
             else{
                 alert("Internal Server Error");
             }
                
            }
        });
    }); 
});

    </script>

Upadate Method in Controller

public function update(ApparatusCodesRequest $request, $id)
    {
    
        $validated = $request->validated();
         // find selected apparatus code details
         $apparatusCodes = ApparatusCodes::find($id);
         $apparatusCodes->rent = $request->input('rent');

        
        //$rent = $_POST['rent'];
         if (empty($rent)) {
           echo "Rent is empty";
         } else {
        echo 'rent is'. $_POST['rent'];
         }

Routes file

Route::post('/apparatus_codes/{id}', [App\Http\Controllers\ApparatusCodesController::class, 'update'] )->name('apparatus_codes.update');

With Laravel there is no need, and in fact, you should never use $_POST at all. If you are using a framework, let the framework handle and sanitise your input.

public function update(ApparatusCodesRequest $request, $id)
{
     // find selected apparatus code details
     $apparatusCodes = ApparatusCodes::find($id);
     $apparatusCodes->rent = $request->input('rent');
     $apparatusCodes->save();

     // dd($request->input('rent'));
}

Also, the request will already be validated before it even hits your controller. So there is no need to call $validated = $request->validated() either.

By the way, you have an issue in your JS when accessing the value of "rent". Change your JS like so:

// Instead of 
var rent = $("#rent").val();

// Change it for
var rent = $("#rent").text();

.val() should only be used for input fields. Or you could alternatively add an input field to render the value coming from the backend and leave the JS intact. Like so:

<td class="data main-bg">
    <input id="rent" name="rent" type="text" value="{{ $apparatusCode->rent }}" />
</td>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM