Skip to content
Advertisement

Ajax / JQuery – Displaying flash message on success

I have a fully working flash system in PHP and am using it to send the user a success message once I create an entry in the DB.

On one of my forms I have a select field which I want the user to be able to seamlessly add entries too it without directing them away from a semi-completed form. The code I’m using is working well. The user clicks on ‘add a category’ (in the select label) it opens a modal, the user creates a new category, it updates the DB and the select field and closes the modal using AJAX. All working.

What I need to do is use or adapt my flash system to give the user a message to say all good your entry was added. I am very new to AJAX and on a steep learning curve!

This is my AJAX / JQUERY code: (I followed a tutorial to get here. The idea is to make this usable across the site when I need to add entries to a select, by adding ‘ajax’ to the form class.)

$('form.ajax').on('submit', function() {
    var that = $(this),
        url = that.attr('action'),
        type = that.attr('method'),
        data = {};

    that.find('[name]').each(function(index,value) {
      var that = $(this),
          name = that.attr('name'),
          value = that.val();
      data[name] = value;
    });
    $.ajax({
      url: url,
      type: type,
      data: data,
      success: function(response) {
        $('#select').load(document.URL +  ' #select');
        $('#addCategoryModal').modal('hide');
        $('#siteMessage').toast('show');
      }
    });
    return false;
  });

And this is the PHP setting the DB record (working) and how I normally trigger a flash message on page reload (messages also work):

      //create record in db
      $newCategory = $this->blogModel->createCategory($formFields);
      if ($newCategory) {
        flash('siteMessage', 'Blog category added successfully');
      } else {
        flash('siteMessage', 'Something went wrong', 'bg-danger');
      }

And this is the flash code:

  function flash($name = '', $message = '', $class = 'bg-success') {
    if (!empty($name)) {
      if (!empty($message) && empty($_SESSION[$name])) {
        if (!empty($_SESSION[$name])) {
          unset($_SESSION[$name]);
        }

        if (!empty($_SESSION[$name.'_class'])) {
          unset($_SESSION[$name.'_class']);
        }

        $_SESSION[$name] = $message;
        $_SESSION[$name.'_class'] = $class;
      } elseif (empty($message) && !empty($_SESSION[$name])) {
        $class = !empty($_SESSION[$name.'_class']) ? $_SESSION[$name.'_class'] : '';
        echo '
        <div id="siteMessage" class="toast shadow" data-delay="8000" role="alert" aria-live="assertive" aria-atomic="true" style="position: absolute; top: 19px; right: 45%; z-index:10">
          <div class="toast-header '.$class.'">
            <i class="fas fa-envelope mr-2 pt-1 text-white"></i>
            <strong class="mr-auto text-white">Site Message</strong>
            <button type="button" class="ml-2 mb-1 close" data-dismiss="toast" aria-label="Close">
              <span class="text-white" aria-hidden="true">&times;</span>
            </button>
          </div>
          <div class="toast-body">
            '.$_SESSION[$name].'
          </div>
        </div>
        ';
        unset($_SESSION[$name]);
        unset($_SESSION[$name.'_class']);
      }
    }
  }

My PHP processing page, creates the entry in the DB and I set the flash message as normal. I think I don’t understand the interaction with how AJAX gets the returned success and setting a flash message.

Any thoughts?

Advertisement

Answer

Thanks to CBroe who pointed out the inherent problems with using a flash message mechanism I’ve added the following div at the bottom of the page and am now calling that direct with toast.show to give the message to the user.

I am not sure if that is the most affective way to do this but it works.

<div id="categoryMessage" class="toast shadow" data-delay="8000" role="alert" aria-live="assertive" aria-atomic="true" style="position: absolute; top: 19px; right: 45%; z-index:10">
  <div class="toast-header bg-success">
    <i class="fas fa-envelope mr-2 pt-1 text-white"></i>
    <strong class="mr-auto text-white">Site Message</strong>
    <button type="button" class="ml-2 mb-1 close" data-dismiss="toast" aria-label="Close">
      <span class="text-white" aria-hidden="true">&times;</span>
    </button>
  </div>
  <div class="toast-body">
    The category was added successfully
  </div>
</div> 
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement