Categories: php, jquery, ajax, laravel

Many forms per page ajax laravel

1 answer

I want to save the results without refreshing the whole page. I have multiple forms and I need to save the data of the one which clicked on the "submit" button.

At the moment, everything is saved, but it refreshes the whole page.

blog.partials._comment_replies.blade

@foreach($comment as $comments)       <form method="post" class="formmmmmmmmmmm">          {{ csrf_field() }}          <input class="form-text form-item__input" type="text" id="form-field-id" name="comment_body" value="" size="60" maxlength="128">          <input type="button" name="submit" value="submit" class="btn btn-primary">       </form>       @include('blog.partials._comment_replies', ['comment' =>$comments->replies]) @endforeach 

script

$(document).ready(function() {     $('.formmmmmmmmmmm').on('click',function(e) {         var form = $(this);         var submit = form.find("[type=submit]");         var submitOriginalText = submit.attr("value");          e.preventDefault();          var data = form.serialize();         var url = form.attr('action');         var post = form.attr('method');          if (jQuery(".formmmmmmmmmmm").length > 0) {             $(".formmmmmmmmmmm").validate({              rules: {                 comment_body: {                     required: true,                     maxlength: 100                 },               },             messages: {                 name: {                     required: "Please enter name",                     maxlength: "Your last name maxlength should be 100 characters long."                 },              },             submitHandler: function(form) {                  $.ajaxSetup({                       headers: {                           'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')                       }                   });                   jQuery('#send_form').html('Sending..');                   $.ajax({                         url:"{{ route('reply.add') }}",                         type: "POST",                         data :data,                         success: function( data ) {                             submit.attr("value", "Submitted");                         },                         beforeSend: function(){                             submit.attr("value", "Loading...");                             submit.prop("disabled", true);                         },                         error: function() {                             submit.attr("value", submitOriginalText);                             submit.prop("disabled", false);                             // show error to end user                         }                     });                 }             });          };     }); }); 

comment controller

public function replyStore(Request $request) {      $reply = new Comment;      $reply->body = $request->get('comment_body');       $reply->user()->associate($request->user());      $reply->parent_id = $request->get('comment_id');       $post = Article::find($request->get('article_id'));       $check = $post->comment()->save($reply);      $arr = array('msg' => 'Something goes to wrong. Please try again lator', 'status' => false);      if ($check) {           $arr = array('msg' => 'Successfully submit form using ajaxxxxxxxxxxxxx', 'status' => true);      }      return Response()->json($arr);    } 

All answers to this question, which has the identifier 61156731

The best answer:

First of all, let's fix your invalid HTML. Every element in DOM should be using unique id. So, make it unique (e.g. using comment id or you can even remove it if you're not using). Plus, we need to change input type to submit. And you don't have to specify form method here.

@foreach($comment as $comments)       <form class="formmmmmmmmmmm">          @csrf          <input class="form-text form-item__input" type="text" id="form-field-id-{{ $comment->id }}" name="comment_body" value="" size="60" maxlength="128">          <input type="submit" name="submit" value="Submit" class="btn btn-primary">       </form>      @include('blog.partials._comment_replies', ['comment' =>$comments->replies]) @endforeach 

And then, we need to update form submit handler.

$(document).ready(function() {     $('.formmmmmmmmmmm').submit(function (e) {         e.preventDefault();         const form = $(this);          let submit = form.find('[type=submit]');         let submitOriginalText = submit.attr('value');         let data = form.serialize();          form.validate({             rules: {                 comment_body: {                     required: true,                     maxlength: 100                 },             },             messages: {                 name: {                     required: 'Please enter name',                     maxlength: 'Your last name maxlength should be 100 characters long.'                 },              },              submitHandler: function(form) {                 $.ajaxSetup({                     headers: {                         'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')                     }                 });                  $('#send_form').html('Sending...');                  $.ajax({                     url: "{{ route('reply.add') }}",                     type: 'POST',                     data: data,                     success: function( data ) {                         submit.attr('value', 'Submitted');                     },                     beforeSend: function() {                         submit.attr('value', 'Loading...');                         submit.prop('disabled', true);                     },                     error: function() {                         submit.attr('value', submitOriginalText);                         submit.prop('disabled', false);                     }                 });             }         });     }); }); 

Removed unnecessary variables (url, post) and form existence check. This should submit a single form at a time without refreshing the page.

Last questions

how do i remove the switch on my home screen?
how to edit the JS date and time to update atuomatically?
How to utilize data stored in a multidimensional array
Powermockito not mocking URL constructor in URI.toURL() method
Android Bluetooth LE Scanner only scans when phone's Location is turned on in some devices
docker wordpress container can't connect to mysql container
How can I declare a number in java that is more than 64-bits? [duplicate]
Optaplanner solutionClass entityCollectionProperty should never return null error when simple JSON object passed to controller
Anylogic, get the time a pedestrain is in a queue
How do I fix this syntax issue with my .flex file?
Optimizing query in PHP
How to find the highest number of a column and print two columns of that row in R?
Ideas on “Error: Type com.google.firebase.iid.zzav is referenced as an interface from com.google.firebase.messaging.zzd”?
JCIFS SmbFile.exists() and SmbFile.isDirectory() return false when it exists and I can listFiles()
PHP total order
Laravel booking system design
neural net - undefined column selected
How to indicate y axis does not start from 0 in ggplot?
Fragments in backStack
Spinner how to change the data