Debug School

rakesh kumar
rakesh kumar

Posted on • Updated on

Validating and processing checkbox inputs for single field in Laravel form submissions

Conditional Display of html div Containers
how to get value of all/multiple checkbox or radio button using visible
How to extract all/multiple checkbox id and put in array
how to append array in formData

Step 1: fetch data from server when i click button

 <button id="callmyAjaxButton" class="btn btn-sm  btn-primary mr-2"   data-id="{{ $item->id }}"   style="position: relative;float:right" onclick="mySocialClick(this, event)">Add cart</button> 
Enter fullscreen mode Exit fullscreen mode

Image description

Step 2: fetch data from server

 function mySocialClick(button, event) {
                console.log("coming here mySocialClick");
                event.preventDefault();
                var paymentId = $(button).data('id');
                console.log(paymentId);
                console.log(paymentId);
                // Clear the existing content in #influencer_result
                $('#influencer_result').html('');
                var url = "{{ route('view-social', ['id' => ':id']) }}".replace(':id', paymentId);
                $.ajax({
                type: 'GET', // You can adjust the HTTP method as needed
                url: url,// Replace with your actual route name
                success: function(data) {
                console.log('view-button social ka data aata hain');
                var users = data.pays;
                console.log(users);

                $('#share-social').modal('show');
                var user_name = users.user_name;
                var user_email = users.user_email;
                var id = users.id;
                var facebook = users.facebook;
                var twitter = users.twitter;
                var youtube = users.youtube;
                var wordpress = users.wordpress;
                var tumbler = users.tumblr;
                var instagram = users.instagram;
                var quora = users.quora;
                var pintrest = users.pinterest;
                var reddit = users.reddit;
                var koo = users.koo;
                var scoopit = users.scoopit;
                var slashdot = users.slashdot;  
                var linked = users.linkedin; 
                var telegram = users.telegram; 
                console.log(facebook)
                console.log(pintrest)
                $('#slug').val(user_name);
        $('#influencer_email').val(user_email);
        $('#item').val(id);
        $('#dataitem_id').val(id);


                if (facebook !== null) {
                console.log(pintrest);
                $('#facebooksocial').text(facebook);
                $('#facebooksocialContainer').show();
                } else {              
                $('#facebooksocialContainer').hide();
                }



                if (twitter !== null) {
                    console.log("yanha aata hain twitter");   
                console.log(twitter);              
                $('#twittersocial').text(twitter);
                $('#twittersocialContainer').show();
                } else {      
                    console.log("yanha nahin aata hain twitter");        
                $('#twittersocialContainer').hide();
                }



                if (youtube !== null) {
                console.log(youtube);
                $('#youtubesocial').text(youtube);
                $('#youtubesocialContainer').show();
                } else {             
                $('#youtubesocialContainer').hide();
                }
                if (wordpress !== null) {
                console.log(wordpress);

                // Set the value of pintrest and show the container
                $('#wordpresssocial').text(wordpress);
                $('#wordpresssocialContainer').show();
                } else {
                // Hide the container if pintrest is null
                $('#wordpresssocialContainer').hide();
                }

                if (tumbler !== null) {
                console.log(tumbler);
                console.log("tumbler aat ahain");
                $('#tumblersocial').text(tumbler);
                $('#tumblersocialContainer').show();
                } else {    
                    console.log("tumbler container aat ahain");         
                $('#tumblersocialContainer').hide();
                }


                if (instagram !== null) {
                console.log(pintrest);
                $('#instagramsocial').text(instagram);
                $('#instagramsocialContainer').show();
                } else {           
                $('#instagramsocialContainer').hide();
                }



                if (quora !== null) {
                console.log(quora);

                // Set the value of pintrest and show the container
                $('#quorasocial').text(quora);
                $('#quorasocialContainer').show();
                } else {
                // Hide the container if pintrest is null
                $('#quorasocialContainer').hide();
                }
                if (pintrest !== null) {
                console.log(pintrest);

                // Set the value of pintrest and show the container
                $('#pintrestsocial').text(pintrest);
                $('#pintrestsocialContainer').show();
                } else {
                // Hide the container if pintrest is null
                $('#pintrestsocialContainer').hide();
                }
                if (reddit !== null) {
                console.log(reddit);

                // Set the value of pintrest and show the container
                $('#redditsocial').text(reddit);
                $('#redditsocialContainer').show();
                } else {
                // Hide the container if pintrest is null
                $('#redditsocialContainer').hide();
                }
                if (koo !== null) {
                console.log(koo);

                // Set the value of pintrest and show the container
                $('#koosocial').text(koo);
                $('#koosocialContainer').show();
                } else {
                // Hide the container if pintrest is null
                $('#koosocialContainer').hide();
                }
                if (scoopit !== null) {
                console.log(scoopit);

                // Set the value of pintrest and show the container
                $('#scoopitsocial').text(scoopit);
                $('#scoopitsocialContainer').show();
                } else {
                // Hide the container if pintrest is null
                $('#scoopitsocialContainer').hide();
                }
                if (slashdot !== null) {
                console.log(slashdot);

                // Set the value of pintrest and show the container
                $('#slashdotsocial').text(slashdot);
                $('#slashdotsocialContainer').show();
                } else {
                // Hide the container if pintrest is null
                $('#slashdotsocialContainer').hide();
                }
                if (telegram !== null) {
                console.log(telegram);

                $('#telegramsocial').text(telegram);
                $('#telegramsocialContainer').show();
                } else {
                // Hide the container if pintrest is null
                $('#telegramsocialContainer').hide();
                }

                if (linked !== null) {
                console.log(linked);       
                $('#linkedsocial').text(linked);
                $('#linkedsocialContainer').show();
                } else {
                // Hide the container if pintrest is null
                $('#linkedsocialContainer').hide();
                }


                },
                    error: function (error) {
                        // Handle the error here
                        console.log('AJAX request error');
                        console.log(error);
                    }
                });
                }
