Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax - Sending input file and additional variable to php file through ajax

I'm trying to send input file and input text through ajax. Because I'll add this feature to my existing function that has plenty of other variables I cannot simply use sending the entire Form like the one used here

Uploading both data and files in one form using Ajax?

This is the basic gist of it

My HTML

<input type='text' name='text' id='text'>
<input type='file' name='media' type="file" / id='media'>
<input type="button" value="Upload" name='submit'/>

My Ajax

$(":button").click(function(){
        var myFormData = new FormData();
        var media = document.getElementById('media');
        var variable = 'foo';
        myFormData.append('pictureFile', media.files[0]);
        var text = $("#text").val();
        $.ajax({ 
            type: 'POST',
            url: 'upload.php',
            data: 
            {
                pictureFile: myFormData,
                text: text,
                var: variable,
            },  
            cache: false,
            success: function (data) {
                alert(data);
            },
            processData: false,
            contentType: false, 
        });
}); 

PHP

include_once ("connection.php");
if ($_SERVER['REQUEST_METHOD'] == 'POST'){

    $temp_name = $_FILES['pictureFile']['name'];
    $pic_type = $_FILES['pictureFile']['type'];

    $pic_temp = $_FILES['pictureFile']['tmp_name'];
    $pic_path = "images/";
    move_uploaded_file($pic_temp,'images/'.$temp_name);

}

So as shown in my code I need a way to send those var media, var text and var variable from data:{}, to upload.php

like image 506
thewheeloftimefan Avatar asked Jan 31 '17 03:01

thewheeloftimefan


1 Answers

You can achieve that by using append

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Jquery Ajax File Upload</title>
</head>
<body>
    <input type='text' name='text' id='text'>
    <input type="file" name="media" id="media">
    <div class="result"></div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script>
    $(document).ready(function(){
        $('#media').change(function(e){
            var file = this.files[0];
            var form = new FormData();
            form.append('media', file);
            form.append('text', $('#text').val());
            $.ajax({
                url : "upload.php",
                type: "POST",
                cache: false,
                contentType: false,
                processData: false,
                data : form,
                success: function(response){
                    $('.result').html(response.html)
                }
            });
        });
    });
    </script>
</body>
</html>
like image 163
Saravanan Sampathkumar Avatar answered Nov 15 '22 10:11

Saravanan Sampathkumar