I’ve encountered this problem, and I couldn’t figure it out. I’m using ASP.NET Core 2 and Ajax.
This is what the JavaScript debugger says:
XML Parsing Error: no root element found Location:
http://localhost:52617/api/favorites/ Line Number 1, Column 1:
This is my JavaScript code:
$(".js-toggle-fav").click(function (e) {
function sendPost() {
console.log("inside post send");
var button = $(e.target);
$.ajax({
type: 'POST',
url: "http://localhost:52617/api/Favorites/",
data: {"EventId": @Model.Event.EventId},
contentType: "application/json; charset=utf-8"
});
}
$.getJSON("http://localhost:52617/api/favorites/@Model.Event.EventId", function (data) {
if (data == null) {
console.log("fav is null");
sendPost();
fav.addClass(toggling);
fav.text("unfav");
}
else {
console.log("fav is NOT null");
sendPost();
fav.removeClass(toggling);
fav.text("fav");
}
);
});
And my API:
[HttpPost]
public async Task<IActionResult> PostFavorite([FromBody] FavoriteDto favorite)
{
if (!ModelState.IsValid)
{
Console.WriteLine(ModelState.ValidationState.ToString());
return BadRequest(ModelState);
}
var uid = _userManager.GetUserId(HttpContext.User);
var fav = await _context.Favourites.SingleOrDefaultAsync(x => x.EventId == favorite.EventId && x.UserId == uid);
if (fav == null)
{
_context.Favourites.Add(new Favorite { EventId = favorite.EventId, UserId=uid });
}
else
{
_context.Favourites.Remove(fav);
}
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateException)
{
if (FavoriteExists(favorite.EventId))
{
return new StatusCodeResult(StatusCodes.Status409Conflict);
}
else
{
throw;
}
}
return Ok(favorite);
}
When I do this with Postman or any restclient, everything works like a charm! With Ajax, that’s not the case.
NOTES:
- In the same
.cshtmlfile, there’s more jQuery and JavaScript code which does something like this, and it’s just working! All the solutions
I’ve checked on the internet didn’t work, unfortunately.- The Get methods (for returning List, or single element are working!)
Вопрос:
Итак, я делаю простое веб-приложение для входа/регистрации, но я продолжаю получать следующую ошибку:
XML Parsing Error: no root element found Location: file:///C:/xampp/htdocs/EdgarSerna95_Lab/login.html Line Number 37, Column 3:
и
XML Parsing Error: no root element found Location: file:///C:/xampp/htdocs/EdgarSerna95_Lab/php/login.phpLine Number 37, Column 3:
вот мой login.php
<?php
header('Content-type: application/json');
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "jammer";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
header('HTTP/1.1 500 Bad connection to Database');
die("The server is down, we couldn't establish the DB connection");
}
else {
$conn ->set_charset('utf8_general_ci');
$userName = $_POST['username'];
$userPassword = $_POST['userPassword'];
$sql = "SELECT username, firstName, lastName FROM users WHERE username = '$userName' AND password = '$userPassword'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$response = array('firstName' => $row['firstNameName'], 'lastName' => $row['lastName']);
}
echo json_encode($response);
}
else {
header('HTTP/1.1 406 User not found');
die("Wrong credentials provided!");
}
}
$conn->close();
?>
Я провел некоторое исследование об ошибках синтаксического анализа xml, но мне все еще не удается заставить работать мой проект, и попытался с Google Chrome и Firefox.
Ответ №1
AHA! Получил это сегодня по той причине, которая заставит меня выглядеть довольно глупо, но которая может когда-нибудь помочь кому-то.
Установив сервер Apache на моем компьютере, с PHP и так далее… Я получил эту ошибку… и затем понял, почему: я нажал на файл HTML, о котором идет речь (то есть тот, который содержит Javascript/JQuery), поэтому адресная строка в браузере показывала “файл:///D:/apps/Apache24/htdocs/experiments/forms/index.html”.
Что вам нужно сделать, чтобы на самом деле использовать сервер Apache (при условии, что он запущен и т.д.) – go “ http://localhost/experiments/forms/index.html” в адресной строке браузера.
В смягчении я до сих пор использовал файл index.php и просто изменил файл “index.html”. Бит получателя, поскольку с первым вы обязаны получить доступ к нему “правильно” с помощью localhost.
Ответ №2
У меня была такая же ситуация в Spring MVC Application, поскольку она была объявлена как void, изменив ее, чтобы вернуть String, решив проблему
@PostMapping()
public void aPostMethod(@RequestBody( required = false) String body) throws IOException {
System.out.println("DoSome thing" + body);
}
To
@PostMapping()
public String aPostMethod(@RequestBody( required = false) String body) throws IOException {
System.out.println("DoSome thing" + body);
return "justReturn something";
}
Ответ №3
Предполагая, что вы работаете с javascript, вам нужно поставить заголовок перед эхом ваших данных:
header('Content-Type: application/json');
echo json_encode($response);
Ответ №4
Убедитесь, что вы используете php-сервер и что php-код находится в соответствующей папке. Я столкнулся с этой проблемой, если php не был там. Я также рекомендую поместить ваш html в ту же папку, чтобы предотвратить ошибки при перекрестном происхождении при тестировании.
Если это не проблема, убедитесь, что каждый SQL-запрос корректен в php и что вы используете текущие стандарты php… Php быстро меняется, в отличие от html, css и Javascript, поэтому некоторые функции могут быть устаревшими.
Кроме того, я заметил, что вы не можете правильно собирать свою переменную, что также может вызвать эту ошибку. Если вы отправляете переменные через форму, они должны быть в правильном формате и отправляться либо POST, либо GET, исходя из ваших предпочтений. Например, если у меня была страница входа в лабиринт:
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<form class="modal-content animate" method="post">
<div class="container">
<label><b>Username</b></label>
<input type="text" id="usernameinput" placeholder="Enter username" name="uname" required>
<label><b>Password</b></label>
<input type="password" id="passwordinput" placeholder="Enter Password" name="psw" required>
<button onclick="document.getElementById('id01').style.display='block'">Sign Up</button>
<button type="button" id="loginsubmit" onclick="myLogin(document.getElementById('usernameinput').value, document.getElementById('passwordinput').value)">Login</button>
</div>
</form>
JavaScript
function myLogin(username, password){
var datasend=("user="+username+"&pwd="+password);
$.ajax({
url: 'makeUserEntry.php',
type: 'POST',
data: datasend,
success: function(response, status) {
if(response=="Username or Password did not match"){
alert("Username or Password did not match");
}
if(response=="Connection Failure"){
alert("Connection Failure");
}
else{
localStorage.userid = response;
window.location.href = "./maze.html"
}
},
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "nError:" + err);
var response = xhr.responseText;
console.log(response);
var statusMessage = xhr.status + ' ' + xhr.statusText;
var message = 'Query failed, PHP скрипт returned this status: ';
var message = message + statusMessage + ' response: ' + response;
alert(message);
}
}); // end ajax call
}
PHP
<?php
$MazeUser=$_POST['user'];
$MazePass=$_POST['pwd'];
//Connect to DB
$servername="127.0.0.1";
$username="root";
$password="password";
$dbname="infinitymaze";
//Create Connection
$conn = new MySQLi($servername, $username, $password, $dbname);
//Check connetion
if ($conn->connect_error){
die("Connection Failed: " . $conn->connect_error);
echo json_encode("Connection Failure");
}
$verifyUPmatchSQL=("SELECT * FROM mazeusers WHERE username LIKE '$MazeUser' and password LIKE '$MazePass'");
$result = $conn->query($verifyUPmatchSQL);
$num_rows = $result->num_rows;
if($num_rows>0){
$userIDSQL =("SELECT mazeuserid FROM mazeusers WHERE username LIKE '$MazeUser' and password LIKE '$MazePass'");
$userID = $conn->query($userIDSQL);
echo json_encode($userID);
}
else{
echo json_encode("Username or Password did not match");
}
$conn->close();
?>
Это помогло бы, если бы вы включили другие части кода, такие как html и JavaScript, поскольку мне не пришлось бы приводить мой собственный пример. Однако я надеюсь, что эти указатели помогут!
- Remove From My Forums
-
Question
-
Hello All,
I am getting the following error when I open the CA. However I am able to open the sites that I created using CA.
Hope my word are clear enough.
Thank U
Thanks & Regards, Chandra Shekhar Rameneni
Answers
-
Hi Chandra,
Based on my research, the error message is only generated by FireFox when the render page is blank in Internet. For some reason, .NET generates a response type of «application/xml» when it creates an empty page. Firefox parses the file as XML and finding
no root element, spits out the error message.
Also, based on your description, the other sites are opened correctly, the issue only happened in Central Administration(CA). This means the SharePoint services are working fine.Since this issue only occurred in the CA, it might be due the application pool for the CA is corrupted. Please try to restart the application pool for the CA to resove the issue:
1. Open Internet Information Service(IIS)
2. List the application pools
3. Select the application pool used for the CA
4. Stop it, and then start it again.Note, if the application pool is running in Classic mode, please change it to be Integrated mode.
Additionally, I found a similar thread, which may help you too:
http://social.msdn.microsoft.com/Forums/en/sharepoint2010general/thread/824d7dda-db03-452b-99c4-531c5c576396If you have any more questions, please feel free to ask.
Thanks,
Jin Chen
Jin Chen — MSFT
-
Marked as answer by
Monday, March 14, 2011 2:44 AM
-
Marked as answer by
So I’m making a simple login/registration web application but I keep getting the following error:
XML Parsing Error: no root element found Location: file:///C:/xampp/htdocs/EdgarSerna95_Lab/login.html Line Number 37, Column 3:
and
XML Parsing Error: no root element found Location: file:///C:/xampp/htdocs/EdgarSerna95_Lab/php/login.phpLine Number 37, Column 3:
here is my login.php
<?php
header('Content-type: application/json');
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "jammer";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
header('HTTP/1.1 500 Bad connection to Database');
die("The server is down, we couldn't establish the DB connection");
}
else {
$conn ->set_charset('utf8_general_ci');
$userName = $_POST['username'];
$userPassword = $_POST['userPassword'];
$sql = "SELECT username, firstName, lastName FROM users WHERE username = '$userName' AND password = '$userPassword'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$response = array('firstName' => $row['firstNameName'], 'lastName' => $row['lastName']);
}
echo json_encode($response);
}
else {
header('HTTP/1.1 406 User not found');
die("Wrong credentials provided!");
}
}
$conn->close();
?>
I’ve done some research about xml parsing errors but I still cant manage to make my project work, ive tried with Google Chrome and Firefox
AHA! Got this today for a reason which will make me look pretty silly but which might one day help someone.
Having set up an Apache server on my machine, with PHP and so on… I got this error… and then realised why: I had clicked on the HTML file in question (i.e. the one containing the Javascript/JQuery), so the address bar in the browser showed «file:///D:/apps/Apache24/htdocs/experiments/forms/index.html».
What you have to do to actually use the Apache server (assuming it’s running, etc.) is go «http://localhost/experiments/forms/index.html» in the browser’s address bar.
In mitigation I have up to now been using an «index.php» file and just changed to an «index.html» file. Bit of a gotcha, since with the former you are obliged to access it «properly» using localhost.
391 votes
1 answers


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
2021-09-22
Write your answer
579
votes


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:
Date the issue was resolved:
2021-09-22
Link To Source
Link To Answer
People are also looking for solutions of the problem: object of class stdclass could not be converted to string
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.
Forum Rules |
|




