-1

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

theveil
  • 57
  • 11
  • You can not perform a file upload by just trying to read `.val()` of the file input field. https://stackoverflow.com/questions/166221/how-can-i-upload-files-asynchronously – CBroe Mar 17 '20 at 11:55
  • Thanks. could you please advise to properly declare the code – theveil Mar 17 '20 at 11:58
  • What do you think I _just_ posted that link for …?!? – CBroe Mar 17 '20 at 11:59
  • yes, i was refering your link. Ive alreday assigned data: formData in my ajax, now how to incorporate this data: new FormData($('#formWithFiles')[0]), ???? – theveil Mar 17 '20 at 12:07
  • Those are two completely different things, you just happen to have a variable that was named `formData` by chance. If you just want to send _all_ the fields of your form - then don’t bother with adding them indivually, just pass the whole form element to the FormData constructor, then it will create the complete form data submission set for you. – CBroe Mar 17 '20 at 12:11
  • Another simple explanation, that focuses on the important parts: https://stackoverflow.com/a/21045034/1427878 – CBroe Mar 17 '20 at 12:12
  • once again thanks for your time in finding link in helping me. what i understands is to append the file upload element to the formdata. I have done it like this. formData.append("uploadfile",$('input[type=file]')[0].files[0]); but still I'm not able to get any response. Apologies of my question if being silly to you. – theveil Mar 17 '20 at 12:20
  • And `formData` would be what exactly now then? Still your own variable by that name, which contains an object? That does not _have_ any `append` method. If that’s not what you mean, then please add your current code to the end of your question. – CBroe Mar 17 '20 at 12:26
  • form is perfectly submitting if i do not choose any upload file... My problem is only with the upload file – theveil Mar 17 '20 at 12:34
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/209773/discussion-between-theveil-and-cbroe). – theveil Mar 17 '20 at 12:43
  • @theveil , You can get all the fields just with the id (or the class) of your html form that you specified into the `form` tag. Please have a look at https://mkyong.com/jquery/jquery-ajax-submit-a-multipart-form/ for an example. – testuser Mar 17 '20 at 13:13

1 Answers1

0

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,
            })
theveil
  • 57
  • 11