How to send Images via AJAX to php

Asked

Viewed 3,888 times

3

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

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

Somebody could help me?

1 answer

4

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

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

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

$.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.

There’s a cool example for you to draw from here: https://www.formget.com/ajax-image-upload-php/

  • 1

    Before answering use search http://answall.com/search?q=%5Bajax%5D+upload

  • 1

    True, I already had the answer, thank you @Guilhermenascimento

Browser other questions tagged

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