I have a PHP page in which a user can insert data (with input text or files) in a DB. These data will be visualized on a web site. I need a preview button. When the user click on preview button, it will be opened a popup window with the text and the image that he has inserted.
So, I need to upload the image on server (to get the complete path of the image and display it) without a submit button and without a refresh of the page in which the user is inserting data (because they don't have to be lost).
I was thinking of ajax and php
my code index.php:
<form action="filePHPForPublishing" method="Post">
//other code...
<input type="file" name="img" id="img" />
<input type="button" id="Preview" name="Preview" value="Preview">
//other code...
<input type="submit" id="publish" name="publish" value="publish">
</form>
my code ajax.js:
$(document).ready(function () {
$("#Preview").click(function() {
var datiForm = new FormData();
datiForm.append('image', $('#img')[0].files[0]);
$.ajax({
type: 'post',
url: 'ajax.php',
data: datiForm,
dataType: 'text',
contentType: false,
processData: false,
success: function (data) {
alert(data);
return false;
},
error: function (xhr, textStatus, errorThrown) {
alert(xhr.status + ': ' + errorThrown);
alert("error");
}
})
});
});
my code ajax.php:
$target_dir = "";
$target_file = $target_dir . basename($_FILES["img"]["name"]);
$uploadOk = 1;
move_uploaded_file($_FILES["img"]["tmp_name"], $target_file);
$linkIMG = basename( $_FILES["img"]["name"]);
But when I click the preview button, there is an error on the php file "undefinable variable img" in this point "$target_file = $target_dir . basename($_FILES["img"]["name"]);
"
am I doing something wrong? I'm new with ajax