K Ahir
K Ahir

Reputation: 395

PHP - how to retrieve value of input type file on Ajax / JQuery page

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;

Upvotes: 1

Views: 6545

Answers (5)

RekKA
RekKA

Reputation: 150

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.

Upvotes: 1

user2110253
user2110253

Reputation: 315

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
                .
                .
            },
        })
    },
});

Upvotes: 0

Bhavin
Bhavin

Reputation: 2158

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
                    .
                    .
                },
            })
        },
    });

Upvotes: 0

jays
jays

Reputation: 13

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

Upvotes: 0

Patrik Kreh&#225;k
Patrik Kreh&#225;k

Reputation: 2683

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
    }
};

Upvotes: 0

Related Questions