Tuesday, September 11, 2018

Collecting multiple data and send by ajax in laravel

Leave a Comment

I'm using ajax to send my data to controller and save it in database, before my code was working then I needed to sort my data when they append in blade after sorting them it stop working by %50.

Good to know

Here is my old code and solution of sorting my data (which caused this issue that i have now)

Logic

  1. I select set
  2. Set childs will append in blade (sorted by custom column)
  3. I choose single or multiple options and hit save button
  4. Data saves to database

More to know

My appended data (based on selected set) are include 2 types of data

  1. Custom inputs (text field & text-area field) which i can manually fill and save (still working with no issue)
  2. Dynamic select option which returns from database and i can select and save their id's (this is the issue dynamics)

Code

Script of appending data

<script defer> $(document).ready(function() {     $('select[name="selectset"]').on('change', function() {         var id = $(this).val();         if(id) {             $.ajax({                 url: '{{ url('admin/selectset') }}/'+encodeURI(id),                 type: "GET",                 dataType: "json",                 success:function(result) {                     $('div#dataaamsg').empty();                     $('div#dataaamsg').append('Use <kbd>CTRL</kbd> or <kbd>SHIFT</kbd> button to select multiple options');                     result.sort(function(a,b) {                         return (a.position > b.position) ? 1 : ((b.position > a.position) ? -1 : 0);                     });                      $.each(result, function(key1, value1) {                          var vvvid = value1.id;                          if(value1['type'] == 'textfield'){                             var my_row = $('<div class="row mt-20 ccin">');                             $('div#dataaa').append(my_row);                         }else if(value1['type'] == 'textareafield'){                             var my_row = $('<div class="row mt-20 ccin">');                             $('div#dataaa').append(my_row);                         }else{                             var my_row = $('<div class="row mt-20">');                             $('div#dataaa').append(my_row);                         }                          // second data                         $.ajax({                             url: '{{ url('admin/findsubspecification') }}/'+value1['id'],                             type: "GET",                             dataType: "json",                             success:function(data) {                                 // Check result isnt empty                                 var helpers = '';                                 $.each(data, function(key, value) {                                     helpers += '<option value="'+value.id+'">'+value.title+'</option>';                                 });                                  if(value1['type'] == 'textfield'){                                     var my_html = '{{ Form::open() }}<input name="product_id" id="product_id" type="hidden" value="{{$product->id}}"><input name="specification_id" id="specification_id" type="hidden" value="'+vvvid+'"><div class="col-md-4">'+value1.title+'</div>';                                     my_html += '<div class="col-md-6"><input id="text_dec" name="text_dec[]" placeholder="text field" class="text_dec form-control"></div>';                                     my_html += '<div class="col-md-2"><button type="button" id="custmodalsavee" class="custmodalsavee btn btn-xs btn-success">Save</button>{{Form::close()}}</div>';                                     my_row.html(my_html);                                 }else if(value1['type'] == 'textareafield'){                                     var my_html = '{{ Form::open() }}<input name="product_id" id="product_id" type="hidden" value="{{$product->id}}"><input name="specification_id" id="specification_id" type="hidden" value="'+vvvid+'"><div class="col-md-4">'+value1.title+'</div>';                                     my_html += '<div class="col-md-6"><textarea id="longtext_dec" name="longtext_dec[]" placeholder="text area field" class="longtext_dec form-control"></textarea></div>';                                     my_html += '<div class="col-md-2"><button type="button" id="custmodalsavee" class="custmodalsavee btn btn-xs btn-success">Save</button>{{Form::close()}}</div>';                                     my_row.html(my_html);                                 }else{                                     var my_html = '{{ Form::open() }}<input name="product_id" id="product_id" type="hidden" value="{{$product->id}}"><div class="col-md-4">'+value1.title+'</div>';                                     my_html += '<div class="col-md-6"><select class="subspecifications form-control tagsselector" id="subspecifications" name="subspecifications[]" multiple="multiple">'+helpers+'</select></div>';                                     my_html += '<div class="col-md-2"><button type="button" id="savedynspecto" class="savedynspecto btn btn-xs btn-success">Save</button>{{Form::close()}}</div>';                                     my_row.html(my_html);                                 }                               }                         });                         // second data                      });                 }             });         }else{             $('div#dataaa').empty();         }     }); }); </script> 

script of saving data (issue part)

<script defer>   $(document).ready(function() {    $("body").on("click", ".savedynspecto", function(e){       var form = $(this).closest('form');       var id = form.find('input[name="product_id"]').val();       // e.preventDefault();       $.ajax({         type: "post",         url: '{{ url('admin/spacssendto') }}',         data: {           '_token': $('input[name=_token]').val(),           'product_id': id,           'subspecifications': $(this).closest('form').find('select.subspecifications').val()         },         success: function (data) {           alert('Specifications added successfully.');           console.log($(this));         },         error: function (data) {           console.log(data);         }       });     });   }); </script> 

Issue

  1. When I try to save my dynamic values i cannot get id of selected option/options

    //returned data in network params _token g1GnKZvzXDztR1lqgDdjI5QOg67SfmmBhjm80fKu product_id 18 subspecifications

Ps1

I've tried to change val() to serialize() and I got

_token g1GnKZvzXDztR1lqgDdjI5QOg67SfmmBhjm80fKu product_id 18 subspecifications subspecifications%5B%5D=20&subspecifications%5B%5D=21&subspecifications%5B%5D=23&subspecifications%5B%5D=32" 

All I needed was 21,23,32 instead i got subspecifications%5B%5D= before each of them.

Ps2

I've tried to change $("body").on("click", ".savedynspecto", function(e){ that would not send any data to back-end (nothing prints in network not even error codes)

Any idea?

3 Answers

Answers 1

After the button... in the string to append, you have {{Form::close()}}</div>.

I think the </div> should come before the {{Form::close()}}.

A messed-up HTML structure can lead to strangenesses quickly.
I'm not 100% sure that is the issue... But it could.

Answers 2

Hi change this line in your code

'subspecifications': $(this).closest('form').find('select.subspecifications').val()

to

'subspecifications': $(this).closest('form').find('select.subspecifications option:selected').map(function(){ return this.value }).get()

It should help

Answers 3

You have MANY select with class subspecifications... So you have to loop through them to get their values.

<script defer>   $(document).ready(function() {    $("body").on("click", ".savedynspecto", function(e){       var form = $(this).closest('form');       var id = form.find('input[name="product_id"]').val();        // An array to store the subspecifications values.       var spec_array = [];        // A loop to go through all them.       form.find('select.subspecifications').each(function(){         spec_array.push($(this).val());       });        // e.preventDefault();       $.ajax({         type: "post",         url: '{{ url('admin/spacssendto') }}',         data: {           '_token': $('input[name=_token]').val(),           'product_id': id,           'subspecifications': spec_array  // The array containing each SELECT values         },         success: function (data) {           alert('Specifications added successfully.');           console.log($(this));         },         error: function (data) {           console.log(data);         }       });     });   }); </script> 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment