Modify the css styling of a div element once the ajax call returns a successful

I am facing an issue with the visibility of my buttons. Currently, I have 3 buttons whose visibility is set to hidden. Upon clicking a specific button, an Ajax call is triggered where I check if the table rows are greater than 0 in the success callback:

$('#addRefBtn').on('click', function(e){
    e.preventDefault();
    var get_input = $('#qr_ref').val();
    var get_po = $('#get_po').val();

    $.ajax({
        type: 'POST',
        url: 'validate_qr.php',
        data: {
            qr_code: get_input,
            po_ID: get_po
        },
        success: function(result)
        {
            var rowCount = $('#productSalesTable tbody tr.ps').length;

            if(rowCount > 0)
            {
                $('#promoModal, #removeModal, #confirmModal').css('visibility', 'visible');
            }
            else
            {
                $('#promoModal, #removeModal, #confirmModal').css('visibility', 'hidden');
            }
        }
    });
});

The location.reload() was commented out for checking purposes and it confirmed that the button's CSS changes when the table row count is greater than zero.

However, upon page reload, the buttons revert back to their original hidden state which is causing concern.

This is the relevant HTML code:

<div id='promoModal' style='visibility:hidden;'>
    <button type="button" class='btn btn-block btn-primary btn-flat' id="promo_modal" data-poid="<?php echo $_GET['po_ID'];?>">
        Add Promo
    </button>
</div>

<div id='removeModal' style='visibility:hidden;'>
    <input type="button" class='btn btn-block btn-warning btn-flat' id="remove_modal" value="Remove Item">
</div>

<div id='confirmModal' style='visibility:hidden;'>
    <button type="button" class='btn btn-block btn-success btn-flat' id="confirm_modal" data-id="<?php echo $_GET['po_ID'];?>">
        Confirm Transaction
    </button>
</div>

Despite knowing that the code is functioning correctly, the button styles do not change as expected even when the table length is greater than zero.

If anyone has suggestions or feedback on this matter, it would be greatly appreciated!

Thank you for your time.

Answer №1

To sum it up, you just have to invoke the success functionality two times in your code. Look at this snippet for a quick look:

// Initially calling the function that hides rows
// to verify if there are 0 or more rows
// and applying necessary styles
successFunction();     // CRUCIAL!!!!

$('#addRefBtn').on('click', function(e) {
  e.preventDefault();
  var get_input = $('#qr_ref').val();
  var get_po = $('#get_po').val();
  //
  $.ajax({
    type: 'POST',
    url: 'validate_qr.php',
    data: {
      qr_code: get_input,
      po_ID: get_po
    },
    success: function(result) {
      // Do you need to repaint or re-render a DOM element here? (Clarify this requirement)
      //
      // Apply styles or call the function again to reapply styles        
      successFunction();

      // Page reload (Using AJAX loses its purpose with page reload)
      // [SUGGESTION] Instead of reloading, consider rendering DOM elements
      // If DOM elements are being rendered, then call the above successFunction after rendering.
      location.reload();
    }
  });
});

function successFunction() {
  var rowCount = $('#productSalesTable tbody tr.ps').length;
  if (rowCount > 0) {
    $('#promoModal').css('visibility', 'visible');
    $('#removeModal').css('visibility', 'visible');
    $('#confirmModal').css('visibility', 'visible');
  } else {
    $('#promoModal').css('visibility', 'hidden');
    $('#removeModal').css('visibility', 'hidden');
    $('#confirmModal').css('visibility', 'hidden');
  }
}

Answer №2

This snippet demonstrates the usage of toggleClass to show/hide a div after a successful AJAX call.

$(document).ready(function(){


$('#addRefBtn').on('click', function(e){
    e.preventDefault();

    setTimeout(function(){
        console.log('sss');  $('#removeModal').toggleClass('show');  
    }, 3000);
  });
  
  
});
#removeModal {
  display: inline-block;
  border: 1px solid red;
  display: none;
}

