Send data to upload images through ajax

6
<script type="text/javascript">
$(function(){
    $("#oformulario").submit(function(e){
        e.preventDefault();

        var nome    = $("#nome").val();
        var email   = $("#email").val();
        var obs     = $("#obs").val();
        var file0   = $("#file0").val();
        var file1   = $("#file1").val();

        if( (nome == "" || nome == null) || 
            (email == "" || email == null) ||   
            (file0 == "" || file0 == null) ){

            alert("Preencha todos os campos obrigatórios.");
            return false;

        } else {

            // Ajax

        }

    });
});
</script>

I want to send # file0 and # file1 which are (input[type=file]) files through ajax to PHP.

    
asked by anonymous 20.08.2014 / 23:54

1 answer

5

Taking advantage of the FormData already mentioned by @Wakim, and since you're using jQuery, you only have to use $.ajax within your condition.

$ .ajax example:

var dados = new FormData(this);
var url = "url/para/postUpload.php";
$.ajax({
    url: url,
    type: 'POST',
    data:  dados,
    mimeType:"multipart/form-data",
    contentType: false,
    cache: false,
    processData:false,
    success: function(data, textStatus, jqXHR)
        {
             // Em caso de sucesso faz isto...
        },
    error: function(jqXHR, textStatus, errorThrown) 
        {
            // Em caso de erro
        }          
    });
    
21.08.2014 / 02:08