简体   繁体   中英

How to send array of data to controller with ajax in laravel

I want send arrays of data to back-end at once but i can't.

issue

1. this is what i send currently

array:5 [
  "_token" => "S5s5ZTTnnP93MyXgCql0l9vhHsiqt5VWaFyEedXj"
  "product_id" => "21"
  "specification_id" => "6"
  "text_dec" => "1"
  "longtext_dec" => null
]

It should be like:

Array [
  0 = [
    data
  ]
  1 = [
    data
  ]
  2 = [
    data
  ]
]
  1. I always get same ID as specification_id while each row in my blade has different ID

Code

appending script

<script defer>
    $(document).ready(function() {
//select the category
        $('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) {
//sort the results
                        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;

//textfield and textareafield are part of my issue (appended rows)
                            if(value1['type'] == 'textfield'){
                                var my_row = $('<div class="row mt-20 ccin">');
                                $('div#dataaa').append(my_row);
                            }else{
                                var my_row = $('<div class="row mt-20 ccin">');
                                $('div#dataaa').append(my_row);
                            }

                            // second data (get values)
                            $.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>';
                                    });


//this is the part of my issue
                                    if(value1['type'] == 'textfield'){
                                        var my_html = '{{ Form::open() }}<input name="product_id" id="product_id" type="hidden" value="{{$product->id}}"><input name="specification_idd" class="specification_idd" id="specification_idd" type="hidden" value="'+vvvid+'"><div class="col-md-4">'+value1.title+'</div>';
                                        my_html += '<div class="col-md-6"><input id="text_decc" name="text_decc" placeholder="text field" class="text_decc form-control"></div>';
                                        my_html += '<div class="col-md-2"><button type="button" id="custmodalsaveee" class="custmodalsaveee btn btn-xs btn-success">Save</button>{{Form::close()}}</div>';
                                        my_row.html(my_html);
                                    }else{ //second part of my issue
                                        var my_html = '{{ Form::open() }}<input name="product_id" id="product_id" type="hidden" value="{{$product->id}}"><input name="specification_idd" class="specification_idd" id="specification_idd" type="hidden" value="'+vvvid+'"><div class="col-md-4">'+value1.title+'</div>';
                                        my_html += '<div class="col-md-6"><textarea id="longtext_decc" name="longtext_decc" placeholder="text area field" class="longtext_decc form-control"></textarea></div>';
                                        my_html += '<div class="col-md-2"><button type="button" id="custmodalsaveee" class="custmodalsaveee btn btn-xs btn-success">Save</button>{{Form::close()}}</div>';
                                        my_row.html(my_html);
                                    }


                                }
                            });
                            // second data

                        });
                    }
                });
            }
        });
    });
</script>

result of code above is like:

一

saving script the part that should be fixed

<script>
$(document).ready(function() {
  $("body").on("click", ".custmodalsaveee", function(e){
        var id = $('input[name="product_id"]').val();

        $.ajax({
          type: "post",
          url: "{{ url('admin/addnewcustomsubspecifications') }}",
          data: {
            '_token': $('input[name=_token]').val(),
            'product_id': id,
            'specification_id': $('.specification_idd').val(),
            'text_dec': $('.text_decc').val(),
            'longtext_dec': $('.longtext_decc').val(),
          },
          success: function (data) {
            alert('Specification added successfully in your product!');
          },
          error: function (data) {
            console.log('Error!', data);
          }
        });
  });
  });
</script>

controller

public function addnewcustomsubspecifications(Request $reqss){
        dd($reqss->all());

    //   $this->validate($reqss, array(
    //     'product_id' => 'required',
    //     'specification_id' => 'required',
    //     'text_dec' => 'nullable',
    //     'longtext_dec' => 'nullable',
    //   ));


    //   $add = CustomProductSpecification::create([
    //       'product_id' => $reqss->product_id,
    //       'specification_id' => $reqss->specification_id,
    //       'text_dec' => $reqss->text_dec,
    //       'longtext_dec' => $reqss->longtext_dec,
    //   ]);
    //   $parent = Specification::where('id', '=', $reqss->specification_id)->first();
    //   return response()->json(array('data'=>$add,'parent'=>$parent));
}

Any idea?

Update

html output

二

Update2

So based on suggestions i've used .map() here is my code and the results

script

$(document).ready(function() {
  $("body").on("click", ".custmodalsaveee", function(e){
        var id = $('input[name="product_id"]').val();

        var specification_idd = $( ".ccin" ).map(function() {
            return $( this ).find('.specification_idd').val();
            return $( this ).find('.text_decc').val();
            return $( this ).find('.longtext_decc').val();
        }).get();
        var text_decc = $( ".ccin" ).map(function() {
            return $( this ).find('.text_decc').val();
        }).get();
        var longtext_decc = $( ".ccin" ).map(function() {
            return $( this ).find('.longtext_decc').val();
        }).get();
  console.log(specification_idd);
  console.log(text_decc);
  console.log(longtext_decc);

        $.ajax({
//rest of it as it was...

and the console results

三

Question

  1. How do i get related results together? specification_id and text fields as 1 array
  2. how I avoid of empty values? if text_dec and longtext_dec are empty for each specification_id doesn't need to be send example specification 40 doesn't have any value in longtext_dec or text_dec no need to be send

Robert, you should directly return view from your Ajax call in your laravel method and just bind html response from the view with your new data.

That is pretty easy way of doing it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM