JS & JS Libraries

Bootstrap modal boxes with Jquery Ajax - examples

examples of bootstrap modal boxes powered by ajax and jquery


Bootstrap modal boxes with Jquery Ajax - examples

Modal boxes

As far as modal boxes are concerned - they have taken website by storm and rightly so, they make sites more user friendly with the advantage that they look good and that they help the UI interaction and usability. They keep the user on the main page while performing actions related to it.

There are 3 types of modal boxes:

  • Modal boxes that has static HTML in it.
  • Modal boxes that generate information that are passed to it via JQUERY
  • And modal boxes that interacts with a programming language like PHP that operate via AJAX and display information from the database on it.

The HTML modal box is easy, you just hide it and display it when the box is activated via a link. All the modal boxes we are displaying here are in conjunction with Bootstrap 3,  bootstrap 3 is the easiest and way to integrate modal boxes into your site. If you don't want to use the whole bootstrap style sheet - the bootstrap site has the option to just download the modal aspect and not the whole stylesheet.

So first we are going to deal with JQUERY modal boxes

JQuery Modal box

HERE is the Jquery modal boxes: We have to 'uploadimage' and 'deleteimage' - we are going to have a list of users, each user might or might not have an image connected to it. Our 'user list page' can be generated by a PHP or in a Framework like Symfony, Cakephp, Laravel etc. On our 'user list page' can either just paste in our modal boxes our use PHP to include them. We are including them, have a look at our 'user list page'

<h1>Users list</h1>
    <div data-table-filter class="pull-right">
        <input class="form-control" type="text" placeholder="Filter results here">
    </div>
    <br><br>
<table class="table table-bordered table-paginated table-sortable table-filterable">
    <thead>
        <th>Name</th>
        <th> </th>
    </thead>
    <tbody>
<?php if(!empty($users)) { ?>
       <?php foreach($users as $user) { ?>
    <tr>
        <td><?php echo $user->name; ?></td>
        <td>
            <?php if(!empty($user->image)) { ?>

                <a
                        href="#deleteimage"
                        role="button"
                        class="btn btn-danger pull-right"
                        data-toggle="modal"
                        data-target="#deleteimage"
                        data-id="<?php echo $user->id; ?>"
                >
                    <i class="icon-trash"></i>
                </a>

                <a
                        href="#viewimage"
                        role="button"
                        class="btn btn-success pull-right viewimg"
                        data-toggle="modal"
                        data-target="#viewimage"
                        data-id="<?php echo $user->id; ?>"
                >
                    <i class="icon-eye-open"></i>
                </a>

          <?php } else { ?>
                <a
                        href="#uploadimage"
                        role="button"
                        class="btn btn-primary pull-right"
                        data-toggle="modal"
                        data-target="#uploadimage"
                        data-id="<?php echo $user->id; ?>"
                >
                    <i class="icon-upload"></i>
                </a>
          <?php } ?>

        </td>
    </tr>
?php } ?>
?php } ?>
    </tbody>
</table>
<?php include('deleteimage_modal.php'); ?>
<?php include('viewimage_modal.php'); ?>
<?php include('uploadimage_modal.php'); ?>

Now have a look at the two files we included, which feeds information to it via JQUERY, ( obviously you need to include or link to jquery somewhere on your page )

deleteimage_modal page

<div class="modal fade" id="deleteimage" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="myModalLabel">Are you sure?</h4>
            </div>
                <div class="modal-body">
                    <p>Are you sure that you wish to delete this image?</p>
                    <p><strong>This action cannot be undone!</strong></p>
                </div>
            <div class="modal-footer">
                <button class="btn pull-left" data-dismiss="modal" aria-hidden="true">Cancel</button>
                <form method="POST" action="/users/deleteimage"  accept-charset="utf-8">
                    <input type="hidden" id="deletevalue" value="" name="id" >
                    <button type="submit" class="btn btn-primary pull-right">Yes, I am sure</button>
                </form>
            </div>
        </div>
    </div>
</div>

in the 'userlist page', the '#deleteimage' will activate this modal box (if you have your links to bootstrap 3 in place)
The same for the '#uploadimage' it will activate the 'uploadimage_modal.php' window.

Can you see this hidden field in the 'deleteimage_modal.php' page?
 

 <input type="hidden" id="deletevalue" value="" name="id" >

We are going to pass the id via JQuery to this field, then when you submit this page it will post to that function and perform the action - in this case delete the image. They way we do this is by including a javascript file. Like this

    $('#deleteimage').on('show.bs.modal', function(event) {
        $("#deletevalue").val($(event.relatedTarget).data('id'));
    });

The id is in the list in data-id="<?php echo $user->id; ?>"  then it gets send to the jquery file that inserts into the modal, which does the rest.

The same for the viewimage modal
 

    $('#uploadimage').on('show.bs.modal', function(event) {
        console.log($(event.relatedTarget).data('id'));
        $("#uploadvalue").val($(event.relatedTarget).data('id'));
});

Uploadimage_modal page

<div class="modal fade" id="uploadimage" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="myModalLabel">Upload an Image</h4>
            </div>
            <form method="POST" action="/uploadimage" enctype="multipart/form-data" accept-charset="utf-8">
                <div class="modal-body">
                    <fieldset>
                        <input type="file" name="fileuploads" id="fileuploads">
                        <input type="hidden" id="uploadvalue" value="" name="id">
                    </fieldset>
                </div>
                <div class="modal-footer">
                    <button type="submit" class="btn btn-primary pull-right">Submit</button>
                </div>
            </form>
        </div>
    </div>
