Each time I make an ajax call, my page reloads, and I've attempted the following actions:
Changing the button type to button
Using event.preventDefault()
Also attempted event.stopPropagation();
Below is a snippet of my app.js:
$(document).ready(() => {
$('#importImg').click(function (event) {
event.preventDefault();
event.stopPropagation();
if ($('#image')[0].files[0] != null) {
$('#loading')[0].style.display = '';
var file = $('#image')[0].files[0];
var formData = new FormData();
formData.append('file', file);
console.log(formData);
$.ajax({
url: 'http://127.0.0.1:8000/upload',
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: (data) => {
var div = document.getElementById("content");
var image = document.createElement("img");
image.src = data;
image.setAttribute("class", "img-site");
div.appendChild(image);
$('#loading')[0].style.display = 'none';
},
error: (jqXHR, textStatus, errorThrown) => {
console.log(jqXHR);
$('#loading')[0].style.display = 'none';
}
})
} else {
alert('Choose a file first!');
}
})
})
Here is a glimpse of my html:
<div class="addimg" style="margin-top: 5rem;">
<input type="file" class="btn btn-primary" name="image" id="image">
<button id="importImg" class="btn btn-danger">Upload</button><span><img style="width: 25px; margin-left: 5px; display: none" id="loading" src="200.gif" alt=""></span>
</div>
Any help or advice would be highly appreciated. Thank you in advance!