Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to upload image to the server using Bootstrap's Modal dialog box, jQuery, AJAX and PHP? If yes how? If no what's the reason for it?

I'm using PHP, jQuery(jquery-1.9.1.min.js and jquery-ui-1.10.0.custom.min.js), AJAX, Bootstrap design framework(Bootstrap v3.0.0), etc.

I'm relatively a newbie in the field of Web Programming.

Now at one place I want to show Bootstrap framework's inbuilt modal dialog box on click of a button. In this modal dialog box there will be a HTML File control for uploading the image file. User will select any image file from his/her local machine by browsing the files. Then after performing all the following necessary validations like

  • proper standard image extension
  • maximum size limit of 5 MB
  • minimum dimensions of 940 px * 370 px

the file should be uploaded to the server using PHP code. If any of the validations fail the relevant error message should be displayed in red color above the File Upload HTML control.

Is it possible to achieve this functionality? I heard that it's not possible to upload files using AJAX. I really don't know whether it's a myth or a fact. If someone knows about this thing please explain to me in detail.

like image 652
PHPFan Avatar asked Dec 12 '22 03:12

PHPFan


1 Answers

Yes, it's possible. Here's something to get you started.

Note: This uses the PHP class class.upload.php for uploading images. (http://www.verot.net/php_class_upload.htm)

All of this code has been tested and works. I just whipped it up, so it's pretty basic but should point you in the right direction. You'll need to sanitize inputs, do the correct messaging, etc.

Just create a file (index.html) and copy/paste the HTML and JavaScript into it. Then create a file post.php and put the PHP in it. Download the class.upload.php script and then create a directory named uploads. Give it the appropriate permissions (0755 or 0777). Keep everything in the same folder for this example. You should be good to go.

It's even possible to put the success and error messages right in the modal. I'm just using alert() here for brevity. If you want to put the messages in the modal, just create a <div> in the modal, give it an ID and then target that ID in the jQuery where I'm using alert(). It's pretty easy.

Edit: Added messaging to the example. :)

Here's the HTML and jQuery (index.html)

<!DOCTYPE html>
    <html>
    <head>
        <title>Upload a Photo</title>
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0">
        <link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
        <!--[if lt IE 9]>
            <script src="//oss.maxcdn.com/libs/html5shiv/r29/html5.min.js"></script>
            <script src="//oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
        <![endif]-->
    </head>
    <body>

        <div class="container">
            <button class="btn btn-primary" data-toggle="modal" data-target="#myModal">Open Modal</button>

            <div class="modal fade" id="myModal">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <form id="form" enctype="multipart/form-data" role="form">
                            <div class="modal-header">
                                <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                                <h4 class="modal-title">Upload Photo</h4>
                            </div>
                            <div class="modal-body">
                                <div id="messages"></div>
                                <input type="file" name="file" id="file">
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                                <button type="submit" class="btn btn-primary">Save</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>

        </div>

        <script src="http://code.jquery.com/jquery.js"></script>
        <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
        <script>
            $('#form').submit(function(e) {

                var form = $(this);
                var formdata = false;
                if(window.FormData){
                    formdata = new FormData(form[0]);
                }

                var formAction = form.attr('action');

                $.ajax({
                    type        : 'POST',
                    url         : 'post.php',
                    cache       : false,
                    data        : formdata ? formdata : form.serialize(),
                    contentType : false,
                    processData : false,

                    success: function(response) {
                        if(response != 'error') {
                            //$('#messages').addClass('alert alert-success').text(response);
                            // OP requested to close the modal
                            $('#myModal').modal('hide');
                        } else {
                            $('#messages').addClass('alert alert-danger').text(response);
                        }
                    }
                });
                e.preventDefault();
            });
        </script>
    </body>
</html>

And your PHP script (post.php)

<?php

    require_once 'class.upload.php';

    $handle = new Upload($_FILES['file']);
    $handle->allowed = 'image/*';

    if($handle->uploaded) {
        $handle->Process('uploads');
        if($handle->processed) {
            echo 'Image uploaded';
        } else {
            echo 'error';
        }
    }
like image 146
timgavin Avatar answered Dec 14 '22 22:12

timgavin