15 1 0 4000 1 https://codeblock.co.za 300 true 0
Create a Custom Alert and Confirmation Dialogue With PHP and JQuery

Create a Custom Alert and Confirmation Dialogue With PHP and JQuery

0 Comments

Alerts, prompts and confirmation popups are absolutely invaluable in any website or app. They let the user know what’s happened and what will happen based on their actions. In the case of confirmation dialogues, users can also prevent disastrous actions like deleting content by mistake.

While JavaScript does have incredibly easy ways to invoke alerts, prompts and confirmation dialogues, it doesn’t allow us to customise them at all and quite frankly, they aren’t the most attractive. In this article we’ll create our own custom popup dialogue with the ability to style it as we wish.

Prerequisites

  • An understanding of PHP.
  • An understanding of JQuery and JavaScript.
  • JQuery installed.

Before we begin, you can see some working examples of the code here.

What we’ll be creating is a simple JavaScript function that looks like this:

customAlert(options, confirmationCallback, dismissalCallback);.

This function takes three optional parameters. The first option must be an object which will contain options we want to override in the function. The second parameter is a function that will be called when the user confirms an action and the third parameter is a function that will be called when the user dismisses the dialogue. Typically, the dismiss action wouldn’t do anything, but it’s nice to have the option.

How It Works

The HTML for the alert / confirmation dialogue is saved in a separate PHP file. To get the alert dialogue to be dynamic, the JavaScipt will request this PHP file while sending some data along with the request. The PHP file will then use these $_GET requests to populate the dialogue. Let’s have a look at the HTML.

The Custom Alert Dialogue JavaScript Function

function customAlert(userOptions, actionWhenConfirmed, actionWhenDismissed) {
  // Default Options
  let options = {
    style : 'info',
    heading : 'Notice',
    type : 'alert',
    text : ''
  };

  // User options
  if(userOptions) {
    $.each(userOptions, function(option, value){
      options[option] = value;
    });
  }

  $.get('/confirmation-dialogue.php', options, function(html) {
      // first remove the confirmation if it exists
      if( $('#confirmation-overlay').length ) {
        $('#confirmation-overlay').remove();
      }
      $('body').append(html);
    })
    .done(function(){

      $('#confirmation-confirm').click(function(){
        if(typeof actionWhenConfirmed === 'function' ) {
          actionWhenConfirmed();
        }
        $('#confirmation-overlay').remove();
      });

      $('#confirmation-dismiss').click(function(){
        if( typeof actionWhenDismissed === 'function' ) {
          actionWhenDismissed();
        }
        $('#confirmation-overlay').remove();
      });

    }).fail(function(data) {
        alert('Something went wrong.');
    });
}

In the JavaScript function above, we’re first setting up our default options.

  let options = {
    style : 'info',
    heading : 'Notice',
    type : 'alert',
    text : ''
  };

In fact that’s all that’s needed to run the function, however, it’s empty and doesn’t provide the user with any information.

Next, we’re checking if there are options added to function and if there are, we’re pushing them to the original options object. Remember, in JavaScript, object property keys must be unique so when we push our values, the original ones will be over-ridden provided we’ve used the same keys as the original.

if(userOptions) {
    $.each(userOptions, function(option, value){
      options[option] = value;
    });
}

Next up, were requesting the HTML for the custom alert / custom confirmation dialogue and sending the values from the options object.

