Debug School

rakesh kumar
rakesh kumar

Posted on • Updated on

How to handle click event with jQuery for dynamic html manipulation after server response in laravel

Handling dynamic html dropdown manipulation after click event
Handling dynamic html button manipulation after click event
How to hide and show html button after event click
Conditional Display of html div Containers
Conditional Display of html buttons using explode function

Handling dynamic html dropdown manipulation after click event
In html display button
Event Handling
Data Extraction using data id
processing server side data using ajax route
after sucess get server side data in variable
based on status show popupmodal and append the data in dropdown
apply ternary operator to get data in work url and work description

In html display button

 <button type="button"  class="btn btn-sm btn-secondary report-button" data-id="{{$data->id}}">
                                            Assigned Task
                                        </button>
Enter fullscreen mode Exit fullscreen mode

output

Image description
Event Handling:

$('.report-button').click(function() {
Enter fullscreen mode Exit fullscreen mode

Data Extraction:

var paymentId = $(this).data('id');
Enter fullscreen mode Exit fullscreen mode

It retrieves the id data attribute value from the clicked element with the class report-button.

HTML Manipulation:

$('#influencer_result').html('');
Enter fullscreen mode Exit fullscreen mode

AJAX Request:

$.ajax({
    type: 'GET',
    url: "{{ route('report-task', ['id' => ':paymentId']) }}".replace(':paymentId', paymentId),
           success: function(data)
                 {
                console.log('view-button ka data aata hain');
                   var approvetask = data.approvetask;
                    var infl_email = data.influencer_email;
                    var infl_admin = data.influencer_admin_id;
                    var status = data.approvetask.status;
                    console.log('approvetask:', approvetask);
                    console.log('infl_email:', infl_email);
                    var task_id = data.approvetask.id;
                    var admin_id = data.approvetask.admin_id;
                    var user_name = data.approvetask.user_name;
                    var work_url = data.approvetask.work_url ? data.approvetask.work_url : "";
                    var work_desc = data.approvetask.work_desc ? data.approvetask.work_desc : "";
                    var share_id = data.approvetask.id;
                    var influencer_email = data.approvetask.influencer_email;
                    var payment_id = data.approvetask.payment_id;
                    console.log('task_id:', task_id);
                    console.log('user_name:', user_name);
                    // var emailString = infl_email.join(',');
                    // var emailStringadmin = infl_admin.join(',');
                    $('#influencer_email').val(infl_email);
                    $('#status').val(status);
                    $('#influencer_admin_id').val(infl_admin);
                    $('#payment_id').val(payment_id);
                    $('#share_id').val(share_id);
                    if (status === 'not approved') {
                        $('#approves-data').modal('show');
                $('#url').html(`
                    <option value="Approve">Approve</option>
                    <option value="Reject">Reject</option>
                    <option value="completed">completed</option>
                    <option value="InProgress">In Progress</option>
                    <option value="onhold">onhold</option>
                `);

            } else if (status === 'Approve') {
                // Add options for 'Reject' status
                $('#approves-data').modal('show');
                $('#url').html(`
                   <option value="completed">completed</option>
                    <option value="InProgress">In Progress</option>
                    <option value="onhold">onhold</option>
                `);

    }

                else if (status === 'Reject') {
                    $('#rejects-data').modal('show');

                }
                else if (status === 'completed') {
                    $('#completed-data').modal('show');

                }
    else if (status === 'InProgress') {
        $('#approves-data').modal('show');
        $('#url').html(`
        <option value="completed">completed</option>
        <option value="onhold">onhold</option>
        `);


    }else if (status === 'onhold') {
        $('#approves-data').modal('show');
        $('#url').html(`
        <option value="completed">completed</option>
        <option value="onhold">onhold</option>
        `);       
    }
    else {

    }            },
      error: function(error) {
        // Handle any errors that occur during the AJAX request
        console.log('Error:', error);
      }
    });
    error: function(error) {
        // Code to handle AJAX errors
    }
});
Enter fullscreen mode Exit fullscreen mode

