Upload image data via ajax

Asked

Viewed 1,542 times

7

<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 files (input[type=file]) by ajax for PHP.

  • Take a look at the file submission section with the FormData: https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects. O FormData belongs to the XMLHttpRequest 2 and the table of supported browser versions is here: http://caniuse.com/#feat=xhr2 (in particular IE8 and IE9 do not support).

1 answer

6


Taking advantage of the FormData already mentioned by @Wakim, and as you are using jQuery, just use $.ajax within your condition.

Example of $.ajax:

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

Browser other questions tagged

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