How to send Images via AJAX to php

3

Good afternoon, I would like to ask for your help. Home I have a system where I need to send an Image of a <input type="file>" to a PHP page via $.ajax() to it, I can upload this image to a sufficient one, while I take the path and store it in the bank via $_pdo . I did an extensive search on the internet and found several websites teaching to do, but I did not understand, the only things I understood was that I should use a command called formData() and pass some parameters in $.ajax() . But I did not understand:

  • how to use formData()
  • what parameters should I pass in $.ajax()
  • If I can pass other types of information along with the image
  • How can I store the value of an image in a <elemento hidden> and bring this information to $.ajax()

Can someone help me?

    
asked by anonymous 03.12.2016 / 18:48

1 answer

3

You need to create a FormData object with input of the image you want to upload:

var fd = new FormData();
fd.append('file', $('#inputFile"));

Then, make the ajax call "POST" by passing FormData as the "date" parameter.

$.ajax({
    url: 'http://dominio/pagina.php',
    data: fd,
    processData: false,
    contentType: false,
    type: 'POST',
    success: function(data) {
        alert(data);
    }
});

On your php page, you can use $_FILES to receive the file.

Yes, you can pass other data. the FormData is dictionary of type key / value, only add other elements and values doing append .

You have a nice example if you are based here: link

    
04.12.2016 / 15:37