</div>

 

When you click submit on the deleteimage it will do the action on the deleteimage() function and the same for the uploadimage() function.

Here is an example of how the controller with these functions in might look like, below once we have dealt the how AJAX work, I will post the whole javascript file aswell.

<?php

class UserimagesController extends Controller
{

    public function imageManager()
    {
        $this->jsfiles[] = $this->link('/js/imagemanager.js');
        $this->stylesheets[] = "/css/font-awesome.min.css";

       // $results =
       // Query database here and get results to display in list
        $this->set('results', $results);

    }


         public function upLoadImage()
    {
        if ($_POST) {

            // do some validation to see if you get the values you expect

            if (empty($_POST['id'])) {
                $this->flash("You have to select an image, please try again", "error");
                $this->redirect('/imagemanager');
            } else {
                $id = htmlspecialchars($_POST['id']); // do some escaping to make your site secure
            }

            if (empty($_FILES['fileuploads']['name'])) {
                $this->flash("You have to select an Image, please try again", "error");
                $this->redirect('uploadimage/' . $id);
            }

            // here I will load the function that deals with image uploads, rename, resize etc

        }

    }

        public function deleteImage($id)
        {
            if ($_POST) {

                // do some validation to see if you get the values you expect

                if (empty($_POST['id'])) {
                    $this->flash("You have to select an image, please try again", "error");
                    $this->redirect('/imagemanager');
                } else {
                    $id = htmlspecialchars($_POST['id']); // do some escaping to make your site secure
                }

                // access a function here that help you retrieve the image name based on the id

                $image = $result['image_name'];

                if ($image === true) {
                    // delete your image here and update the database function can be accessed here
                    $this->flash("The image has been deleted", "success");
                    $this->redirect('/imagemanager');
                } else {
                    $this->flash("Sorry, the image was not deleted", "error");
                    $this->redirect('/imagemanager');
                }

                $this->layout = null;
            }
        }

    public function displayImage($id)
    {
        if (!$this->isAjax()) {
            return $this->requestBadRequest400();
        }

        if (empty($id)) {
            $this->flash("Please select and image to view", "error");
            $this->redirect('imagemanager');
        }

        $id = htmlspecialchars($id); // some escaping

        // access a function here that help you retrieve the image name based on the id

        $image = $result['image_name'];

        $values['id'] = $result['id'];
        $values['name'] = $result['user'];
        $values['image'] = '<img src="'.$image.'" alt="'.$result['user'].' style="max-width:400px;">';

        $this->sendJsonResponse($values);

    }


    private function requestBadRequest400()
    {
        header("HTTP/1.0 400 Bad Request");
        echo 'Bad request.';
        exit;
    }

    /**
     * @param $data mixed
     */
    private function sendJsonResponse($data)
    {
        $json = json_encode($data);
        header("HTTP/1.1 200 OK");
        header('Content-type: application/json');
        echo $json;
        exit;
    }

}

The is all we need to have the JQUERY - Bootstrap modal boxes work

Ajax - bootstrap modal boxes

Let's start backwards with the ajax way of doing this, the end result is we want to hit the 'displayimage()' function and then display that in our modal. As you see in the 'displayimage()' function - we tell it it is 1. Ajax, 2. We output the values we get from the database then 3. Json_encode them.

We are using the javascript below to display the values from our function to our  modal box..

    $(".viewimg").on("click",function () {
        var dataID = $(this).data('id');

        $.ajax({
            url: '/users/viewImage/' + dataID,
            type:'GET',
            dataType: 'json',
            context: this,
            success: function(values)
            {
                $('.id').html(values.id);
                $('.user').html(values.make);
                $('.image').html(values.image);
                // log all values to the javascript console in your browser
                console.log(values);
                $(".loader").hide();
            },
            fail: function () {
                modal.find('.modal-body').append('<div class="alert alert-error">Oops! something went wrong</div>');
                $(".loader").hide();
            }
        });
    });

In the javascript we tie the values we get from the function in php to the javascript console then we'll display them, once they are loaded we tell the imageloader to stop displaying.

Viewimage_modal page

<div class="modal fade" id="viewimage" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="myModalLabel"><span class="user"> </span></h4>
            </div>
            <div class="modal-body" style="text-align:center;">
                <div class="loader" id="loader"><img src="/img/progress.gif"/><span>Loading, please wait...</span></div>
                <span class="image"> </span>
            </div>
            <div class="modal-footer">
            </div>
        </div>
    </div>
</div>

here are the complete javascript file for both the ajax and jquery modal boxes together..

$(document).ready(function() {

    $(".viewimg").on("click",function () {
        var dataID = $(this).data('id');

        $.ajax({
            url: '/viewImage/' + dataID,
            type:'GET',
            dataType: 'json',
            context: this,
            success: function(values)
            {
                $('.id').html(values.id);
                $('.user').html(values.make);
                $('.image').html(values.image);
                // log all values to the javascript console in your browser
                console.log(values);
                $(".loader").hide();
            },
            fail: function () {
                modal.find('.modal-body').append('<div class="alert alert-error">Oops! something went wrong</div>');
                $(".loader").hide();
            }
        });
    });

    $('#uploadimage').on('show.bs.modal', function(event) {
        console.log($(event.relatedTarget).data('id'));
        $("#uploadvalue").val($(event.relatedTarget).data('id'));
});

    $('#deleteimage').on('show.bs.modal', function(event) {
        $("#deletevalue").val($(event.relatedTarget).data('id'));
    });

});


Published: 27th March 2017 by

Adverts