jquery – Pass form data via ajax file


Good day!

I have such a problem – I'm going to upload images to the site without reloading the page via ajax.

There is this form:

<form name="uploadimages" method="post" enctype="multipart/form-data">
<input id="uploadimage" type="FILE" name="uploadimage" id="uploadfile">

and here is a function that should send a file from the upload field to the handler with Ajax like this:

 <script type="text/javascript">
        function setimage() {

        var uploadfile = $("#uploadimage").val();
                type: "POST",
                url: "uploadimages.php",
                data: "img=" + uploadfile,
        success: function(html){


There are no problems with this, everything works in the handler, except for one thing – there is a resize function, which also works separately!
Looks like this:

//тут объявляется функция

$img = $_POST['img'];//получаем данные

$image = imageResize($img, 'litimages', 1000, 1000);//делаем ресайз (пареметры - картнка, директория для сохраненияя, размеры)

$image = "<br><br><img src='".$image."' width='700'><br><br>"; //вставляем в тег адрес 
echo $image; //и возвращаем

Everything is logical, but in fact it gives an error:

Catchable fatal error: Argument 1 passed to imageResize() must be an array, string given, called in Z:\home\superli\www\uploadimages.php on line 92 and defined in Z:\home\superli\www\uploadimages. php on line 5

This, as for me, is connected with the fact that here

var uploadfile = $("#uploadimage").val();

the name of the image is sent, not the image itself.

Please help me figure out how to send the file itself, thanks in advance!


The question is about jQuery, not how to download files for all browsers. It's simple, take a look ( jsfiddle ):

function setimage() {
    var $input = $("#uploadimage");
    var fd = new FormData;

    fd.append('img', $input.prop('files')[0]);

        url: 'http://example.com/script.php',
        data: fd,
        processData: false,
        contentType: false,
        type: 'POST',
        success: function (data) {


Oh-ho, php has nothing to do with it, the dollar at the beginning of the variable name means that most likely it contains a jQuery collection.


Have you changed your script? Otherwise, in the example you have $_POST['img'] , but there should be $_FILES['img'] as I wrote above. It seems to me that it's too early for you to do such things, start with the basics of php, learn how to load the file without ajax, and then try to fasten it to the working code.

Scroll to Top