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.
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";
}
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);
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!
Related
I having written a php script which makes an SQL query and fetches a list of unique names from the database.
I am making an AJAX GET request using jQuery to the php script. When I check resources in the console I see that the php script is being called, and when I check the response it contains a list of unique names.
However, the jquery GET request is failing, and is displaying an error message in the console.
It may be easier and clearer to look at my code, as I have no idea what is the issue here. Please see code below.
php
<?php
header('Content-Type: application/json');
$servername = "****";
$username = "****";
$password = "****";
$dbname = "****";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT DISTINCT(name) FROM customer";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo json_encode(array('customer' => $row["name"]));
}
} else {
echo "0 results";
}
$conn->close();
?>
JS
$.ajax({
type: 'GET',
url: 'getcustomers.php',
success: function(data){
console.log(data);
},
error: function() {
console.log('error');
}
});
In the console it simply says error, meaning it has executed the error function.
When I load the php file in the browser it displays the following.
{"name":"Peter"}{"name":"Alan"}{"name":"Mike"}
Your JSON response is not a valid one. You are printing each data row on each iteration. So replace the while statement with this one,
if ($result->num_rows > 0) {
$return = array();
while($row = $result->fetch_assoc()) {
$return[] = array('customer' => $row["name"]);
}
echo json_encode($return);
} else {
echo "0 results";
}
Considering your script returns any result (I hope you've tried running it in broswer) then you can use something like this:
$.get('path/to/file/filename.php').done(function(response) {
$('#exampleDiv').html(response);
});
Although, common errors because you must specify the directory path if the php file you're requesting is outside the current working directory.
change your error handler function header to the following:
error: function (jqXHR, textStatus, errorThrown) {
then print that and see what the error is
you are echoing json_encode string in side while loop, instead of that you will have to push row in an array and at the end you can echo json string only once.
$outputArr = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
array_push(outputArr ,array('customer' => $row["name"]));
}
} else {
echo "0 results";
}
echo json_encode($outputArr);
I've been at this for quite a while now, and I have pretty much no experience with PHP and I've only begun with JavaScript.
I'm attempting to run a PHP script that I have on my server from the JavaScript on the webpage using AJAX. To be honest, I don't really have much of an idea of what I'm doing.
My current code:
JS:
function Write() {
$.ajax({
type: "POST",
url: "Write.php",
data: {
'GUID': "12345678987654321",
'IP': "127.0.0.2",
'USERNAME': "George",
'BAN_REASON': "Broke my pencil."
},
success: function(data) {
console.log(data);
}
});
}
PHP:
<?php
exec("java -jar Database.jar '.$_POST['GUID']' '.$_POST['IP']' '.$_POST['USERNAME']' '.$_POST['BAN_REASON']'");
?>
(I'm also not too entirely sure that I did that String correctly, so help on that would be appreciated)
Basically, that PHP code is using a Java program I made to write to a MySQL database using the arguments that are being sent by the PHP "exec()." It's not writing to the database at all, so I'm assuming it's something with the AJAX going to the PHP function.
When "Write()" is ran, all it does is print out the PHP code to the console...
NEW CODE
<?php
//Server
$servername = "localhost";
$dbusername = $_POST['DB_USERNAME'];
$password = $_POST['DB_PASSWORD'];
$dbname = "bansdb";
$username = $_POST['USERNAME'];
$guid = $_POST['GUID'];
$ip = $_POST['IP'];
$ban_reason = $_POST['BAN_REASON'];
$connection = new mysqli($servername, $dbusername, $password, $dbname);
if ($connection->connect_error) {
die("Connection Failed: " . $connection->connect_error);
}
$sql = "INSERT INTO bans (GUID, IP, USERNAME, BAN_REASON)
VALUES ('$guid', '$ip', '$username', '$ban_reason')";
if (mysqli_query($connection, $sql)) {
echo "Ban successfully added.";
} else {
echo "Error: " . $sql . mysqli_error($connection);
}
mysqli_close($connection);
?>
I would not pass your DB user/password over the network. Just make a simple application password and store the password statically in the PHP with the db user/password (in HTML modify form to have APP_PASSWORD input). With parameterized queries aside from closing SQL injection you also can have single quotes in your value and don't have to worry about the query breaking (the driver handles the quoting).
<?php
//Server
$servername = "localhost";
$dbusername = 'static_db_user';//$_POST['DB_USERNAME'];
$password = 'staticpassword';//$_POST['DB_PASSWORD'];
$dbname = "bansdb";
if($_POST['APP_PASSWORD'] != 'Some generic password') {
die('Invalid Credentials');
}
$username = $_POST['USERNAME'];
$guid = $_POST['GUID'];
$ip = $_POST['IP']; // I would store IP as an unsigned int, ip2long
$ban_reason = $_POST['BAN_REASON'];
$connection = new mysqli($servername, $dbusername, $password, $dbname);
if ($connection->connect_error) {
die("Connection Failed: " . $connection->connect_error);
}
$sql = "INSERT INTO bans (GUID, IP, USERNAME, BAN_REASON)
VALUES (?,?,?,?)";
if ($stmt = mysqli_prepare($connection, $sql)) {
mysqli_stmt_bind_param($stmt, , 'ssss', $guid, $ip, $username, $ban_reason;
if(mysqli_stmt_execute($stmt)) {
echo "Ban successfully added.";
} else {
echo "Execute Error: " . $sql . mysqli_error($connection);
}
} else {
echo "Prepare Error: " . $sql . mysqli_error($connection);
}
mysqli_close($connection);
?>
all it does is print out the PHP code to the console...
Do you have a web server that's configured to execute PHP code? You must realize that you cannot just run a plain php file in your browser opened from the filesystem on your "server".
Make a new file called info.php and save it to your web server. Inside it should only be this:
<?php
phpinfo();
If you see that code when you browse to it, then you do not have PHP enabled. Otherwise, you will see a lot of information about your configuration.
not too entirely sure that I did that String correctly
pretty close, but you should read up about some quotes
this might work for you:
<?php
exec("java -jar Database.jar $_POST[GUID] $_POST[IP] $_POST[USERNAME] $_POST[BAN_REASON]");
I'm trying to insert a JSON array of objects passed via a jquery $.ajax POST into a MySQL database via PHP. I've seemingly tried everything but for some reason I can't get it to work. Any suggestions would be much appreciated.
PHP
<?php
$servername = "servername";
$username = "username";
$password = "password";
$dbname = "dbname";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$data = json_decode($_POST, true);
foreach ($data as $item) {
$worker_id = $item['worker_id'];
$response_time = $item['time'];
$video_id = $item['video_id'];
$submission = $item['response'];
$test_answer = $item['test_answer'];
$sql = "INSERT INTO nristudy (worker_id, response_time, video_id, submission, test_answer)
VALUES ('$worker_id', '$response_time', '$video_id', '$submission', '$test_answer')";
if (!($conn->query($sql))) {
die($conn->error);
}
}
if (!$conn->commit()) {
echo "Transaction commit failed";
exit();
}
$conn->close();
?>
Javascript
var json = JSON.stringify(submissions);
$.ajax({
type: "POST",
url: "http://hci.cs.wisc.edu/nri/store_data.php",
data: json,
success: function(data){
console.log("Success: " + data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert('An error occurred... look at the console for more information!');
console.log('jqXHR:');
console.log(jqXHR);
console.log('textStatus:');
console.log(textStatus);
console.log('errorThrown:');
console.log(errorThrown);
}
});
The solution to your problem depends heavily on what the error is. However, one thing that is pretty clear is that you should be escaping the strings you are trying to put into the query.
I recommend that you switch to using PDO and prepared statements as you will not have to worry about escaping anything and can rely on PDO to take care of it when you prepare the statement.
You might also want to try serialize instead of json_encode but if it works there is a chance that SQL injection is still a real big possibility for you.
<?php
$con = mysqli_connect("localhost", "root", "", "" ) or die("Neuspjelo spajanje");
function InsertUser(){ global $con;
if(isset($_POST['sign_up'])){
$name = mysqli_real_escape_string($con, $_POST['u_name']);
$pass = mysqli_real_escape_string($con,$_POST['u_pass']);
$email = mysqli_real_escape_string($con,$_POST['u_email']);
$country = mysqli_real_escape_string($con,$_POST['u_country']);
$gender = mysqli_real_escape_string($con,$_POST['u_gender']);
$b_day = mysqli_real_escape_string($con,$_POST['u_birthday']);
$date = date("m-d-Y");
$status = "unverified";
$posts = "No";
$get_email = "select * from users where user_email='$email'";
$run_email = mysqli_query($con, $get_email);
$check = mysqli_num_rows($run_email);
$insert = "insert into users (user_name, user_pass, user_email, user_country, user_gender, user_b_day,
user_image, register_date, last_login, status, posts) values
('$name','$pass', '$email', '$country', '$gender', '$b_day', 'default.jpg',
'$date', '$date', '$status', '$posts')";
$run_insert = mysqli_query($con, $insert);
$result = mysql_query($insert);
if($result){
echo "<script>alert ('You're successfully registered!')</script>";
echo "<script>window.open('home.php', '_self')</script>";
}
}
}
?>
You can't echo javascript and run it in a page that's already loaded. This would need to be the result of an ajax call on the client side with your redirects occuring from your ajax callbacks.
If you're ok with ditching the alert, you can just issue a redirect from php:
header('Location: home.php');
To do it ajaxy:
$.ajax({
type: "GET",
url: "your_insert_user.php"
}).success(function(xhr) {
alert ("You're successfully registered!");
window.open('home.php', '_self');
}).fail(function (jqXHR, status, errorThrown) {
//something else here
});
But, why would you want to issue an ajax call just to redirect?
Additionally, you need to issue the appropriate responses from your insert script:
if ($result) { echo ""; } //issues a "200 OK"
else { header("HTTP/1.1 422 Unprocessable Entity"); } //fires the failure callback in ajax
I would pass a conditional GET or POST paramater to home.php with some value flag and display your message there.
Based on what you post above, you are dealing with two separate issues here.
You say "it inserts" so I'm assuming that means that the mysql query to insert the new row into your database completes successfully. Then you send some HTML code, containing a (somewhat mangled) Javascript snippet, to the browser, which is supposed to issue a redirect request to the client's web browser, which doesn't have the desired result, seeing as you write that it "won't redirect".
Keep in mind that redirection is performed by the browser, is dependent on the browser's capabilities and/or settings, and requires proper javascript in the first place.
How do properly request a redirect from the browser has been discussed before on SO.
First of all,remove this line $result = mysql_query($insert); then modify your code and add this, hope it will work:
$run_insert = mysqli_query($con, $insert);
if($run_insert){
echo "<script>alert ('You\'re successfully registered!')</script>";
echo "<script>window.open('home.php', '_self')</script>";
}
I have a login script that should return 'success' or 'failure' respectively, but it adds many spaces before the result, in the console it shows tha value as "<tons of space> success". This is the PHP for the login script:
public function login() {
global $dbc, $layout;
if(!isset($_SESSION['uid'])){
if(isset($_POST['submit'])){
$username = mysqli_real_escape_string($dbc, trim($_POST['email']));
$password = mysqli_real_escape_string($dbc, trim($_POST['password']));
if(!empty($username) && !empty($password)){
$query = "SELECT uid, email, username, password, hash FROM users WHERE email = '$username' AND password = SHA('$password') AND activated = '1'";
$data = mysqli_query($dbc, $query);
if((mysqli_num_rows($data) === 1)){
$row = mysqli_fetch_array($data);
$_SESSION['uid'] = $row['uid'];
$_SESSION['username'] = $row['username'];
$_SERVER['REMOTE_ADDR'] = isset($_SERVER["HTTP_CF_CONNECTING_IP"]) ? $_SERVER["HTTP_CF_CONNECTING_IP"] : $_SERVER["REMOTE_ADDR"];
$ip = $_SERVER['REMOTE_ADDR'];
$user = $row['uid'];
$query = "UPDATE users SET ip = '$ip' WHERE uid = '$user' ";
mysqli_query($dbc, $query);
setcookie("ID", $row['uid'], time()+3600*24);
setcookie("IP", $ip, time()+3600*24);
setcookie("HASH", $row['hash'], time()+3600*24);
echo 'success';
exit();
} else {
//$error = '<div class="shadowbar">It seems we have run into a problem... Either your username or password are incorrect or you haven\'t activated your account yet.</div>' ;
//return $error;
$err = 'failure';
echo($err);
exit();
}
} else {
//$error = '<div class="shadowbar">You must enter both your username AND password.</div>';
//return $error;
$err = "{\"result\":\"failure\"}";
echo json_encode($err);
exit();
}
}
} else {
echo '{"result":"success"}';
exit();
}
return $error;
}
and the form and JS
<div class="shadowbar"><form id="login" method="post" action="/doLogin">
<div id="alert"></div>
<fieldset>
<legend>Log In</legend>
<div class="input-group">
<span class="input-group-addon">E-Mail</span>
<input type="email" class="form-control" name="email" value="" /><br />
</div>
<div class="input-group">
<span class="input-group-addon">Password</span>
<input type="password" class="form-control" name="password" />
</div>
</fieldset>
<input type="submit" class="btn btn-primary" value="Log In" name="submit" />
</form></div>
$(function login() {
$("#login").validate({ // initialize the plugin
// any other options,
onkeyup: false,
rules: {
email: {
required: true,
email: true
},
password: {
required: true
}
}
});
$('form').ajaxForm({
beforeSend: function() {
return $("#login").valid();
},
success : function(result) {
console.log(result);
if(result == " success"){
window.location = "/index.php";
}else if(result == " failure"){
$("#alert").html("<div class='alert alert-warning'>Either you're username or password are incorrect, or you've not activated your account.</div>");
//$("#alert").show();
}
}
});
});
but the result always has a lot of spaces for some reason. I'm new to JS, so if this is common, I don't already know.
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
define("CCore", true);
session_start();
//Load files...
require_once('include/scripts/settings.php');
require_once('include/scripts/version.php');
require('include/scripts/core.class.php');
require('include/scripts/nbbc_main.php');
$parser = new BBCode;
$core = new core;
$admin = new admin;
require_once('include/scripts/layout.php');
require_once('include/scripts/page.php');
//Set Variables...
global $dbc, $parser, $layout, $main, $settings, $core;
$page = new pageGeneration;
$page->Generate();
?>
this is my index, and anything before the page is generated and login() is called, is in there.
I suppose you are using Ajax calls. I had the same problem, but it my case the result hadn't contain spaces, it was returned in new line. The problem was that my script which was requested by Ajax, contained "new line" character before the PHP script. Search your script file for spaces before PHP script starting with <?php //code... If you had included some scripts in the script which returns success note, search them as well.
I dont know if it matters but your
if(result == " success"){ // <<<<<< Here is a Problem maybe
window.location = "/index.php";
}else if(result == " failure"){ // <<<<<< Here is a Problem maybe
$("#alert").html("<div class='alert alert-warning'>Either you're username or password are incorrect, or you've not activated your account.</div>");
//$("#alert").show();
}
compares your result from the server which is i.e. "success" with " success". There is space too much.
EDIT:: I dont get ether why you jumps between the response format. Sometimes you echo "success" which is plain and good with your if condition but sometimes you return json encodes strings.
These Responses you can't just compare with plain text. These Responses you have to Parse into a JSON Object. Then you could compare with:
if (parsedJSONobject.result == "success"){}
The comments on the question are most probably correct: the spaces are being (again, probably, nobody can know for sure without reading the whole source) echoed by PHP included before this. For example, if you do:
<?php
// there's a space before the previous line
you'd get that space in the output.
What you can do is a bit of a hack, you include a header, for example:
header('Content-Type: text/html');
just before your success output, this will (yet again, probably) output something like:
Warning: Cannot modify header information - headers already sent by (output started at /some/file.php:12) in /some/file.php on line 23
(note the "output started" part) and now you know where to start looking.
HTH.