Error trying to submit form with AJAX file

0

I have the following code that I deployed before testing in my project:

index.php

 <form method="post" id="formulario" enctype="multipart/form-data">
 <input name="nome" type="text"/>
 <input name="img" type="file"/>
 <button> Enviar</button>
 </form>

<script src="jquery.min.js"></script>
<script>
$(function()
{
    $('#formulario').submit(function(e)
    {
        var formData = new FormData(this);
        $.ajax(
        {
            url: "recebe.php",
            type: "POST",
            data: formData,
            success: function(result)
            {
                alert(result);
            }
        });     
        e.preventDefault();
    });
});
</script>

recib.php

<?php
foreach($_POST as $value)
{
    echo $value." - ";
}

foreach($_FILES['img'] as $value)
{
    echo $value." + ";
}

if (move_uploaded_file($_FILES['img']['tmp_name'],  'teste.jpg')) {
    echo "Sucesso";
}

The goal is to upload the image without having to reload the page. I've tried creating FormData and sending it by ajax , but alert of return is not even displayed. I do not know what the error is.

    
asked by anonymous 08.04.2016 / 20:07

2 answers

0

I was able to do this:

var dados = new FormData(this);

$.ajax(
{
    url: 'recebe.php',
    type: 'POST',
    data:  dados,
    mimeType:"multipart/form-data",
    contentType: false,
    cache: false,
    processData:false,
    success: function(data, textStatus, jqXHR)
    {
         alert(data);
    },
    error: function(jqXHR, textStatus, errorThrown) 
    {
        // Em caso de erro
    }          
});
    
08.04.2016 / 20:41
-1

The parameter is method, not type:

$.ajax(
        {
            url: "recebe.php",
            method: "POST",
            data: formData,
            success: function(result)
            {
                alert(result);
            }
        }); 
    
08.04.2016 / 20:16