I am trying to add products to a database, along with some pictures, server-side is PHP. I want to upload everything asynchronously via AJAX. I want the pictures saved in a directory name after the product id ( thumbs/productID ).
The first part, which is submiting the product information and retrieving its id is done. However, when uploading the files, I can’t upload both files and strings, to inform my script in which folder to save. I can however send only the files.
Is there any way to send both files and text at the same time? Any help would be appreciated.
$('#register-product').on('submit', function ( evt ) {
evt.preventDefault();
var i = 0, len = document.getElementsByName("images").length-1, reader, file;
var myFiles = document.getElementsByName("images");
// Adds all files to formdata
for ( ; i < len; i++ ) {
file = myFiles[i].files[0];
if (!!file.type.match(/image.*/)) {
if ( window.FileReader ) {
reader = new FileReader();
reader.readAsDataURL(file);
}
if (formdata) {
formdata.append("images[]", file);
}
}
}
// Send data to the server.
if (formdata) {
$.ajax({
url: "upload.php",
type: "POST",
// data: formdata, // This is correct
data: {formdata, id: 1}, // This doesn't work
processData: false,
contentType: false,
success: function (res) {
console.log(res);
}
});
}
});
Just append another value to your formdata:
You can access it as you wont through $_POST[“id”].