笑故挽风 2018-09-19 05:23 采纳率: 100%
浏览 17

Ajax仅发送选择的数据

I have ajax code which is working only if i select option for all selects.

Issue

Select box 1 (option selected)
Select Box 2 (option selected)
Select Box 3 (option didn't select)

result: code 500 (won't send data)

//////////////////////

Select Box 1 (option selected)
Select Box 2 (option selected)
Select Box 3 (option selected)

result: code 200 (sending data)

Code

<script defer>
$(document).ready(function() {
    $('body').on("change", ".autosubspecifications", function() {
      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.autosubspecifications option:selected').each(function(){
        spec_array.push($(this).val());
      });

      console.log(id);
      $.ajax({
        type: "post",
        url: '{{ url('admin/spacssendto') }}',
        data: {
          '_token': $('input[name=_token]').val(),
          'product_id': id,
          'subspecifications': spec_array,
        },
        success: function (data) {
          alert('Specifications added successfully.');
          console.log($(this));
        },
        error: function (data) {
          console.log(data);
        }
      });
    });
  });
</script>

What I want

Is to send data as they selected if i choose options for two or even one of my select boxes get code 200, not to be forced to select values for all my selects.

Any idea?

Update

here is my back-end (controller)

public function spacssendto(Request $request)
{
      $this->validate($request, array(
          'product_id' => 'required',
          'subspecifications' => 'required',
        ));
        $product = Product::find($request->product_id);
        $product->subspecifications()->sync($request->subspecifications, false);
}

Sync method

What my sync method does, is to store product_id and subspecification_id into table named product_subspecification

database

one

how data are passing currently

two

Error

as my network response (when i'm not select option from all my select boxes) i get:

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`u641790295_kargr`.`product_subspecification`, CONSTRAINT `product_subspecification_subspecification_id_foreign` FOREIGN KEY (`subspecification_id`) REFERENCES `subspecifications` (`id`)) (SQL: insert into `product_subspecification` (`product_id`, `subspecification_id`) values (21, ))

Update 2

I've made some changes in order to ignore empty values of subspecification and avoiding error in back-end, here is my current code:

public function spacssendto(Request $request) {
        $this->validate($request, array(
          'product_id' => 'required',
          'subspecifications' => 'required',
        ));
        $product = Product::find($request->product_id);

        $looped = $request->subspecifications;
        $spec = [];
        foreach($looped as $loope){
            if($loope != ''){
                $spec[] = $loope;
            }
        }

        if(isset($spec)) {
            $product->subspecifications()->sync($spec, false);
        }
    }

this way i only get array items that have values (image #2 above).

So far so good,

The issue comes when I replace one of my previous choices and except being edit it will add up.

sample

1

2

3

4

Any idea how i can make that replacement happen?

PS: sync method by default does that replacement but since I've got issue with empty values and provided if's in my controller now i lost the ability of sync replacement.

  • 写回答

2条回答 默认 最新

  • weixin_33674437 2018-09-19 05:39
    关注

    Return code 500 means your backend code (behind your ajax call) is failing. What you can do is to either:

    1) fix that code on the backend to handle the missing values ie if it doesn't find what it needs - handle that situation appropriately (e.g. using the default value) so it doesn't fail

    2) or you can do the same on the client (js) side by filling out the missing values. Something like:

        ...
              // A loop to go through all of selects.
              form.find('select.autosubspecifications').each(function() 
              {
                var selectedOption = $(this).val() || "sensible-default-value";
                spec_array.push(selectedOption);
              });
    ...
    
    评论

报告相同问题?