3

I am facing an error where I am unable to pass the image file through AJAX when uploading a image file. Here are my codes

AJAX

    var file = $("#thumbnail").get(0).files[0];
alert(file.name+" | "+file.size+" | "+file.type);
var formdata = new FormData();
formdata.append("file", file);

alert (formdata);

    $.ajax({
        url: "php/post-check.php",
        type: "POST",
        data: {
            title: title,
            thumbnail: formdata
        },
        success: function (data) {
            $("div#postresult").removeClass("alert alert-danger");
            $("div#postresult").html(data);
        }
    });

PHP

<?php 
        $target_dir = "../thumbnail-pictures/";
        $target_file = $target_dir . basename($_FILES["thumbnail"]["name"]);
        $uploadOk = 1;
        $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);

        if (file_exists($target_file)) {
            echo "Sorry, thumbnail file already exists. <br>";
            $uploadOk = 0;
        }

        if ($_FILES["thumbnail"]["size"] > 1000000) {
            echo "Sorry, your file is too large.";
            $uploadOk = 0;
        }

        if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg") {
            echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
            $uploadOk = 0;
        }

        if ($uploadOk == 0) {
            echo "Sorry, your file was not uploaded, ";

        } else {
            if (move_uploaded_file($_FILES["thumbnail"]["tmp_name"], $target_file)) {
                
            } else {
                echo "Sorry, there was an error uploading your file.";
            }
        }
        ?>

HTML

<form action="" method="post" enctype="multipart/form-data" id="newpost">
                <div class="col-lg-12">
                        <div class="form-group">
                            <label>Title</label>
                            <input class="form-control" name="title" id="title" required>
                            
                        </div>

                        <div class="form-group">
                            <label>Video Thumbnail **Only JPEG & PNG is accepted**</label>
                            <input type="file" name="thumbnail" id="thumbnail" accept="image/png, image/gif, image/jpeg" >
                        </div>

The PHP code itself is working fine so I assume that the problem lies within the AJAX section, however I am unsure of how to solve this. Thankful for any help given!

peterh
  • 11,875
  • 18
  • 85
  • 108
Jun Jie
  • 149
  • 1
  • 15

3 Answers3

0

the problem should be on the parameter processData, please add the parameter processData: false, to your ajax request and try to get your image on the php.

            $.ajax({
                url: formURL,
                type: form.attr('method'),
                dataType: 'json',
                data: formData,//form.serialize(),
                processData: false,  // tell jQuery not to process the data
                contentType: false,   // tell jQuery not to set contentType
                beforeSend: function(){},
                success: function(data, textStatus, jqXHR) {},
                error: function(jqXHR, textStatus, errorThrown) 
               {
                  alert(jqXHR+ textStatus+ errorThrown);
                },
              complete: function(){}
                });

hope helps.good luck

Theo Itzaris
  • 4,321
  • 3
  • 37
  • 68
0

Place your inputs properly in one form and use FormData() to send the form as a whole. I would suggest something like this :

<form method="post" enctype="multipart/formdata" id="myForm">
   <input type="text" name="title" />
   <input type="file" name="thumbnail" />
</form>

Build and send the data with js :

var form = document.getElementById('myForm');
var formData = new FormData(form);

alert (formdata);

$.ajax({
    url: "php/post-check.php",
    type: "POST",
    data: formData,
    success: function (data) {
        $("div#postresult").removeClass("alert alert-danger");
        $("div#postresult").html(data);
    }
});

Now you can get the data in php like this way :

$title = $_POST['title'];
$thumb = $_FILES['thumbnail'];
$tmp_file_path = $thumb['tmp_name'];
-1

You could just post the entire form in async using ajaxForm() like this:

$("#newpost").ajaxForm({
    success: function(data) {
        $("div#postresult").removeClass("alert alert-danger");
        $("div#postresult").html(data);
    },
    error: function(a, textStatus, exception) {

    }
});

AjaxForm is not part of core JQuery but you can find the source here and the documentation here

Calle Bergström
  • 480
  • 4
  • 12