Error trying to submit form with AJAX file

Asked

Viewed 102 times

0

I have the following code I implemented for testing before putting 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>

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 tried creating a FormData and sending him by ajax, but the alert return is even displayed. I don’t know what the error is.

2 answers

0


I got it this way:

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
    }          
});

-1

Parameter is method, not type:

$.ajax(
        {
            url: "recebe.php",
            method: "POST",
            data: formData,
            success: function(result)
            {
                alert(result);
            }
        }); 
  • In AJAX use type to inform the type of the form. This is not the error.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.