jquery - How to pass the image file from an input type file with Ajax to PHP using $.post
Get the solution ↓↓↓I've been seeing a lot of thread about this, but I still cannot figure out how to make it work with $.post. I just recently added this input type file for uploading an image together with a text that will go to my database. I can get this done in server side but not with ajax. Some said to use the FormData object but I still can't make it work.
My goal is to simply move the image to a specific folder with AJAX and PHP. What I can't figure out is how to pass the image from the input type file with AJAX to PHP.
The codes I provided below is as basic I could make them for them to be easy to read here.
Here's my html
<form name="form" id="form" action="upload.php" method="post" enctype="multipart/form-data">
<input type="text" id="message" name="message"/>
<input type="file" id="imgupload" name="file" accept="image/jpeg, image/png, image/gif"/>
<input type="submit" id="submit" name="submit" value="Submit"/>
</form>
Here's my Ajax call
$(document).on("click", "#submit", function() {
var message = $("#message").val();
var form = $("#form")[0]; //this is what I'm trying to figure out
var form_data = new FormData(form); //this is what I'm trying to figure out
$.post("upload.php", {
message: message,
form_data //this is what i'm trying to pass to upload.php but doesn't work
}, function(data) {
// success msg
};
});
Here's my php:
if($_FILES['file']['name'] != '') {
$filename = $_FILES['file']['tmp_name']
$path = $_FILES['file']['name'];
$fullpath = "../uploads/images/".$path;
move_uploaded_file($filename, $fullpath);
$message = $_POST['message']; //this is for the message in input text, you may ignore
$messageQuery = "insert to db...." //this is for my insert query for database, you may ignore
mysqli_query($conn, messageQuery) //again this is just a query for database, you may ignore
}
else {
echo "Failed to upload";
}
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: warning: a non-numeric value encountered in
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.