0

I was trying to make a web app. but I don't want to use jquery for ajax. Here's the jquery implementation of this.


    $('#btn-predict').click(function () {
            var form_data = new FormData($('#upload-file')[0]);
    
            // Show loading animation
            $(this).hide();
            $('.loader').show();
    
            // Make prediction by calling api /predict
            $.ajax({
                type: 'POST',
                url: '/predict',
                data: form_data,
                contentType: false,
                cache: false,
                processData: false,
                async: true,
                success: function (data) {
                    // Get and display the result
                    $('.loader').hide();
                    $('#result').fadeIn(600);
                    $('#result').text(' Result:  ' + data);
                    console.log('Result:  ' + data);
                },
            });
        });

I want to convert this into vanilla javascript. So, I have tried this..

var btnPredict = document.getElementById('btn-predict')
    btnPredict .addEventListener('click', function (){

        var formData = new FormData(document.getElementById('upload-file'))

        // Show loading animation
        var btn = document.getElementById('btn-predict')
        btn.style.display = 'none'

        var loader = document.querySelector('.loader')
        loader.style.display = 'block'

        // Make prediction by calling api /predict
        var r = new XMLHttpRequest();
        r.open("POST", "/predict",  true);
        r.onreadystatechange = function (data) {
            if (r.readyState != 4 || r.status != 200){
                // Get and display the result
                var loader = document.querySelector('.loader')
                loader.style.display = 'none'
                var result = document.querySelector('#result')
                fadeIn(result,600)   // fadeIn is defined below 
                result.textContent = 'Result: '+ data
                console.log('Result: '+ data)
            }
        }
        r.send(formData)
    })

But this gives me Result : [Object Event] What's wrong in my code? What is the javascript equivalent of

        contentType: false,
        cache: false,
        processData: false
Saihan
  • 1
  • 2

0 Answers0