10

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
  • Can u console what u are getting in $.each(data, function(key, value) { helpers += '<option value="'+value.id+'">'+value.title+'</option>'; }); in helper Commented Sep 6, 2018 at 4:31
  • can you please share sample results, generated by controllers with me ? Commented Sep 8, 2018 at 11:06
  • @ArashKhajelou hi, if i use serialize this is my result array:3 [ "_token" => "Ou5M0WwUziuG3h1WN3D0D2ND5nCtaKejZDUSEnwa" "product_id" => "21" "subspecifications" => "subspecifications%5B%5D=4&subspecifications%5B%5D=5&subspecifications%5B%5D=22" ] if i use val this is the result array:3 [ "_token" => "Ou5M0WwUziuG3h1WN3D0D2ND5nCtaKejZDUSEnwa" "product_id" => "21" "subspecifications" => array:1 [ 0 => "3" ] ] PS: the way val returns data is correct the issue with it is that only gets first row values when i have multiple row always return first one. Commented Sep 10, 2018 at 0:43

3 Answers 3

3
+25

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

Sign up to request clarification or add additional context in comments.

9 Comments

hi, thanks for the respond. it appears to be working however with this method it requires small changes which i'm not sure how to do it. explanation before each form sends selected options id and when i click save button it saves only those options that's why i had save button for each appended row in my blade, currently save button on any of these rows will send all selected options id from all rows, so i think it's better to have only 1 save button in total instead of 1 save button for each row. Q how can i make that happen?
for better understanding i made these images of before/after 1 ibb.co/hU1tpe 2 ibb.co/cpjDpe
If you want just one button for saving. I think better way split selects and send them on server with different names.
how can i set different names? my data are dynamic could be any amount of rows.
Can you share with me: 1) Html of page 2) Controller method
|
2

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.

15 Comments

still sending subspecifications empty as my issue part i shared the code
okay... My other idea is to try to remove the brackets [] in name="subspecifications[]" because the output of a <select multiple> already is an array...
yet getting empty subspecifications
mmm... Before the Ajax request (which you can commented out just for tests), try those console.logs: console.log( $(this).closest('form').find('select.subspecifications').length ); and console.log( $(this).closest('form').find('select.subspecifications').val() ).
I lost you... Does the first console.log returned 1 (so we're sure the element is found) And does the second shows an array with correct values?
|
0

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>

3 Comments

this is what i get with this code, error 500 + _token Ou5M0WwUziuG3h1WN3D0D2ND5nCtaKejZDUSEnwa product_id 21 subspecifications[] subspecifications[3][] 199 subspecifications[4][] […] 0 204 1 205
Error 500? I cant' tell.. That is due to the code you have on the ressource called by Ajax. That is, for sure, another problem. Now you have some data sent about each SELECT, which is good... And that was the topic of your question.
thanks anyway man, i see if others have another solutions :/ confused by this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.