0
I’m developing a form that can receive multiple images in a file Multiple input field. The method I am using converts these images to Base64, and so sends them via POST to an Hidden input with the value of Base64. However, I’m encountering some problems with ajax and fileReader.
Here follow the codes:
function converte() {
const imagens = document.getElementById('passeio_imagens').files;
var x = 0;
for (var i = 0; i < imagens.length; i++) {
const reader = new FileReader()
reader.readAsDataURL(imagens[i]);
reader.onload = () => {
$('#form-cadastrar-passeio').append('<input name="imagem' + x + '" type="hidden" value="' + reader.result + '">')
x++
}
}
}
$('#form-cadastrar-passeio').validate({
rules: {
nome: 'required',
preco: 'required',
duracao: 'required',
tipo: 'required',
descricao: 'required',
endereco: 'required',
longitude: 'required',
latitude: 'required'
},
submitHandler: (form) => {
converte()
$.ajax({
url: form.action,
type: form.method,
data: $(form).serialize(),
success: (response) => {
console.log(response)
const jsonObject = JSON.parse(response)
alert(jsonObject.message)
if (jsonObject.code === 200) {
location.href = '../'
}
},
error: (message) => {
alert('Erro ao inserir dados: ' + message)
}
})
}
}
})
The problem I’m having is when the POST comes to PHP, the picture fields, image1... are not received. I suspect it is because the Reader.onload is not finished until the ajax is executed. Would you have some way to ensure that the multiple image Reader.onload ends before running ajax?