Enter fullscreen mode Exit fullscreen mode

Step 3: After fetching data display data in popup modal

 <div id="share-social" class="modal fade" role="dialog">
        <div class="modal-dialog">
            <div class="modal-content">
            <div class="modal-header">
                    <h4 class="modal-title mt-2"> Select social site and add cart</h4>
                </div>
                <div class="modal-body">                   
                <div class="card-body">
                <form method="post" id="addcarts" style="margin-left:-10px;" class="form-horizontal" enctype="multipart/form-data">
                          @csrf   
                        <div class="row">
                            <div >
                            <div>
                                <input type="checkbox" id="selectAll" class="mr-2" onchange="selectAllSocial()">
                                <label for="selectAll"><b>Select All</b></label>
                            </div>
                                <div  id="facebooksocialContainer">
                                <input type="checkbox" class="socialCheckbox" id="face_priceCheckbox">           
                                    <span><b>Facebook: </b></span>
                                    <span id="facebooksocial"></span>
                                </div>
                                <div  id="twittersocialContainer">
                                <input type="checkbox" class="socialCheckbox" id="twitter_priceCheckbox">        
                                    <span><b>Twitter: </b></span>
                                    <span id="twittersocial"></span>
                                </div>
                                <div  id="youtubesocialContainer">
                                <input type="checkbox" class="socialCheckbox" id="youtube_priceCheckbox"> 
                                    <span><b>Youtube: </b></span>
                                    <span id="youtubesocial"></span>
                                </div>
                                <div  id="wordpresssocialContainer">
                                <input type="checkbox" class="socialCheckbox" id="wordpress_priceCheckbox"> 
                                    <span><b>Wordpress: </b></span>
                                    <span id="wordpresssocial"></span>
                                </div>
                                <div  id="tumblersocialContainer">
                                <input type="checkbox" class="socialCheckbox" id="tumblr_priceCheckbox"> 
                                    <span><b>Tumbler: </b></span>
                                    <span id="tumblersocial"></span>
                                </div>
                                <div id="instagramsocialContainer">
                                <input type="checkbox" class="socialCheckbox" id="instagram_priceCheckbox"> 
                                    <span><b>Instagram: </b></span>
                                    <span id="instagramsocial"></span>
                                </div>
                                <div id="quorasocialContainer">
                                <input type="checkbox" class="socialCheckbox" id="quora_priceCheckbox"> 
                                    <span><b>Quora: </b></span>
                                    <span id="quorasocial"></span>
                                </div>
                                <div id="pintrestsocialContainer">
                                <input type="checkbox" class="socialCheckbox" id="pintrest_priceCheckbox"> 
                                    <span><b>Pintrest: </b></span>
                                    <span id="pintrestsocial"></span>
                                </div>
                                <div id="redditsocialContainer">
                                <input type="checkbox" class="socialCheckbox" id="reddit_priceCheckbox"> 
                                    <span><b>Reddit: </b></span>
                                    <span id="redditsocial"></span>
                                </div>
                                <div  id="koosocialContainer">
                                <input type="checkbox" class="socialCheckbox" id="koo_priceCheckbox"> 
                                    <span><b>Koo: </b></span>
                                    <span id="koosocial"></span>
                                </div>
                                <div id="scoopitsocialContainer">
                                <input type="checkbox" class="socialCheckbox" id="scoopit_priceCheckbox"> 
                                    <span><b>Scoopit: </b></span>
                                    <span id="scoopitsocial"></span>
                                </div>
                                <div  id="slashdotsocialContainer">
                                <input type="checkbox" class="socialCheckbox" id="slashdot_priceCheckbox"> 
                                    <span><b>Slashdot: </b></span>
                                    <span id="slashdotsocial"></span>
                                </div>
                                <div  id="telegramsocialContainer">
                                <input type="checkbox" class="socialCheckbox" id="telegram_priceCheckbox"> 
                                    <span><b>Telegram: </b></span>
                                    <span id="telegramsocial"></span>
                                </div>
                                <div id="linkedsocialContainer">
                                <input type="checkbox" class="socialCheckbox" id="linkedin_priceCheckbox"> 
                                    <span><b>Linked In: </b></span>
                                    <span id="linkedsocial"></span>
                                </div>
                             <input type="hidden" value="{{ Auth::user()->id }}" name="admin_id" id="admin_id" />                   
                            <input type="hidden"  name="slug" id="slug" />
                            <input type="hidden" name="influencer_email"   id="influencer_email" />
                            <input type="hidden" value="{{ Auth::user()->email }}" name="admin_email" id="admin_email">
                            <input type="hidden" value="{{ Auth::user()->name }}" name="user_name">
                            <input type="hidden"  name="item"  id="item">
                            <input type="hidden" name="dataitem_id"  id="dataitem_id">
                            <button type="submit" name="action_button" id="action_button" class="btn btn-sm py-1 btn-primary me-2" value="Add">Add Cart</button>
                            </div>                            
                        </div>

    </form>
                        </div>                      
                    </div>
                </div>
            </div>
        </div>
