Edgar Serna
Edgar Serna

Reputation: 73

XML Parsing Error: no root element found Location

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

Upvotes: 4

Views: 34019

Answers (4)

Raj
Raj

Reputation: 747

I had same situation in Spring MVC Application as it was declared as void, changing it to return String solved the issue

@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";
}

Upvotes: 5

mike rodent
mike rodent

Reputation: 15652

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.

Upvotes: 9

Midimistro
Midimistro

Reputation: 325

Make sure you're php server is running and that the php code is in the appropriate folder. I ran into this same issue if the php was not there. I also recommend putting your html in that same folder to prevent cross-origin errors when testing.

If that is not the issue, ensure that every SQL call is correct in the php, and that you are using current php standards... Php changes quickly, unlike html, css and Javascript, so some functions may be deprecated.

Also, I noticed that you may not be collecting your variable correctly, which can also cause this error. If you are sending variables via form, they need to be in proper format and sent either by POST or GET, based on your preference. For example, if I had a login page for a maze game:

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 script 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();
?>

It would help if you included the other parts of the code such as the html and JavaScript as I wouldn't have to give my own example like this. However, I hope these pointers help!

Upvotes: 0

Yolo
Yolo

Reputation: 1579

Assuming you are working with javascript, you need to put a header in front of echoing your data:

header('Content-Type: application/json');
echo json_encode($response);

Upvotes: 0

Related Questions