javascript - "XML Parsing Error: no root element found"
Get the solution ↓↓↓I'm testing some code to be able to upload mp3-files and have them stored on the website. I've followed some tutorials on how to do this with JS and PHP, but I always get the error (in firefox):
XML Parsing Error: no root element found
Location: https://filesavetest.jasperdg.repl.co/ajaxfile.php
Line Number 29, Column 3:
Can someone help me?
Here's my HTML:
<html>
<head>
<title>JSFileSaveTest</title>
</head>
<body>
<div >
<input type="file" name="file" id="file">
<input type="button" id="btn_uploadfile"
value="Upload"
onclick="uploadFile();" >
</div>
<script type="text/javascript">
function uploadFile(){
var files = document.getElementById("file").files;
if(files.length>0){
var formdata = new FormData();
formdata.append("file", files[0])
var xhttp = new XMLHttpRequest();
//Set POST method and ajax file path
xhttp.open("POST", "ajaxfile.php", true)
//Call on request changes state
xhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
var response = this.responseText;
if(response==1){
alert("upload suc6")
}else{
alert("file not uploaded")
}
}
}
//Send request with data
xhttp.send(formdata)
}else{
alert("Please select a file")
}
}
</script>
</body>
</html>
And here's my PHP:
<?php
if(isset($_FILES["file"]["name"])){
//Filename
$filename = $_FILES["file"]["name"];
//Upload location
$dir = "upload/";
//File path
$path = $dir.$filename;
//File extension
$file_extension = pathinfo($path, PATHINFO_EXTENSION);
$file_extension = strtolower($file_extension);
//Valid extensions
$valid_ext = array("mp3");
$response = 0;
//Check extension
if(in_array($file_extension, $valid_ext)){
//Upload file
if(move_uploaded_file($_FILES["file"]["tmp_name"], $path)){
$response=1;
}
}
echo $response;
exit;
}
?>
And here's my file structure:
[![enter image description here][1]][1]
Tnx! [1]: https://i.stack.imgur.com/DD3Om.png
Answer
Solution:
If the server doesn't provide a Content-Type header, XMLHttpRequest assumes that the MIME type is "text/xml". You can avoid this by calling overrideMimeType() to specify a different type.
Don't know exactly but it seems to me that the correct mime type for MP3 is audio/mpeg or application/octet-stream.
Try to set mimeType before xhttp.open, with:
xhttp.overrideMimeType("audio/mpeg");
Or
xhttp.overrideMimeType("application/octet-stream");
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: trying to access array offset on value of type bool in
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.