Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

63
Views
Empty form when uploading a PDF file with XHR

I've got a function to get a file type input, and upload the selected file using xhr, the problem it's working fine with images, but once I'm trying to upload a pdf file the js function

function uploadFile() {
const files = document.getElementById("file").files;

if(files.length > 0 ){
    const formData = new FormData();
    formData.append("file", files[0]);
    formData.append('__csrf', document.getElementById('csrf_profile').value);

    const xhr = new XMLHttpRequest();

    // Set POST method and ajax file path
    xhr.open("POST", "/api/user/background", true);

    // call on request changes state
    xhr.onreadystatechange = function() {
        if (this.readyState === 4) {
            const response = JSON.parse(this.responseText);
            if(response.status === true){
                document.getElementById('message').innerText = 'cover image has been updated';
                document.getElementById('message').style.color = 'var(--main-colo)';
                reloadPage();
            }else{
                document.getElementById('message').innerText = response.message;
                document.getElementById('message').style.color = '#F00';
            }
        }
    };

    // Send request with data
    xhr.send(formData);

}else{
    document.getElementById('message').innerText = "Please select a file";
    document.getElementById('message').style.color = '#F00';
}
}

in my PHP handler I'm debugging using

die(print_r($_POST,true));

if it's an image I get Array ( [__csrf] => token ) if it's a pdf I get Array ( ) this is what I couldn't understand what exactly am I doing wrong here

7 months ago ยท Juan Pablo Isaza
Answer question
Find remote jobs