Louis Shiggy Lombardi Louis Shiggy Lombardi - 1 month ago 5x
Ajax Question

Return PHP data with AJAX

I am slowly learning how to build a fully custom CMS system, and currently building a Image Uploader. Ive got my PHP form to work but what i want is to send and return data to the upload.php file using AJAX. So far i have managed to successfully send the form data to PHP and the image is uploaded into the my uploads folder. The trouble I am having is that nothing is returned to me to tell me if it was successful or not. I would like the image to display if its successful and and error message if its not. I am not that experienced with using Javascript or AJAX so could someone please look at my code and tell me where i am going wrong?


<div class="container-main">
<form action="" method="post" id="myForm" enctype="multipart/form-data">
<input type="file" name="file" id="file"><br>
<input type="submit" id="upload-img" name="submit" class="btn btn-success" value="Upload Image">

<div class="progress progress-striped active">
<div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%">
<span class="sr-only">0% Complete</span>
<div class="image">
<!-- uploaded image goes here -->

<script type="text/javascript" src="js/custom.js"></script>


$('#upload-img').on('click', function() {
var file_data = $('#file').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
url: 'upload.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(){
$(".image").html("<img src='"+response.responseText+"' width='100%'/>");



$allowedExts = array("gif", "jpeg", "jpg", "png","GIF","JPEG","JPG","PNG");

$temp = explode(".", $_FILES["file"]["name"]);

$extension = end($temp);

if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& in_array($extension, $allowedExts)) {

if ($_FILES["file"]["error"] > 0) {
echo "Invalid File Type";
} else {
$target = "../upload/";
move_uploaded_file($_FILES["file"]["tmp_name"], $target. $_FILES["file"]["name"]);
echo "../upload/" . $_FILES["file"]["name"];

} else {
echo "Error uploading image";

Many Thanks!


You don't need to use the .responseText property (it doesn't exist anyway)

and your function should be like so:

success: function(response){
                    $(".image").html('<img src="'+response+'" width="100%"/>');


Note I changed your single/double quotes around.