Enter fullscreen mode Exit fullscreen mode

Image description

Step 4: handling checkboxes for social media platforms within a modal for single and multiple select checkbox

how to get value of all/multiple checkbox or radio button

 var selectedContainers = [];
    $('#selectAll').change(function () {
            const socialCheckboxes = $('.socialCheckbox:visible');
        const selectAllCheckbox = $('#selectAll');

        socialCheckboxes.prop('checked', selectAllCheckbox.prop('checked'));
        logSelectedSocialContainers();

    });

    $('.socialCheckbox').change(function () {
        logSelectedSocialContainers();
    });

    function logSelectedSocialContainers() {

        const selectedContainers = $('.socialCheckbox:checked').map(function () {
            return this.id.replace('Checkbox', ''); // Get the ID without "Checkbox" suffix
        }).get();
        console.log('Selected Social Containers:', selectedContainers);
        $('#selectedSocialContainersInput').val(selectedContainers.join(','));


    }
Enter fullscreen mode Exit fullscreen mode

Image description

Image description

Image description

Step5: click addcart without click checkbox

Image description

How to extract all/multiple checkbox id and put in array
how to append array in formData

     $('#addcarts').on('submit', function(event) {
         event.preventDefault();   
         var selectedSocials = [];
    $('.socialCheckbox:checked').each(function () {
        selectedSocials.push($(this).attr('id').replace('Checkbox', ''));
    });

    // Log the selected socials to the console
    console.log("Selected Socials:", selectedSocials);
    if (selectedSocials.length === 0) {
        $('#social-modal').modal('show');
    }
    else
    {
      if ($('#action_button').val() == 'Add') {
        console.log('add action_button click ho rha ha');
        var formData = new FormData(this);

        // Include the selected socials in the FormData
        formData.append('selected_socials', selectedSocials);

        // Log the data to the console
        console.log("FormData:");
        for (var pair of formData.entries()) {
            console.log(pair[0] + ', ' + pair[1]);
        }
        $.ajax({
          url: "{{route('addcarts.store') }}",
          method: "POST",
          data: formData,
          contentType: false,
          cache: false,
          processData: false,
          dataType: "json",
          headers: {
            "Authorization": "Bearer " + localStorage.getItem('a_u_a_b_t')
          },
          beforeSend: function() {

          },

          success: function(data) {
           // Handle the response from the server
           console.log(data);
           var html = '';
           if (data.success) {         
            console.log('add success success click ho rha ha');
            $('#approve-modal').modal('show');
           }
           else 
           {

           }
         },
          error: function(xhr, status, error) {           
            console.log(error);
          }
        });
      };
    }
    })
