upload without refresh with FormData, jquery

10

I need to update my script and I want to adapt my upload forms to be upados without the need to refresh. I did not use the script for third-party scripts so I searched and found this function of jQuery FormData .

I did not really understand what I read so I came here to ask for a support ...

How to send files to the server (PHP) using Ajax and FormData?

Thank you.

    
asked by anonymous 09.12.2014 / 18:03

1 answer

7

I use jQuery , without plugin, to be able to upload files.

I'll illustrate in a very simplified way:

index.php

<script src="jquery.js"></script>

<script>
$(function()
{
    $('form').submit(function(e)
    {
        e.preventDefault();

        var formData = new FormData();

        formData.append('image', $('#file').prop('files')[0]);

          $.ajax({
            url: 'upload.php',
            data: formData,
            type: 'post',
            success: function(response)
            {
                console.log(response)
            },
            processData: false,
            cache: false,
            contentType: false
          });
    });
});
</script>

<form method="post" enctype="multipart/form-data">
    <input type="file" id="file" />
    <input type="submit" />
</form>

upload.php

if (move_uploaded_file($_FILES['image']['tmp_name'], $novo_nome)) {
     echo json_encode($_FILES);
}

You need to send the data via post by Ajax and, in the form, set it to enctype="multipart / form-data"     

09.12.2014 / 20:05