In html

 <div id="approves-data" 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>
                                <div class="modal-body">

                                <form method="post" id="task_form" style="margin-left:-30px;" class="form-horizontal" enctype="multipart/form-data">
                                            @csrf

                                            <div  class="form-group">
                                                <h4>Assigned Task</h4>
                                                <label class="control-label ">Status</label>                                                
                                                    <select name="url" id="url" class="w-100 p-2">
                                                    <option value="" class="form-control text-dark">Select status</option>

                                                    </select>
                                            </div>

                                            <div class="form-group">
                                            <span id="urlErrorMessage" class="text-danger"></span>
                                                    <label for="video_upload" class="control-label" style="color: black;">Work Link :</label>

                                                    @if(!empty($sharedata->Video_link))
                                                    <input type="url" name="video_upload" id="video_upload" class="form-control" value="{{$sharedata->Video_link}}" placeholder="https://www.youtube.com/watch?v=-eq1bkGF4rg">
                                                    @else
                                                    <input type="text" name="video_upload" id="video_upload"  class="form-control" value="" placeholder="">
                                                    @endif
                                                </div>

                                                <div class="form-group">
                                                    <label class="control-label" style="color: black;"> Description : </label>
                                                    @if(!empty($sharedata->description))
                                                    <textarea id="write_up" name="write_up" id="write_up"  rows="4" cols="4" class="form-control" WRAP>{{$sharedata->description}}</textarea>
                                                    @else
                                                    <textarea id="write_up" name="write_up" id="write_up" rows="4" cols="4" class="form-control" WRAP></textarea>
                                                    @endif
                                                </div>

                                            <!-- Sending admin_id and admin_email in hidden input box -->
                                            <input type="hidden" value="{{ Auth::user()->id }}" name="admin_id" id="admin_id" />
                                            <input type="hidden" value="{{ Auth::user()->email }}" id="admin_email" name="admin_email" />
                                            <input type="text"  name="influencer_email" id="influencer_email">
                                       <input type="text"  name="influencer_admin_id" id="influencer_admin_id">
                                       <input type="hidden" name="action" id="action" />
                                        <input type="hidden" name="hidden_id" id="hidden_id" />
                                        <input type="hidden" name="share_id" id="share_id" />

                                        <button type="submit" name="action_button" id="action_button" class="btn btn-sm py-1 btn-primary me-2" value="Add">Submit</button>
                                    <input type="text"  name="payment_id" id="payment_id">
                                    </div>                                  
                                    </form>
                                </div>                                
                            </div>
                        </div>
                    </div>
Enter fullscreen mode Exit fullscreen mode

output

Image description

Another Example

In html display button

  <button type="button" style="width: 300px;" class="btn btn-primary suggest-button" data-id="{{$user->id}}">
                                   Update Status
                                        </button>
Enter fullscreen mode Exit fullscreen mode

output

Image description

