Send image with Ajax

2

How can I send an image through ajax?

The code I have is this and for now it only sends text, how could I take the image of <input type="file" id="foto"/> and send it?

My code:

function updateProfile(){
    var name = $("#name").val();
    var lastname = $("#lastname").val();
    var email = $("#email").val();
    var phone = $("#phone").val();
    $("#form-updateProfile").submit(function(){
        var profileData = {
            name : name,
            lastname : lastname,
            email : email,
            phone : phone
        }
        $.post('php/db_updateProfile.php', profileData, returnValues);
        return false;
    });
    function returnValues(recievedData){
        console.log(recievedData);
    }
}
    
asked by gmarsi 03.12.2017 в 22:23
source

1 answer

3

Try adding enctype="multipart / form-data" in the form html element. I think it would be easier if you serialize it in the following way since you use jquery: $('form').serialize(); with that you serialize the whole form with the values.

The html would look like this:

<form enctype="multipart/form-data" id="form">
    <input type="file" id="myFile" name="miImagen">
    <button type="submit">Enviar</button>
</form>

The JavaScript would be the following:

 $("#form").on('submit',function(){
      $.post('php/db_updateProfile.php', $('#form').serialize(), returnValues);
 });

I continued with your code to give you an example ...

    
answered by 03.12.2017 в 23:23