Reputation: 554
I've looked around but I can't seem to find a solution to this. I'm a newbie when it comes to AJAX/PHP so please forgive me if this is a simple question.
I have this AJAX that is supposed to grab the image uploaded in a form and pass it to the handler to copy on server.
My indexing system is verified on the client side, so I need to be able to pass the Id variable to rename the file. Here's the AJAX code:
var input = document.getElementById("imgBrw");
file = input.files[0];
if (file !== undefined) {
formData = new FormData();
if (!!file.type.match(/image.*/)) {
formData.append("image", file);
console.log(formData);
$.ajax({
url: "file_handler.php",
type: "POST",
data: formData,
processData: false,
contentType: false,
success: function () {
console.log('img copied');
}
});
} else {
alert('Not a valid image!');
}
} else {
console.log('No image change');
}
And here is my PHP:
$name = $_POST["articleA"];
$dir = "img/content/$name";
move_uploaded_file($_FILES["image"]["tmp_name"], $dir);
As you can see there is no articleA variable in the AJAX, but when I try to add it to data it doesn't write the image at all, like so:
data:{formData:formData, articleA: articleA}
My question is how to pass the articleA variable alongside the image data in formData.
Upvotes: 2
Views: 1521
Reputation: 11
$.ajax({
type: "POST",
url: "insert_record.php",
//dataType:'json',
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function(data) {
alert("OK");
}
});
Upvotes: 1
Reputation: 554
Got it! In the end I left:
formData.append("image", file);
and added another:
formData.append("nameA", articleA);
On the PHP side simply got it on POST:
$name = $_POST['nameA'];
$dir = "img/content/$name";
move_uploaded_file($_FILES["image"]["tmp_name"], $dir);
Upvotes: 3