$.get('/confirmation-dialogue.php', options, function(html) {
}

When the server returns the request, we first check if any dialogue exists so we don’t pollute the DOM with unnecessary and unused dialogues. Since the dialogue is wrapped in the overlay, we only need to remove the overlay to get rid of it and its children.

// first remove the confirmation if it exists
if( $('#confirmation-overlay').length ) {
   $('#confirmation-overlay').remove();
}
$('body').append(html);

When the Ajax call has completed and is done, we first check that function has valid functions as callbacks and activate them, depending on which course of action the user took. Additionally, we remove the dialogue since we don’t need it anymore.

$('#confirmation-confirm').click(function(){
    if(typeof actionWhenConfirmed === 'function' ) {
         actionWhenConfirmed();
    }
    $('#confirmation-overlay').remove();
});
$('#confirmation-dismiss').click(function(){
        if( typeof actionWhenDismissed === 'function' ) {
          actionWhenDismissed();
        }
        $('#confirmation-overlay').remove();
});

Finally, if the Ajax call fails we’ll simply let the user know. This can happen if there’s a network error or if you’ve made a typo with your variables in the next section.

The HTML & PHP for The Custom Alert Dialogue

<?php

$style = isset($_GET['style']) ? $_GET['style'] : '';
$heading = isset($_GET['heading']) ? $_GET['heading'] : '';
$type = isset($_GET['type']) ? $_GET['type'] : '';
$text = isset($_GET['text']) ? $_GET['text'] : '';

if ($style == 'danger') {
    $colour = 'danger';
}
elseif($style == 'warning') {
    $colour = 'warning';
}
elseif($style == 'success') {
    $colour = 'success';
}
else {
    $colour = 'info';
}

?>

<div id="confirmation-overlay" class="p-5">
    
    <div id="confirmation-dialogue" class="card mx-auto">
        
        <div class="card-header d-flex align-items-center">
            <span class="mr-2">
                <i class="fas fa-exclamation-circle text-<?php echo $colour; ?>"></i>
            </span>
            <h5 class="my-1 card-title "><?php echo $heading; ?></h5>
        </div>
        
        <div class="card-body">
            <?php echo $text; ?>
            
            <?php if($type == 'prompt') : ?>
                <div class="row">
                    <div class="col">
                        <input type="text" id="prompt-input" class="form-control form-control-sm mt-3 w-100"/>
                    </div>
                </div>
            <?php endif; ?>
        </div>
        
        <div class="card-footer" class="text-center d-flex align-item-center justify-content-center">
            <div class="btn-toolbar">
            
                <?php 
                if($type == 'confirmation') : ?>
                <div class="btn-group mr-2" role="group">
                  <button id="confirmation-dismiss" type="button" class="btn btn-sm btn-danger">No</button>
                </div>
      
                <div class="btn-group mr-2" role="group">
                  <button id="confirmation-confirm" type="button" class="btn btn-sm btn-success">Yes</button>
                </div>
                
                <?php elseif ($type == 'prompt')  : ?>
                
                    <div class="btn-group mr-2" role="group">
                      <button id="confirmation-dismiss" type="button" class="btn btn-sm btn-danger">Cancel</button>
                    </div>
          
                    <div class="btn-group mr-2" role="group">
                      <button id="confirmation-confirm" type="button" class="btn btn-sm btn-success">Submit</button>
                    </div>
      
                <?php else : ?>
      
                <div class="btn-group mr-2" role="group">
                  <button  id="confirmation-dismiss" type="button" class="btn btn-sm btn-info">Okay</button>
                </div>
      
                <?php endif; ?>
      
            </div>
        </div>
        
    </div>
    
</div>

In the code above, you can see we’re assigning variables to the $_GET values. While we’re doing that we’re also preventing errors by making sure that if a particular request is empty or not sent, we assign an empty string. We’re also writing some logic to determine what colour the dialogue should be based on the style.

In the HTML section, we’re simply providing some structure for the dialogue and plugging in our variables where we want them to show. We’re also using some logic to determine which buttons to show and the input for the prompt, for example. This is decided by the $type / $_GET[‘type’] variable submitted with the Ajax request. In the case of the prompt, w

Styling the Custom JavaScript Dialogue

I’m using Twitter Bootstrap for most of the styling. If you refer to the HTML above, you’ll notice that depending on the style, the $colour variable changes. Both the confirmation overlay and dialogue box have the following custom styling:

#confirmation-overlay {
    position: fixed;
    height: 100vh;
    width: 100vw;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    z-index: 99999999;
    background: none;
    background-color: #fff;
    background-color: rgba(0,0,0, 0.5);
}

#confirmation-dialogue {
    min-width: 400px;
    max-width: 400px;
    max-height: 95vh;
    overflow: auto;
    font-size: 14px;
    background-color: #fff;
    background-clip: padding-box;
    border: 1px solid rgba(0, 0, 0, 0.1);
    box-shadow: 0 0.25rem 0.75rem rgba(0, 0, 0, 0.1);
    -webkit-backdrop-filter: blur(10px);
    backdrop-filter: blur(10px);
    border-radius: 0.25rem;
}

Using Our Custom JavaScript Dialogue

Now, with all of the above set up, all we have to do is set our options and call the function when ever we need it. In the example code below, when a user clicks the delete button, we’ll only invoke the delete function if they confirm.

$(document).on('click', '#delete-thing', function(e){
    e.preventDefault();
    
    let options = {
         style : 'danger',
         heading : 'Confirm Delete',
         type : 'confirmation',
         text : "Are you sure you want to delete this thing?"
    };

    customAlert('options', function() {
        delete_the_thing();
    } );
});

And that’s all there is to it. Remember to prevent multiple form submissions in some circumstances like form submissions that have confirmation dialogues.

I hope this helps you. Please let me know.

Is this still valid in 2021? Please let me know in the comments below.

Was This Helpful?

Infinite Scroll & Load More With JQuery and PHP
Previous Post
Infinite Scroll & “Load More” With JQuery and PHP
Authenticate and Safeguard Your Laravel API With Sanctum
Next Post
Authenticate and Safeguard Your Laravel API With Sanctum

0 Comments

Leave a Reply