The problem:
I was unable to find any resources online regarding changing elements before and after an ajax request. If I have a <p>
element with id="myText"
, if I want to change the innerHTML
of that element before the AJAX
request, and after, this is not possible.
I essentially want to change the text of #myText
to "loading…" on click of the button, then run my AJAX
request, and within that request, on success it changes that elements text from "loading…", to data
, which works. However, the "loading…" does not show.
When I check devTools, I can see that the innerHTML is indeed changing to "Loading…", but it just does not show. If I remove the AJAX
request, the element successfully changes to "loading…"
$(function() {
$('#uploadBtn').click(function() {
document.getElementById('myText').innerHTML = 'loading...'
var form_data = new FormData($('#myForm')[0]);
$.ajax({
type: 'POST',
url: '/flaskFunction',
data: form_data,
contentType: false,
cache: false,
processData: false,
async: false,
success: function(data) {
document.getElementById('myText').innerHTML = data
}
});
});
});
3
Answers
How about this, just set the value on click and if there is an error show it or just clear the element.
If an element with id "textArea" is an actual
textarea
tag then you can’t set the content of it with innerHTML. You need to use value, like any form control.I actually can’t get your example to NOT work 😄 Is it possible that the text is actually changing, but the request executes so quickly that you just don’t see it on the screen? If you can see the change in devtools, it should be happening. Try this in your
success()
function to wait 2 seconds before changing the text from'loading...'
todata
: