jquery – file uploading in PHP & Ajax from bootstrap modal-ThrowExceptions

Exception or error:

Before beginning let me say that i had referred many of the other post to resolve my issue, but I couldn’t put it wright or find a solution particular to my problem. That is the reason of my question here.

Let me begin I’m presently using some form elements in a modal. All the form elements submits through my present ajax and stores in mysql db.

But when I add file upload element to the form, My ajax donot submit the form and do not reflect in mysql db.

HTML:

<div class="col-md-12 col-sm-12 col-xs-12 form-group has-feedback">
    <label style="color:#333D79FF; font-size:15px;">Upload Files </label>
    <input type="file" name="srfile" id="srfile" class="form-control has-feedback-left" accept=".jpg,.jpeg,.png,.pdf,.doc,.docx,.xls,.xlsx"/>
    <span class="fas fa-upload form-control-feedback left text-info" aria-hidden="true"></span>
    <span id="info">Only</span> .jpg, .jpeg, .png, .pdf, .doc, .docx, .xls, .xlsx files allowed. Max File Size 2 MB
</div>

I use bootstrap validator to validate my form elements, after validating it submits to the php and therby to mysql db.

JQUERY:

$(document).ready(function() {
.on('success.form.bv', function(e) {
            // Prevent submit form from page loading or refreshing

            e.preventDefault();

            // get the form data
            // there are many ways to get this data using jQuery (you can use the class or id also)
            var formData = {
                'firstname'         : $('input[name=firstname]').val(),
                'lastname'          : $('input[name=lastname]').val(),
                'gender'            : $('input[name=gender]').val(),
                'address'           : $('input[name=address]').val(),
                'city'              : $('select[name=city]').val(),
                'state'             : $('select[name=state]').val(),
                'country'           : $('select[id=country').val(),
                'aboutyourself'     : $('textarea[name=aboutyourself]').val(),
                'uploadfile'        : $('input[type=file]').val(),
                'send'              : $('button[name=send]').val()
            };

            // process the form
            $.ajax({
                type        : 'POST', // define the type of HTTP verb we want to use POST
                enctype     : 'multipart/form-data',
                url         : 'pages/insert.php', // the url where we want to POST
                data        : formData, // our data object
                dataType    : 'json', // what type of data do we expect back from the server
                encode      : true
            })
                // using the done promise callback
                .done(function(data) {

                    //log to the console form data in object form
                    //console.log(JSON.stringify(formData));

                    // log responce data to the console so we can see
                    console.log(data); 

                    // ALL GOOD! just show the success message!
                    $(".status").html(data.status);
                    $(".msg").html(data.msg);
                    if (data.status_code===200) {
                        $('#status').html(data.status);
                        $('#msg').html(data.msg);
                    } else {
                        $('#statuserror').html(data.status);
                        $('#msgerror').html(data.msg);
                    }

                });

            });
    });

My insert.php

if(isset($_POST['send'])){

        $firstname=$_POST['firstname'];
        ......
        .....
        .....
        etc..,


        //File Upload
        if(isset($_FILES['uploadfile'])){
            $errors= array();
            $file_name = $_FILES['uploadfile']['name'];
            $file_size = $_FILES['uploadfile']['size'];
            $file_tmp = $_FILES['uploadfile']['tmp_name'];
            $file_type = $_FILES['uploadfile']['type'];
            $file_ext=strtolower(end(explode('.',$_FILES['uploadfile']['name'])));

            $extensions= array("jpeg","jpg","png","pdf","doc","docx","xls","xlsx");

            if(in_array($file_ext,$extensions)=== false){
                $errors[]="extension not allowed, please choose a JPEG or PNG file.";
            }

            if($file_size > 2097152) {
                $errors[]='File size must be excately 2 MB';
            }

            if(empty($errors)==true) {
                move_uploaded_file($file_tmp,"images/".$file_name);
                echo "Success";
            }else{
                print_r($errors);
            }
        }

        $adduser=$link->prepare("INSERT INTO `users` (`firstname`,`lastname`,`gender`,`address` ,`city` ,`state` ,`country`  ,`aboutyourself` ,`file`) VALUES (?,?,?,?,?,?,?,?,?)");
        $adduser->bind_param('sssssssss', $firstname, $lastname, $gender, $address, $city, $state, $country, $aboutyourself, $file_name);
        $adduser->execute();
        if($adduser) {
            $success = array(
                'status' => 'Success!', 
                'status_code' => 200, 
                'msg' => 'User has been added.');
            echo json_encode($success);
        }else {
            $error = array(
                'status' => 'Error!', 
                'status_code' => 404, 
                'msg' => 'Error occurred in adding user. Please modify and try again.');
            echo json_encode($error);
        }
    }

My problem is when i add $file_name in the insert query this do not insert the values nor the file is uploaded. Otherwise when I donot use $file_name value all other values are being added to the db.

Note: please understand that there are various input field i’ve used such as firstname, lastname, address, etc. although i’ve not shown the code of those in my HTML code above just to reduce code. I hope you will understand

Where did I go wrong. Please help. Appreciate your positive response.

UPDATE:
To my above ajax formdata variable, I’ve made changes as below

var formData = {
                'firstname'         : $('input[name=firstname]').val(),
                'lastname'          : $('input[name=lastname]').val(),
                'gender'            : $('input[name=gender]').val(),
                'address'           : $('input[name=address]').val(),
                'city'              : $('select[name=city]').val(),
                'state'             : $('select[name=state]').val(),
                'country'           : $('select[id=country').val(),
                'aboutyourself'     : $('textarea[name=aboutyourself]').val(),
                'send'              : $('button[name=send]').val()
            };

            formData.append("uploadfile",$('input[type=file]')[0].files[0]);

I’m not finding success to upload the file

How to solve:

Finally I found the solution. Basically I’ve changed the ajax formdata and restructured my insert.php file.

Below link helped me to understand the idea.
https://www.codexworld.com/ajax-file-upload-with-form-data-jquery-php-mysql/

my modified ajax is as below

        $.ajax({
                type        : 'POST', // define the type of HTTP verb we want to use POST
                enctype     : 'multipart/form-data',
                url         : 'insert.php', // the url where we want to POST
                data        : new FormData(this),
                dataType    : 'json',
                contentType : false,
                cache       : false,
                processData : false,
            })

Leave a Reply

Your email address will not be published. Required fields are marked *