Event Handling:

  $('.suggest-button').click(function() {
Enter fullscreen mode Exit fullscreen mode

Data Extraction:

  var productid = $(this).data('id'); 
Enter fullscreen mode Exit fullscreen mode

It retrieves the id data attribute value from the clicked element with the class report-button.

HTML Manipulation:

   $('#influencer_result').html('');
Enter fullscreen mode Exit fullscreen mode

AJAX Request:

   $.ajax({
                type: 'GET', // You can adjust the HTTP method as needed
                url: "{{ route('suggest-task', ['id' => ':productid']) }}".replace(':productid', productid),
               success: function(data)
                 {
                console.log('suggest-button ka data aata hain');
                    var approvetask = data.approvetask;
                    var infl_email = data.influencer_email;
                    var infl_admin = data.influencer_admin_id;
                    console.log('approvetask:', approvetask);
                    console.log('infl_email:', infl_email);
                    var task_id = data.approvetask.id;
                    var admin_id = data.approvetask.admin_id;
                    var status = data.approvetask.publisher_status;
                    var influencer_status = data.approvetask.status;
                    var user_name = data.approvetask.user_name;
                    var share_id = data.approvetask.id;
                    var influencer_email = data.approvetask.influencer_email;
                    var payment_id = data.approvetask.payment_id;
                    console.log('task_id:', task_id);
                    console.log('user_name:', user_name);
                    console.log('status:', status);
                    // var emailString = infl_email.join(',');
                    // var emailStringadmin = infl_admin.join(',');
                    $('#influencer_email').val(infl_email);
                    $('#influencer_admin_id').val(infl_admin);
                    $('#payment_id').val(payment_id);
                    $('#share_id').val(share_id);

                    if (status === 'not approved') {

                      if (influencer_status === 'not approved') {
                        $('#notapprove-data').modal('show');
                      }
                      else if (status === 'completed') {
                          $('#completes-data').modal('show');                        
                          }
                          else if (status === 'Reject') {                         
                          $('#rejected-data').modal('show');                        
                          }
                      else{
                        $('#suggest-data').modal('show');
                    $('#suggest_option').html(`
                        <option value="">Select status</option>
                        <option value="Approve">Approved</option>
                        <option value="Reject">Rejected</option>                
                        <option value="InProgress">Modification Require</option>                        
                    `);

                      }

                      } else if (status === 'completed') {
                          // Add options for 'Reject' status

                          $('#completes-data').modal('show');

                          }
                    else{
                      $('#suggest-data').modal('show');

               $('#suggest_option').html(`
                    <option value="">Select status</option>
                    <option value="Approve">Approved</option>
                    <option value="Reject">Rejected</option>                
                    <option value="InProgress">Modification Require</option>

                `);

                                                  }

                       },
      error: function(error) {
        // Handle any errors that occur during the AJAX request
        console.log('Error:', error);
      }
    });
Enter fullscreen mode Exit fullscreen mode

In html

  <div id="suggest-data" 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>
                                <div class="modal-body">
                                <form method="post" id="suggestion_form" style="margin-left:-10px;" class="form-horizontal" enctype="multipart/form-data">
                                            @csrf                                            
                                            <div  class="form-group">
                                                <h4>Update Status</h4>
                                                <label class="control-label ">Status</label>  
                                                    <select  name="suggest_option" id="suggest_option" class="w-100 p-2">
                                                    <option value="" class="form-control text-dark">Select status</option>                                                       
                                                    </select>
                                            </div>
                                                <div class="form-group">
                                                    <label class="control-label" style="color: black;"> Suggestion : </label>                                                 
                                                    <textarea id="suggest_write_up"  name="suggest_write_up" id="suggest_write_up"  rows="4" cols="4" class="form-control" WRAP></textarea>                                                    
                                                </div>

                                            <!-- Sending admin_id and admin_email in hidden input box -->
                                            <input type="hidden" value="{{ Auth::user()->id }}" name="admin_id" id="admin_id" />
                                            <input type="hidden" value="{{ Auth::user()->email }}" id="admin_email" name="admin_email" />
                                            <input type="hidden"  name="influencer_email" id="influencer_email">
                                       <input type="hidden"  name="influencer_admin_id" id="influencer_admin_id">
                                       <input type="hidden" name="action" id="action" />
                                        <input type="hidden" name="hidden_id" id="hidden_id" />
                                        <input type="hidden" name="share_id" id="share_id" />                                        
                                        <button type="submit" name="action_button" id="action_button" class="btn btn-sm py-1 btn-primary me-2" value="Add">Submit</button>
                                    <input type="hidden"  name="payment_id" id="payment_id">
                                    </div>                                  
                                    </form>
                                </div>                                
                            </div>
                        </div>
                    </div>  
Enter fullscreen mode Exit fullscreen mode

output

Image description

Handling dynamic html button manipulation after click event

based on server data button text change using ifelse
a templating engine in Laravel, to conditionally generate buttons based on the value of $data->publisher_status

@if Statement:

@if ($data->publisher_status === 'Approve')
Enter fullscreen mode Exit fullscreen mode

This is an @if directive in Blade. It checks if the value of $data->publisher_status is equal to the string 'Approve'. If this condition is true, the following code block will be executed.

Button for 'Approve' Status:

<button type="button" class="btn btn-sm btn-secondary" disabled>
    Approve by Publisher
</button>
Enter fullscreen mode Exit fullscreen mode

If the status is 'Approve,' it generates a disabled button with the label "Approve by Publisher."

@elseif Statement:

@elseif ($data->publisher_status === 'InProgress')
Enter fullscreen mode Exit fullscreen mode

If the first condition is false, it checks if the status is 'InProgress'. If true, the following code block will be executed.

Button for 'InProgress' Status:

<button type="button" class="btn btn-sm btn-secondary" disabled>
    Modification Required
</button>
Enter fullscreen mode Exit fullscreen mode

If the status is 'InProgress,' it generates a disabled button with the label "Modification Required."

Another @elseif Statement:

@elseif ($data->publisher_status === 'Reject')
Enter fullscreen mode Exit fullscreen mode

If the previous conditions are false, it checks if the status is 'Reject.' If true, the following code block will be executed.

Button for 'Reject' Status:

<button type="button" class="btn btn-sm btn-secondary" disabled>
    Rejected by Publisher
</button>
Enter fullscreen mode Exit fullscreen mode

If the status is 'Reject,' it generates a disabled button with the label "Rejected by Publisher."

@else Statement:

@else 
Enter fullscreen mode Exit fullscreen mode

If none of the above conditions are true, this code block will be executed.

Button for Other Status (default):

<button type="button" class="btn btn-sm btn-secondary" disabled>
    not approved
</button>
Enter fullscreen mode Exit fullscreen mode

If the status is anything other than 'Approve,' 'InProgress,' or 'Reject,' it generates a disabled button with the label "not approved."

@if ($data->publisher_status === 'Approve')
                                    <button type="button" class="btn btn-sm btn-secondary" disabled>
                                        Approve by Publisher
                                        </button>
                                    @elseif ($data->publisher_status === 'InProgress')
                                        <button type="button" class="btn btn-sm btn-secondary" disabled>
                                        Modification Required
                                        </button>  
                                        @elseif ($data->publisher_status === 'Reject')
                                        <button type="button" class="btn btn-sm btn-secondary" disabled>
                                        Rejected by Publisher
                                        </button>                                        
                                        @else 
                                        <button type="button" class="btn btn-sm btn-secondary" disabled>
                                        not approved
                                        </button>
Enter fullscreen mode Exit fullscreen mode

output

Image description

Image description

How to hide and show html button after event click

In html code

 @if($user->status ===  'completed' || $user->status ===  'not approved')                
                                        @else
                                        <button type="button" style="width: 300px;" class="btn btn-primary suggest-button" data-id="{{$user->id}}">
                                   Update Status
Enter fullscreen mode Exit fullscreen mode

Image description

in case of hide

Image description

Image description

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

Button Markup:

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

Image description

This button has an id of "callAjaxButton" and a data-id attribute that holds a dynamic value (presumably an ID associated with some data). The onclick attribute triggers the myButtonClick function when the button is clicked.

JavaScript Function:

function myButtonClick(button, event) {
    console.log("coming here");
    event.preventDefault();
    var paymentId = $(button).data('id');
    console.log(paymentId);
    // Clear the existing content in #influencer_result
    $('#influencer_result').html('');

    // Generate URL with the paymentId
    var url = "{{ route('view-price', ['id' => ':id']) }}".replace(':id', paymentId);

    // Make an AJAX request
    $.ajax({
        type: 'GET',
        url: url,
        success: function(data) {
            console.log('view-button ka data aata hain');
            var users = data.pays;

            // Display modal
            $('#share-data').modal('show');

            // Extract prices from the AJAX response
            var facebook = users.face_price;
            var twitter = users.twitter_price;
            // ... (similar lines for other social media platforms)

            // Display or hide containers based on the presence of data
             if (facebook !== null) {
        console.log(pintrest);
        // Set the value of pintrest and show the container
        $('#facebook').text(facebook);
        $('#facebookContainer').show();
    } else {
        // Hide the container if pintrest is null
        $('#facebookContainer').hide();
    }

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

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

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

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

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

        // Set the value of pintrest and show the container
        $('#instagram').text(instagram);
        $('#instagramContainer').show();
    } else {
        // Hide the container if pintrest is null
        $('#instagramContainer').hide();
    }
    var quora = users.quora_price;
        var pintrest = users.pinterest_price;
        var reddit = users.reddit_price;
        var koo = users.koo_price;
        var scoopit = users.scoopit_price;
        var slashdot = users.slashdot_price;  
        var linked = users.linkedin_price; 
        var telegram = users.telegram_price; 


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

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

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

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

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

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

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

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

    if (linked !== null) {
        console.log(linked);       
        $('#linked').text(linked);
        $('#linkedContainer').show();
    } else {
        // Hide the container if pintrest is null
        $('#linkedContainer').hide();
    } 
      },
                error: function (error) {
                    // Handle the error here
                    console.log('AJAX request error');
                    console.log(error);
                }
            });
            }
Enter fullscreen mode Exit fullscreen mode

output

Image description

This function is called when the button is clicked. It prevents the default form submission (if it's within a form), extracts the data-id attribute from the button, clears existing content, constructs a URL with the paymentId, and then makes an AJAX request to that URL.

In the success callback, it logs data to the console, shows a modal (#share-data), and populates or hides containers based on the received data.

Conditional Display of html buttons using explode function

   @php
                        $parts = explode(':', $item->addcarts);
                        $valueAfterColon = isset($parts[1]) ? $parts[1] : null;
                          @endphp
                          @if (($parts[1] == 'yes') && (auth()->user()->email == $parts[0])) 
                            <button type="submit"  
                             class="btn btn-sm  btn-primary" style="position: relative;float:right">Added</button> 
                            @else                            
                            <button type="submit"  
                             class="btn btn-sm  btn-primary addToCartBtn" data-item-id="{{ $item->id }}"  style="position: relative;float:right">Add To Cart</button> 
                            @endif 
                            <button id="callAjaxButton" class="btn btn-sm  btn-primary mr-2"   data-id="{{ $item->id }}"   style="position: relative;float:right" onclick="myButtonClick(this, event)">View Price</button>  
Enter fullscreen mode Exit fullscreen mode

Image description

Top comments (0)