简体   繁体   中英

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

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>

Change ID's according to your file, Below is an example of sending data of input type file and text through jquery/ajax. The important thing is var data=new FormData($("#myForm")[0]); this code will send data to your target file as in below case is sendDetails.php . you can change the target file name according to your requirement. Hope it help you :)

 $(document).ready(function(){ $("#submit").click(function(){ var form=$("#myForm"); var data=new FormData($("#myForm")[0]); $.ajax({ url:form.attr("action"), type:"POST", data:data, processData: false, contentType: false, success:function(d){ alert(d); } }); }); $("#myForm").submit(function(){ return false;}); $("#show").click(function(){ $("#showDetails").load("showDetails.php"); }); }) 
 <body> <div> <form id="myForm" method='post' action='sendDetails.php' enctype='multipart/form-data'> Name: <input type="text" placeholder="Please Enter Your Name:" name="studentName" id="name"><br> CNIC: <input type="text" placeholder="Please Enter Your CNIC:" name="studentCNIC" id="CNIC"><br> Gmail:<input type="text" placeholder="Please Enter Your Gmail:" name="studentGmail" id="Gmail"><br> Image:<input type="file" name="studentimage" id="image"><br> <Button id="submit" name="submit">Save</Button> </form> </div> <div id="showDetails"> </div> <div> <Button id="show">Show_Details</Button> </div> </body> 

url:form.attr("action"), type:"POST", data:data, processData: false, contentType: false, success:function(d){ alert(d); }

    });

});

$("#myForm").submit(function(){ return false;});

$("#show").click(function(){

    $("#showDetails").load("showDetails.php");
});

})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM