0

I'm trying to send a Json object to PHP, but when I run the PHP code it doesn't receive anything. I get the Json from transforming an excel file into Json and from there I want to send it to PHP to process it and save it in the database. The problem is that the Network does not send me anything:

below my code:

//this code is to convert excel file in json
let selectedFile;

document.getElementById('importBUDid').addEventListener('change', (event)=>{
    selectedFile = event.target.files[0];
});

document.getElementById('uploadBud').addEventListener('click', ()=>{
    let jsonObj;
    if (selectedFile) {
        let fileReader = new FileReader();
        fileReader.readAsBinaryString(selectedFile);
        fileReader.onload = (event)=>{
            //console.log(event.target.result);
            let dato = event.target.result;
            let workbook = XLSX.read(dato, {type:"binary"});
            //console.log(workbook.Strings);
            workbook.SheetNames.forEach(sheet => {
                let rowObject = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheet]);
                //console.log(rowObject);
                jsonObj = rowObject;
            });
            //console.log(jsonObj);
            testBud(jsonObj);
            
        }
    }
    
}); 
//this code is to send the json object to PHP
function testBud(dt1){
    const dt = JSON.stringify(dt1)
    //console.log(dt);


    const data = new FormData();
    const jsonBlob = new Blob([dt], {type: "application/json"});
    data.append("data", jsonBlob);
    //console.log(data.data);
    console.log(data.data);
    fetch("model/importBud.php", {
    method: "POST",
    body: data.data,
    /* headers:{
      'Content-Type': 'application/json'
        }, */
    }).then(resp => {
    if(!resp.ok) {
        const err = new Error("Response wasn't okay");
        err.resp = resp;
        throw err;
    }
    console.log(resp);
    }).catch(err => {
    console.error(err);
    });
}

PHP below

$obj = $_POST['data'];

if ($obj != "") {
    echo "lleno";
}else{
    echo "vacío";
}
madison_sg
  • 11
  • 1
  • 1
    welcome to stackoverflow, it's always best to search around for what you are looking to do. Here's an example https://stackoverflow.com/questions/29775797/fetch-post-json-data – mcgraphix Jun 15 '22 at 21:11

1 Answers1

0

Try moving the php file into a Public folder, and then do the fetch call like this:

fetch("./public/model/importBud.php", {method: "POST", [...]);
Javi Martínez
  • 368
  • 1
  • 4
  • 16