1

I can retrieve input type text, textarea, select on Ajax / JQuery page. Then variable values are passed to PHP process page where data are retrieve using POST method and data inserted into database table. All things are working fine.

But when I try to retrieve value of input type file variable on Ajax / Query page, it is giving blank value. I tried different codes to do it which I found from internet.

Please advise so I can make necessary changes in my script to make it working.

personal_details.php

<form name="AddForm" id="AddForm" novalidate>
<div class="control-group form-group">
    .
    .
    <input type="file" name="file_photo" id="file_photo">
    .
    .
    other fields like Name, Mail etc
    .
    .
    <div id="success"></div>
    <!-- For success/fail messages -->
    <button type="submit" class="btn btn-primary">Send Message</button>
</div>
</form>

personal_details.js

$(function() {

$("#AddForm input,#AddForm textarea, #AddForm file").jqBootstrapValidation({
    preventSubmit: true,
    submitSuccess: function($form, event) {
        event.preventDefault(); 
        var name = $("input#name").val();
        var email = $("input#email").val();
        .
        .
        var file_photo = $("file#file_photo").val();
        //var file_photo = $('#file_photo')[0].files[0];
        //var file_photo = document.getElementById("file_photo").files[0];

        $.ajax({
            url: "./user/personal_details_p.php",
            type: "POST",
            data: {
                name: name,
                email: email,
                file_photo: file_photo,
            },
            cache: false,

            success: function(data) 
            {
                //alert(data);
                var $ResponseText_L=JSON.parse(data);
                .
                .
                if condition
                .
                .
            },
        })
    },
});

personal_details_p.php

$str_name = "";
if (isset($_POST["name"])) { $str_name = trim($_POST["name"]); }
$str_email = "";
if (isset($_POST["email"])) { $str_email = trim($_POST["email"]); }
$str_photo = "";
if(isset($_FILES['file_photo'])) { $str_photo = trim($_FILES['file_photo']['name']); }

.
.
SQL Query to insert data
.
.

$response['status']='SUC';
$response['message']="Data inserted successfully";
echo json_encode($response);
return;
1

5 Answers 5

1

Easy Ajax Image Upload with jQuery, PHP

All textbox, textarea and file type variables will be available on PHP process page with the same name like they have on HTML form page.

Sign up to request clarification or add additional context in comments.

Comments

0

I have made my own function for asynchronous upload with progress bar. I will try to write example for you. Also add enctype="multipart/form-data" attribute to your form.

var file_photo = $("file#file_photo").val();
var form = file_photo.parents('form');
file_photo.on('change', processUpload);

var processUpload = function() {
    var formData = new FormData(form[0]);

    $.ajax({
        url: "./user/personal_details_p.php",
        type: 'POST',
        xhr: function() {
            var myXhr = $.ajaxSettings.xhr();

            if(myXhr.upload) {
                myXhr.upload.addEventListener('progress', progressHandling, false);
            }

            return myXhr;
        },
        success: function(json) {
            file_photo.val(''); // Empty file input after upload
        },
        error: function() {
            // Do whatever you want as error message
        },
        data: formData,
        cache: false,
        contentType: false,
        processData: false
    });
};

var progressHandling = function(e) {
    if(e.lengthComputable) {
        // Uploaded bytes: e.loaded / Maximum bytes: e.total
    }
};

1 Comment

Ty, I will try this and will let you know result.
0

you can use https://github.com/blueimp/jQuery-File-Upload. It has various options and its documentation is also good. so if you can use plugin you can go with this

Comments

0

Please Try below code for file upload.

   $(function() {

    $("#AddForm input,#AddForm textarea, #AddForm file").jqBootstrapValidation({
        preventSubmit: true,
        submitSuccess: function($form, event) {
            event.preventDefault(); 
            var name = $("input#name").val();
            var email = $("input#email").val();

            // my edit for File upload code starts here

             var FileData = $('#file_photo').prop('files')[0];   
             var form_data = new FormData();                  
             form_data.append('file', FileData);

           // my edit for File upload code ends here             

            $.ajax({
                url: "./user/personal_details_p.php",
                type: "POST",
                data: {
                    name: name,
                    email: email,
                    file_photo: file_photo,
                },
                cache: false,

                success: function(data) 
                {
                    //alert(data);
                    var $ResponseText_L=JSON.parse(data);
                    .
                    .
                    if condition
                    .
                    .
                },
            })
        },
    });

1 Comment

Ty for your answer, page is not submitted when I keep this code 'file_photo: file_photo,' ... Please advise about this.
0

For accessing file you should have to do like this in jquery:

 $(function() {

$("#AddForm input,#AddForm textarea, #AddForm file").jqBootstrapValidation({
    preventSubmit: true,
    submitSuccess: function($form, event) {
        event.preventDefault(); 
        var name = $("input#name").val();
        var email = $("input#email").val();
         var file_data = $("#file_photo").prop("files")[0];

    var form_data = new FormData();

            form_data.append("doc_upload", file_data)
            var data_text=$('form').serializeArray();
            $.each(data_text,function(key,input){
                form_data.append(input.name,input.value);
            });
        $.ajax({
            url: "./user/personal_details_p.php",
           contentType: false,
           processData: false,
            data: form_data,  
            cache: false,

            success: function(data) 
            {
                //alert(data);
                var $ResponseText_L=JSON.parse(data);
                .
                .
                if condition
                .
                .
            },
        })
    },
});

7 Comments

After using above piece of code, I am not able to click on submit button now. Please advise.
then you have to pass for form_data to data please check answer i just edit it i hope you will get some idea
Ty... page is not submitted when I keep this code 'data: form_data,' on page ... Please advise about this.
Please check in firefox console and let me know error
TypeError: 'append' called on an object that does not implement interface FormData.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.