FormData () object for sending files via ajax Jquery

3

I need to send data from a form via ajax to the server (php). I used the FormData () object but without success. Part of my jquery:

var formdata = new FormData($("#myform"));
var link = "form/insert";
        $.ajax({
            type: 'POST',
            url: link,
            data: formdata ,
            processData: false,
            contentType: false

        }).done(function (data) {
            $("div.container-fluid").html(data);
        });

My html has:

<input type="text" class="form-control" id="name" placeholder="name" name="name">
 <input type="file" id="arquivo" name="arquivo" />

Running the script only returns null. I would like to send via ajax the input text and the file?

    
asked by anonymous 27.10.2015 / 00:08

1 answer

8

When retrieving the form, it may be that a vector is returned, so take the key 0 (if there is only one).

  

Note: Verify that the form enctype is multipart / form-data

//Exemplo do JS
var formdata = new FormData($("form[name='nome_do_form']")[0]);
var link = "form/insert";
    $.ajax({
        type: 'POST',
        url: link,
        data: formdata ,
        processData: false,
        contentType: false

    }).done(function (data) {
        $("div.container-fluid").html(data);
    });

HTML example:

<form name="nome_do_form" enctype="multipart/form-data">
     <input type="text" class="form-control" id="name" placeholder="name" name="name">
     <input type="file" id="arquivo" name="arquivo" />
     <input type="submit" />
</form>

PHP example:

<?php

echo "Texto: " . $_POST['name'] . '<br/><br/>';

if (move_uploaded_file($_FILES['arquivo']['tmp_name'], __DIR__."/upload_".date('YmdHis')."_".$_FILES['arquivo']['name'])) {
        echo "Arquivo recebido {$_FILES['arquivo']['name']} - o seu tamanho é de  {$_FILES['arquivo']['size']}";
} else {
        echo "Falha ao fazer upload!";
}
    
27.10.2015 / 02:51