Trying to display record using Ajax

  ajax, javascript, laravel, php

i’m currently working on a movie database.
I’m trying to make a Pop-up form to edit movies category, i have tested using the console.log to check if when clicking in some movie the data where alright and it worked.

Console.Log

But now i need to send the data to the form inputs and i’m getting errors when trying to get the values.

Error $(‘name’).val()

Blade:

<div class="modal fade" id="editModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
  <div class="modal-content">
    <div class="modal-header">
      <h5 class="modal-title" id="exampleModalLabel">Edit category</h5>
      <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
    </div>
<form method="post" action="{{ url('update-category') }}">
 @csrf
  <input type="text" name="category_id" id="category_id">
<div class="modal-body">
  <div class="col-auto">
    <label >Category name</label>
    <input type="text" class="form-control-plaintext" id="name" name="name">
  </div>
</div>
    <div class="modal-footer">
      <button type="submit" class="btn btn-primary">Save</button>
      <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
    </div>
    </form>
  </div>
</div>
</div>

<script>
  $(document).ready(function(){
    $(document).on('click','.editbtn', function(){
        var category_id=$(this).val();
           $('#editModal').modal('show');

      $.ajax({
          type:"GET",
          url:"../category/edit-category/"+category_id,
          success: function(response){
         //  console.log(response.name);
           $('#name').val(response.category.name);
          }
      });
    });
}); 
</script>

Controller:

public function edit($id){
    $category=category::find($id);//findOrFail
    return response()->json([
        'status'=>200,  //value for test only
        'name'=>$category,
    ]);
}

Thanks

Source: Laravel

Leave a Reply