Home > Blockchain >  Change innerhtml of element before AJAX request
Change innerhtml of element before AJAX request

Time:06-22

I am using an ajax request, on the submit of a form to run a flask function. This is all working well. However, I am also trying to change the INNERHTML of an element before the ajax request is sent. To do so, I tried to use beforeSend as per below. However, this does not work, the text does not change until the success function happens.

$(function() {
    $('#upload-file-btn2').click(function() {
        var form_data = new FormData($('#myForm')[0]);
        $.ajax({
            type: 'POST',
            url: '/flaskFunction',
            data: form_data,
            contentType: false,
            cache: false,
            processData: false,
            async: false,
            beforeSend: function() {
              document.getElementById('textArea').innerHTML = 'loading...'
            },
            success: function(data) {
                document.getElementById('textArea').innerHTML = data
            },
        });
    });
});

CodePudding user response:

How about this, just set the value on click and if there is an error show it or just clear the element.

$(function() {
    $('#upload-file-btn2').click(function() {
        var form_data = new FormData($('#myForm')[0]);
        document.getElementById('textArea').innerHTML = 'loading...';
        $.ajax({
            type: 'POST',
            url: '/flaskFunction',
            data: form_data,
            contentType: false,
            cache: false,
            processData: false,
            async: false,
            beforeSend: function() {
            },
            success: function(data) {
                document.getElementById('textArea').innerHTML = data
            },
            error: function(data) {
            
                document.getElementById('textArea').innerHTML = "failed"
           }
        });
    });
});

CodePudding user response:

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.

document.getElementById('textArea').value = 'loading...'
  • Related