Enter fullscreen mode Exit fullscreen mode
<div id="social-modal" class="modal fade" role="dialog">
                        <div class="modal-dialog">
                            <div class="modal-content">
                                <div class="modal-header bg-light">
                                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                                    <br>                                    
                                </div>
                                <center> <div class="modal-body">
                                    <h5 class="text-center" style="margin:0; color:red;"> Please Select any social site</h5>
                                </div></center>
                            </div>
                        </div>
                    </div>
Enter fullscreen mode Exit fullscreen mode

Image description

Step6: click addcart with click checkbox
how to get value of all/multiple checkbox or radio button using visible
Toggling Checkbox

$('#addcarts').on('submit', function(event) {
         event.preventDefault();   
         var selectedSocials = [];
    $('.socialCheckbox:checked').each(function () {
        selectedSocials.push($(this).attr('id').replace('Checkbox', ''));
    });

    // Log the selected socials to the console
    console.log("Selected Socials:", selectedSocials);
    if (selectedSocials.length === 0) {
        $('#social-modal').modal('show');
    }
    else
    {
      if ($('#action_button').val() == 'Add') {
        console.log('add action_button click ho rha ha');
        var formData = new FormData(this);

        // Include the selected socials in the FormData
        formData.append('selected_socials', selectedSocials);

        // Log the data to the console
        console.log("FormData:");
        for (var pair of formData.entries()) {
            console.log(pair[0] + ', ' + pair[1]);
        }
        $.ajax({
          url: "{{route('addcarts.store') }}",
          method: "POST",
          data: formData,
          contentType: false,
          cache: false,
          processData: false,
          dataType: "json",
          headers: {
            "Authorization": "Bearer " + localStorage.getItem('a_u_a_b_t')
          },
          beforeSend: function() {

          },

          success: function(data) {
           // Handle the response from the server
           console.log(data);
           var html = '';
           if (data.success) {         
            console.log('add success success click ho rha ha');
            $('#approve-modal').modal('show');
           }
           else 
           {

           }
         },
          error: function(xhr, status, error) {           
            console.log(error);
          }
        });
      };
    }
    })
