1

How do I use AJAX, Javascript and PHP to POST data AND a file?

I can post the data inputs "name" and "lname", but not the file "myfile".

I have a input page called "input.php" and a post page called "postit.php".

input.php

My html:

<form method="post" name="form" action="postit.php" enctype="multipart/form-data">
    <input type="text" name="name" id="name" placeholder="Name" >
    <input type="text" name="lname" id="lname" placeholder="lname">
    <input type="file" name="myfile" id="myfile" placeholder="myfile">

    <button type="button" onclick="myFunction()">Save</button><br>
</form>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

My Javascript:

function myFunction() {
    var name = document.getElementById("name").value;
    var lname = document.getElementById("lname").value;
    var myfile = document.getElementById("myfile").value;
    $.ajax({
        type : "POST",
        url  : "postit.php",
        data : { name : name, lname : lname, myfile: myfile },
        success: function(res){                                      
            setTimeout(function () {location.reload()}, 400);
        }
    });
}

postit.php

<?php 
$name = $_POST['name']; 
$lname = $_POST['lname']; 
$myfile = $_FILES['myfile']['name'];
?>
user2868139
  • 97
  • 2
  • 6

0 Answers0