Search code examples
phpjqueryajaxlaravelcrud

Back button not working laravel ajax crud


I am trying to go to previous page but it isn't working and somehow giving me "SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'name' cannot be null (Connection: mysql, SQL: insert into 'students' ('name', 'email', 'contact', 'course', 'updated_at','created_at') values (?, ?, ?, ?, 2023-07-12 08:59:56, 2023-07-12 08:59:56))" this error

create.blade

<div class="div2">

    <form method="post" name="form" class="create_form" action="{{ route('students.store') }}" enctype="multipart/form-data">
        @csrf
        Name <input type="text" name="name" id="name"><br><br>
        Email <input type="text" name="email" id="email"><br><br>
        Contact <input type="text" name="contact" id="contact"><br><br>
        Course <input type="text" name="course" id="course"><br><br>

        <button type="submit" class="save_create">Save</button>
        <button type="submit" class="back_create" formaction="{{ route('students.index') }}">Back</button>
    </form>
</div>

Ajax submit and back button code block

$(document).on('submit', '.create_form', function(event) {
  event.preventDefault();
  var data = $(this).serialize();
  $.ajax({
    url: "{{ route('students.store') }}",
    data: data,
    type: "POST",
    dataType: "json",
    success: function(response) {
      window.location.href = ("{{ route('students.index') }}");
    },
    error: function(error) {
      console.log("Errors :", error);
    }
  });
});

// Back button clicked on create page
$(".back_create").on("click", function(event) {
  event.preventDefault();
  $.ajax({
    type: "GET",
    url: "{{ route('students.index') }}",
    success: function(response) {
      window.location.href = ("{{ route('students.index') }}");
    }
  });
});

Route is full controller:

Route::resource('/students',StudentController::class);

I tried to put the url using

$(this).attr('formaction')

also but then the save button won't work.


Solution

  • You should change

    <button type="submit" class="back_create" formaction="{{ route('students.index') }}">Back</button>
    

    to

    <button type="button" class="back_create" data-formaction="{{ route('students.index') }}">Back</button>
    

    Because of type of button is submit will submit form instead and put this block

    // Back button clicked on create page
    $(".back_create").on("click",function(event){
       event.preventDefault();
       $.ajax({
            type: "GET",
            url: "{{ route('students.index') }}",
            success: function (response) {
                 window.location.href = ("{{ route('students.index') }}");
            }
       });
    });
    

    to the outside $(document).on('submit')...