Enter fullscreen mode Exit fullscreen mode

In controller write a logic to store data after selecting checkbox
Use-of-inarray-within-a-foreach-loop-for-data-filtering-in-laravel-applications

 public function addcarts(Request $request)
    {

        Log::info('In addcarts store');
        Log::info('Data received via AJAX:', $request->all());
        $itemId = $request->input('dataitem_id');
            Log::info($itemId);
            $input = $request->all();
            $cartID = null;
            $admins_id=  $request->input('admin_id');
            $admins_email=  $request->input('admin_email');
            $user_name=  $request->input('user_name');
            $addcart= addcart::where('admin_id', $admins_id)
            ->orderBy('created_at', 'desc') // Order by 'created_at' column in descending order
            ->get();   
             $addprofile=Addprofile::where('id',$itemId)->first();
             Log::info($addprofile);

             $payments=payments::where('admin_id',$addprofile->user_id)->first();
             Log::info($payments);           
             $slug= $addprofile->slug;
             $influencer_email= $addprofile->user_email;
             $admin_email=  $request->input('admin_email');
             $user_name=  $request->input('user_name');
             $influencer_admin_id= $addprofile->user_id;

           if(!$addcart->isEmpty())
           {
            $carts_id =$addcart->pluck('cart_id')->toArray();
            $pays=  Paytm::where('cart_id', $carts_id[0])->where('admin_id',$admins_id)->get();
                        if (!$pays->isEmpty())
                        {
                            $cartsID = 'CART-' . Str::random(4);    
                            $cartID = $cartsID. '-' . $admins_id; 
                            Log::info($cartID);                  
                        }
                        else{
                            $addcarts_id =$addcart->pluck('cart_id')->toArray();
                            $cartID = $addcarts_id[0];
                            Log::info($cartID); 
                        }
                    }
                    else{
                        Log::info("last cart id hain na"); 
                        $cartsID = 'CART-' . Str::random(4);    
                        $cartID = $cartsID. '-' . $admins_id;
                        }

                if($addprofile) 
                { 
                    Log::info("addprofile cart id hain na"); 
                    $selectedSocials = explode(',', $request->selected_socials);
                    $socialSites = ['face_price','twitter_price','youtube_price', 'wordpress_price', 'tumblr_price','instagram_price','quora_price', 'pintrest_price','reddit_price','koo_price','scoopit_price','slashdot_price', 'telegram_price','linkedin_price'];
                 // Create a single instance of addcart
                        $addCart = new addcart;
                        $addCart->admin_id = $admins_id;
                        $addCart->cart_id = $cartID;
                        $addCart->influencer_admin_id = $addprofile->user_id;
                        $addCart->admin_email = $admins_email;
                        $addCart->user_name = $user_name;
                        $addCart->slug = $slug;
                        $addCart->influencer_email = $influencer_email;

                        foreach ($socialSites as $socialSite) {
                            // Check if the social site is in $selectedSocials
                            if (in_array($socialSite, $selectedSocials)) {
                                // Update the property of the existing $addCart instance
                                $addCart->{$socialSite} = $payments->{$socialSite} ?? 0;
                            }
                        }

                        // Save the $addCart instance after the loop
                        $addCart->save();
                    log::info($itemId);
                     $addingprofile= DB::table("addprofiles")->where('id',$itemId)->update(['addcarts' => "$admins_email:yes"]);
                    return response()->json([
                        'message' => "task disapprove successfully", 
                        'success' => true,
                    ]);
                  }
        }
Enter fullscreen mode Exit fullscreen mode

OUTPUT

After selecting multiple checkbox
Image description

After selecting single checkbox

Image description

Summary

Conditional Display of html div Containers
Get server side data like facebook,twitter after ajax route processing
if these are not null then display div container using id and display span text using id

how to get value of all/multiple checkbox or radio button using visible
How to extract all/multiple checkbox id and put in array
how to append array in formData

Top comments (0)