0

I am trying to make an upload form, which uploads a photo with ajax, but a problem I currently have is, it doesn't really make a sense about it. Here is a code so do you have any ideas why it doesn't work ?

<form id="commentForm" enctype="multipart/form-data">
          <input type="file" name="fileToUpload">
    <button type="submit" name="commentSubmit" id="commentButton" class="btn green"><i class="fa fa-paper-plane"></i> </button>
</form>
<div id="output">GGG</div>
<script type="text/javascript">
    $('#commentForm').on('submit',(function(e) {

        e.preventDefault();

        $.ajax({
            type: 'post',
            url: 'test2.php',
            cache: false,
            contentType: false,
            processData: false,
            data: $('#commentForm').serialize(),
            success: function (html) {
                $('#output').html(html);

            }
        })
    }));
</script>

and here is "test2.php"

<?php


$day_hour = date("H");
$day_min = date("i");
$day_sec = date("s");


if (isset($_FILES["fileToUpload"]["tmp_name"])) {
error_reporting(0);
$target_dir = "upload/";
$target_file = $target_dir . $photo_name_codi . "TSG" . $day_hour . $day_min . $day_sec . "_" . rand(100, 999) . ".jpg";
$uploadOk = 1;
$imageFileType = pathinfo($target_file, PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if (isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if ($check !== false) {
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if ($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif"
) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file " . $target_file . " has been uploaded. " . $imageFileType;
} else {
echo "Sorry, there was an error uploading your file.";
}
}
}
nika
  • 59
  • 1
  • 8
  • 2
    Possible duplicate of [How can I upload files asynchronously?](http://stackoverflow.com/questions/166221/how-can-i-upload-files-asynchronously) – u_mulder Mar 06 '17 at 09:05

1 Answers1

0

Try this:

Html:

<input id="pic" type="file" name="pic" />
<button id="upload">Upload</button>

Jquery:

$('#upload').on('click', function() {
        var file_data = $('#pic').prop('files')[0];
        var form_data = new FormData();
        form_data.append('file', file_data);

        $.ajax({
                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(output){
                    alert(output);              // display response from the PHP script, if any
                }
         });
         $('#pic').val('');                     /* Clear the file container */
    });

Php:

<?php
    if ( $_FILES['file']['error'] > 0 ){
        echo 'Error: ' . $_FILES['file']['error'] . '<br>';
    }
    else {
        if(move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']))
        {
            echo "File Uploaded Successfully";
        }
    }

?>
Mayank Pandeyz
  • 25,704
  • 4
  • 40
  • 59