.show {
  display: inline-block !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='promoModal' style='visibility:hidden;'>
  <button type="button" class='btn btn-block btn-primary btn-flat' id="promo_modal" data-poid="<?php echo $_GET['po_ID'];?>">
      Add Promo
  </button>
</div>

<div id='removeModal'>
  <input type="button" class='btn btn-block btn-warning btn-flat' id="remove_modal" value="Remove Item">
</div>

<!-- <div><button type="button" class='btn btn-block btn-danger btn-flat' id="void_modal">Void Transaction</button></div> -->
<div id='confirmModal' style='visibility:hidden;'>
  <button type="button" class='btn btn-block btn-success btn-flat' id="confirm_modal" data-id="<?php echo $_GET['po_ID'];?>">   
    Confirm Transaction
  </button>
</div>


 <button type="button" class='btn btn-block btn-success btn-flat' id="addRefBtn">   
    Call Ajax Request
  </button>

Answer №3

One way to hide content is by using a class called display-hide, like this:

.display-hide{
display:none;
}

You can apply this class to HTML elements like this:

<div id='promoModal' class="display-hide">
                    <button type="button" class='btn btn-block btn-primary btn-flat' id="promo_modal" data-poid="<?php echo $_GET['po_ID'];?>">
                      Add Promo
                    </button>
                </div>

To show the hidden content based on a condition, you can do something like this:

if(rowCount > 0)
          {
            $('#promoModal').show();
            $('#removeModal').show();
            $('#confirmModal').show();
          }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to retrieve all elements, including those that are hidden, within a CSS grid

My goal is to retrieve all the "Available Items" using Javascript in one go. However, I am facing an issue where not all of them are visible at once due to the need to manually scroll through a CSS grid. <div class="gridWrapper" data-dojo-attach-point= ...

Is it possible to invoke a TypeScript function that was previously initialized in the HTML file?

I am facing an issue where I want to trigger a function upon pressing a button. The problem arises when I try to call the function that I initialized in the HTML file - the button does not recognize it. Even after using < script> tags, the function ...

Loading content dynamically into a div from an external or internal source can greatly enhance user experience on a website. By

As I work on my website, I am incorporating a div structure as shown below: <div class="container"> <div class="one-third column"> <a id="tab1" href="inc/tab1.html"><h2>tab1</h2></a> </div> & ...

Ways to trigger a server function in JavaScript upon closing a browser tab or the entire browser

How can I trigger a server function when closing a browser tab or window using JavaScript? Similar to this image //Below is the code for my server-side function: public ActionResult DeleteNotPostedImage(string folder , string PostID) { folder ...

Guide to implementing the offcanvas sidebar with bookmarks using Bootstrap

On my website, I have implemented a convenient offcanvas sidebar using Bootstrap 5. This sidebar contains html bookmark links that allow users to quickly navigate to specific points on the page by clicking on them. Here is an abbreviated version of the cod ...

ngClass causing styling issue when applying styles

When I use class names like error and info, the CSS works fine. For example, in this Angular app (latest version) here: https://stackblitz.com/edit/github-i4uqtt-zrz3jb. However, when I try to rename the CSS classes and add more styles, like in the examp ...

My HTML table is not printing at full width

Seeking assistance with creating a printable calendar using an HTML table. The calendar prints perfectly on a Mac, but when attempted on Windows in all browsers, it adds a 3" margin at the top regardless of CSS print settings. The client requires the cal ...

Verify the input data, accepting solely numerical values up to a specified maximum limit

To ensure my code validates input correctly, it must only allow numeric values and notify the user if anything else is entered. If the value exceeds a specified maximum value, the user should be warned and the input rejected. Alphanumeric values are not pe ...

Create HTML content from a file retrieved from the server

I have been working on a dynamic website project, diving into web development from scratch despite having coding experience in general. As I navigate Angular CLI and Bootstrap, I've come across a fundamental question: Do modern websites house all thei ...

Getting the value of a JavaScript variable and storing it in a Python variable within a Python-CGI script

Is there a way to capture the value of a JavaScript variable and store it in a Python variable? I have a Python-CGI script that generates a selection box where the user can choose an option from a list. I want to then take this selected value and save it ...

jQuery AJAX encountering parsing error when retrieving data from Laravel controller

I'm attempting to retrieve data from a laravel controller using 'jquery' ajax, but I keep encountering the 'parsererror'. According to the laravel documentation, it automatically sets the header Content-Type= 'application/json ...

"Retrieving the value of an array for a specific DOM element using jQuery

Issue: I am struggling to pass an array of checkbox IDs to a hidden DOM element and retrieve it successfully. Currently, I can only manage to do this for a single checkbox ID, as shown in the example below: var selectedCheckBoxIds = [22, 23, 24]; $(&apos ...

What is the best way to download an updated social media post for a Django user?

Objective A user has the ability to edit their own posts by clicking on the edit button, making edits, and then saving the changes. Issue Editing a social media post does not result in the changes being saved. Overview Create a new post similar to how ...

Arrange the parallel table columns within their own individual divs to be perfectly aligned

I have a layout with two divs stacked on top of each other, each containing a table with the same number of columns. I need to ensure that the columns in both tables are the same width and aligned properly. If a column in one table expands, I want the corr ...

I'm experiencing difficulties with a JavaScript slideshow in Vegas

After installing the vegas jQuery plugin to my project using npm, I encountered issues when attempting to use it according to the documentation. Despite linking the required vegas.min.js and vegas.min.css files in my HTML, the plugin doesn't appear to ...

Text within the footer section

When displaying the name of a subcategory, I want it in one line. However, if the subcategory name contains two words, it should be displayed in two lines. https://i.stack.imgur.com/CcDeL.png Code: .Footer { width: 100%; display ...

unable to parse JSON

After making an ajax call to the server, I received the following response: var data = [{ "Response": { "ResponseStatus": { "Code": "1", "Description": "Success" }, "TransactionReference": {} } }, ...

Keep the submenu visible upon clicking the sign-in form / Adjust the background color when the parent li is selected

I am facing two issues with my navigation menu that has dropdown lists: When clicking on a parent li, its submenu is displayed, but it gets hidden when clicking on another parent li or anywhere else on the page. For the first li.parent which contains a ...

Guide on displaying property file values in JavaScript within a Spring MVC application

Currently, I have hard-coded messages in the message.properties file such as "Are you sure you want to delete the message?". I am looking for a way to extract these messages from message.properties and use them in JavaScript. Any suggestions on how to ach ...

Style Vue slots one by one

I am a beginner delving into the world of vue (specifically, vue 2) and aiming to grasp the concept of utilizing slots in the most effective manner. Below is the code I'm working with: <template> <div> <button cla ...