-1

I have used an ajax request using laravel api. In this i select a boat on basis of which its accessories ccomes up with categories and sub categoreis and then the accessory to be selected. The following is my sscript but I am unable to find the issue due to which the accessory is not showed up. The javascript code is:

$(document).ready(function () {
  // Initialize Select2 for accessory_discount class
  $(".accessory_discount").select2();

  var selectedAccessoryIds = []; // Array to store selected accessory IDs

  $("#boat-select").change(function () {
    var selectedBoats = $(this).val();
    var $accessorySelect = $("#accessory-select");

    // Clear the existing options and selected accessory IDs
    $accessorySelect.empty();
    $accessorySelect.append('<option value="">Select an accessory</option>');
    selectedAccessoryIds = [];

    if (selectedBoats.length > 0) {
      console.log("Selected Boats: ", selectedBoats);

      $.ajax({
        url: route("custom-boat-discounts.get-accessories"),
        type: "POST",
        data: { boats: selectedBoats },
        success: function (response) {
          console.log("Response: ", response);

          if (response.success) {
            var data = [];

            $.each(response.accessories, function (index, boat_cat) {
              var catGroup = {
                text: boat_cat.ltitle,
                children: [],
              };

              $.each(boat_cat.sub_categories, function (index, boat_sub_cat) {
                var subCatGroup = {
                  text: boat_sub_cat.ltitle,
                  children: [],
                };

                $.each(
                  boat_sub_cat.sub_sub_categories,
                  function (index, boat_sub_sub_cat) {
                    subCatGroup.children.push({
                      id: boat_sub_sub_cat.id,
                      text: boat_sub_sub_cat.ltitle,
                      cat: boat_cat.ltitle,
                      subCat: boat_sub_cat.ltitle,
                    });
                  }
                );

                catGroup.children.push(subCatGroup);
              });

              data.push(catGroup);
            });

            // Initialize Select2 with the new data
            $accessorySelect.select2({
              data: data,
              templateResult: formatAccessory,
              templateSelection: formatAccessorySelection,
              allowClear: true,
              multiple: false, // Allow single selection
            });

            // Trigger change event to update Select2 with new data
            $accessorySelect.trigger("change");

            // Add event listener for select and unselect events
            $accessorySelect.on(
              "select2:select select2:unselect",
              function (e) {
                selectedAccessoryIds = $(this).val() || [];
                console.log("Selected Accessory IDs:", selectedAccessoryIds);

                // Update hidden input field with selected IDs
                $("#selected-accessory-ids").val(
                  JSON.stringify(selectedAccessoryIds)
                );
              }
            );
          } else {
            console.error("Response success is false: " + response.message);
          }
        },
        error: function (xhr, status, error) {
          console.error("AJAX Error: ", status, error);
        },
      });

      function formatAccessory(accessory) {
        if (!accessory.id) {
          var $accessory = $("<span>" + accessory.text + "</span>");
          if (
            accessory.element &&
            $(accessory.element).parent().is("optgroup")
          ) {
            $accessory.addClass("ml-2");
          }
          return $accessory;
        }
        return $("<span>" + accessory.text + "</span>");
      }

      function formatAccessorySelection(accessory) {
        if (!accessory.id) {
          return accessory.text;
        }
        return (
          accessory.cat + " - " + accessory.subCat + " - " + accessory.text
        );
      }
    }
  });
});

My server side logic is:

public function getAccessories(Request $request)
    {
        $boatIds = $request->input('boats', []);

        if (empty($boatIds)) {
            return response()->json(['success' => false, 'message' => 'No boats selected.']);
        }

        $accessories = [];
        foreach ($boatIds as $boatId) {
            $boat = $this->predefinedListRepository->findById($boatId);

            if (!$boat) {
                return response()->json(['success' => false, 'message' => "Boat with ID $boatId not found."]);
            }

            $boat_cats = $boat->childitems_display();

            foreach ($boat_cats as $boat_cat) {
                $boat_cat_data = [
                    'id' => $boat_cat->id,
                    'ltitle' => $boat_cat->ltitle,
                    'sub_categories' => []
                ];
            
                foreach ($boat_cat->childitems() as $boat_sub_cat) {
                    $boat_sub_cat_data = [
                        'id' => $boat_sub_cat->id,
                        'ltitle' => $boat_sub_cat->ltitle,
                        'sub_sub_categories' => []
                    ];
            
                    foreach ($boat_sub_cat->childitems() as $boat_sub_sub_cat) {
                        $boat_sub_sub_cat_data = [
                            'id' => $boat_sub_sub_cat->id,
                            'ltitle' => $boat_sub_sub_cat->ltitle,
                        ];
            
                        $boat_sub_cat_data['sub_sub_categories'][] = $boat_sub_sub_cat_data;
                    }
            
                    $boat_cat_data['sub_categories'][] = $boat_sub_cat_data;
                }
            
                $accessories[] = $boat_cat_data;
            }
            
        }

        return response()->json([
            'success' => true,
            'accessories' => $accessories,
        ]);
    }

I want the proper selection so that I can save the accessory selected

1 Answer 1

0

This issue might occur if the selected option is not properly added to the underlying element or if Select2 is not correctly initialized with the new data. Example Code:

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

Comments

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.