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'm trying to create a system on my HTML website where you can enter a code which then gets checked by a php-file. The php shall compare the code with codes that are in my MYSQL Table. The php shall also check whether the code was allready used or not. After the check is completed a message shall appear on the Website that tells the user if his code is valid or not.
If the Code is valid, it shall inform me somehow that somebody entered a code.
I've wrote some code but when I press the button it's not working at all.Here my HTML code:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11/jquery.min.js">
</script>
<script>
$(document).ready(function() {
//the min chars for promo-code
var min_chars = 6;
//result texts
var checking_html = 'Checking...';
//when keyup
$('#code').keyup(function(event){
//run the character number check
if($('#code').val().length == min_chars){
//show the checking_text and run the function to check
$('#Promo_code_status').html(checking_html);
check_code();
}
});
});
//function to check the promo code
function check_code(){
//get code
var code = $('#code').val();
//use ajax to run the check
$.post("check_code.php", { code: code },
function(result){
//if the result is 0
if(result == 0){
//show that the code is correct
$('#Promo_code_status').html(code + ' is correct.');
}else if(result == 1){
//show that the code is correct, but already has been used
$('#Promo_code_status').html(code + ' has allready been used.');
}else{
//show that the code is not correct
$('#Promo_code_status').html(code + ' is not correct.');
}
});
}
</script>
</head>
<body>
<center><h1>Enter Promo Code</h1>
<form method="post" action="check_code.php">
<input type="text" id="code" name="code" maxlength="6" />
<div id="promo_code_status"></div>
<br>
<input type="submit" value="Let's go"></center>
</form>
</body>
</html>
And here you have my PHP File:
<?php
//connect to database
$user = "***"; //Username
$pass = "***"; //Password
$host = "localhost"; //Host
$dbdb = "***"; //Database name
$connect = mysqli_connect($host, $user, $pass, $dbdb);
if(!$connect)
{
trigger_error('Error connection to database: '.mysqli_connect_error());
}
//get the code
mysqli_real_escape_string($connect, $_POST['code']);
//mysql query to select field code if it's equal to the code that we checked '
$result = mysqli_query($connect, 'select Code from Codes where Code = "'. $code .'"');
$record = mysqli_fetch_array($result);
//if number of rows fields is bigger them 0 that means the code in the database'
if(mysqli_num_rows($result) > 0){
if($record['used'] == 0) {
//and we send 0 to the ajax request
echo 0;
} else{
//and we send 1 to the ajax request
echo 1;
}
}else{
//else if it's not bigger then 0, then the code is not in the DB'
//and we send 2 to the ajax request
echo 2;
}
?>
By pressing the Button "Let's go" the PHP shall do it's Job and afterwards it shall give the user the information about his code.
What do I have to change?
I thing you not assign the post value in $code, that's reason.
$code = mysqli_real_escape_string($connect, $_POST['code']);
make sure the jquery CDN that you are using can be accessed. because it looks like wrong CDN.
in the checkcode() function, you use #Promo_code_status, P is uppercase, while in html you use promo_code_status with p is lowercase.
in php file you forget to assign values to the $code
I hope this helps
I am having an issue with a brand new site I am trying to create, Its pretty basic right now, and I am just playing around with seeing how I like to do things.
So I have a place where I can log in currently, just two forms and a button. And I would like to use Ajax to call a php script that handles the login and then spits out a response depending on how it goes.
Here is what I have.
HTML:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<form id="key-form" name="keyform" action="scriptLogin.php" method="POST">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" class="button" value="Login">
</form>
Ajax Call:
$(document).ready(function(){
$("#key-form").submit(function(e) {
e.preventDefault(); // stop normal form submission
$.ajax({
url: "scriptLogin.php",
type: "POST",
data: $(this).serialize(), // you also need to send the form data
dataType: "json",
success: function(data){ // this happens after we get results
$("#response").show();
$("#response").html("");
// If there is no error the response will be {"success":true}
// If there is any error means the response will be {"error":["1":"error",..]}
if(data.success){
$("#response").prepend("<h3>Successfully Logged In</h3>");
}else{
$.each(data.error, function(index, val){
$("#response").prepend("<h3>" +val+ '</h3>');
});
}
}
});
});
});
scriptLogin.php
<?php
session_start();
// Database configuration
// Not the real credentials obviously
define('DB_HOST', 'dbhost');
define('DB_USER', 'username');
define('DB_PASS', 'password');
define('DB_NAME', 'dbname');
// Initializing error array
$response['error'] = array();
try {
$db = new PDO('mysql:host=' . DB_HOST .';dbname=' . DB_NAME . ';charset=utf8mb4', DB_USER, DB_PASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
} catch (Exception $e) {
$response['error'][] = "Error in DB Connection";
}
// Store post and session values to variable.
$username = $_POST['username'];
$password = $_POST['password'];
$key = $_POST['key'];
// Validating Password
if($password === '' || $password === FALSE ){
$response['error'][] = "Your Password cannot be blank";
}
if($username === '' || $username === FALSE ){
$response['error'][] = "Your Username is too short!";
}
// If validation password update the password for the user.
if(empty($response['error'])){
$stmt = $db->prepare("SELECT * FROM Login WHERE username= :username"); // Prepare the query
// Bind the parameters to the query
$stmt->bindParam(':username', $username);
$stmt->bindParam(':password', $password);
//Carry out the query
$stmt->execute();
$hash = $stmt['hash'];
$affectedRows = $stmt->rowCount(); // Getting affected rows count
if($affectedRows != 1){
$response['error'][] = "No User is related to the Username";
}
if(password_verify($password, $hash))
{
$_SESSION['username'] = $_POST['username'];
$_SESSION['userid'] = $stmt['ID'];
}
else
{
$response['error'][] = "Your password is invalid.";
}
}
// printing response.
if(!empty($response['error'])){
echo json_encode($response);
}else{
echo json_encode(array("success"=>true));
}
?>
So whenever I try and log in. I get this error:
POST http://website.net/scriptLogin.php 500 (Internal Server Error)
m.ajaxTransport.send # jquery.min.js:4
m.extend.ajax # jquery.min.js:4
(anonymous function) # (index):62
m.event.dispatch # jquery.min.js:3
m.event.add.r.handle # jquery.min.js:3
I need a shove in the correct direction. I checked the sites error page on cpanel. I have nothing for this. Im baffled.
EDIT #1:
Here is the error from loginScript.php
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY093]: Invalid parameter number: parameter was not defined' in /home/mcomputers/public_html/key/scriptLogin.php:40 Stack trace: #0 /home/mcomputers/public_html/key/scriptLogin.php(40): PDOStatement->bindParam(':password', NULL) #1 {main} thrown in /home/mcomputers/public_html/key/scriptLogin.php on line 40
I'm writing a little install script for my current project. The first "step" of this script asks the user for his MySQL credentials and tests them. Everything is done via an AJAX query using jQuery's $.ajax.
My client-side script looks like this:
<section class="col-md-6" style="display: none;" id="pane2">
<h1 style="text-align: center;">MySQL Setup</h1>
<form method="POST" action="stuff.php" role="form" class="installform">
<input type="text" class="form-control" placeholder="Host" name="host" id="host">
<input type="text" class="form-control" placeholder="Database Name" name="dbname" id="dbname">
<input type="text" class="form-control" placeholder="Username" name="sqlusername" id="sqlusername">
<input type="password" class="form-control" placeholder="Password" name="sqlpassword" id="sqlpassword">
</form>
<a><button class="btn btn-primary btn-lg btn-block" id="sqlbutton">Next</button></a>
<script>
$(function() {
$('#sqlbutton').click(function() {
var host = $('#host').val();
var dbname = $('#dbname').val();
var username = $('#sqlusername').val();
var password = $('#sqlpassword').val();
var credentials = "host=" + host + "&dbname=" + dbname + "&username=" + username + "&password=" + password;
$.ajax({
type: "POST",
url: "sqlchecker.php",
data: credentials,
success: function(data) {
if (data == 'success') {
$('#sqlbutton').html("All right.");
}
else {
$('#sqlbutton').html("Something is wrong");
}
}
});
});
});
</script>
And my sqlchecker.php script is currently this:
<?php
$host = $_POST['host'];
$dbname = $_POST['dbname'];
$username = $_POST['username'];
$password = $_POST['password'];
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
// Opens a connection to the database using PDO
try {
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
}
catch(PDOException $ex)
{
die("Couldn't connect to the database. Error code: " . $ex->getMessage());
}
echo('success');
?>
Of course, at the moment, it makes absolutely no distinction between errors, if there wasn't any, it displays "All right." and if there was one, then it displays "Something is wrong". But I'd like it to be a bit more specific and tell the user what exactly is wrong in the query.
I'm looking to kind of "parse" PDO exceptions, the problem is that they return a complete sentence that is almost impossible to use in an if statement. Is there a way to configure PDO at the connection so it only returns an error code, that would be way easier to interpret using jQuery?
Thanks a lot for your answers!
A call to getCode on the exception should give you a code you can work with. You could then switch on this and give your user some appropriate feedback. This would definitely be cleaner than trying to manipulate the string message returned.
$errorCode = $ex->getCode();
switch($errorCode) {
case 1000:
//...
break;
default:
//...
break;
}
For my sql I believe the error code will be listed here:
https://dev.mysql.com/doc/refman/5.0/en/error-messages-server.html
Basically I have a php script located on a sever that generates a JSON file listing places from a mysql database. Using jQuery Mobile I am developing an application to display these places. My code works in Chrome & Safari, however when I port it over to Phonegap it doesn't work. I have searched all over the internet but can't find an answer :(.
The php file for generating JSON (json.php):
<?php
header('Content-type: application/json');
$server = "localhost";
$username = "xxx";
$password = "xxx";
$database = "xxx";
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$sql = "SELECT * FROM places ORDER BY name ASC";
$result = mysql_query($sql) or die ("Query error: " . mysql_error());
$records = array();
while($row = mysql_fetch_assoc($result)) {
$records[] = $row;
}
mysql_close($con);
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
?>
My Javascript file located within my app (Loads JSON and displays it):
$('#places').bind('pageinit', function(event) {
getPlaces();
});
function getPlaces() {
var output = $('#placeList');
$.ajax({
url: 'http://www.mysite.com/json.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
var place = '<li><a href="">'+item.name+'<span class="ui-li-count">'
+ item.checkins+'</span></a></li>';
output.append(place);
});
$('#placeList').listview('refresh');
},
error: function(){
output.text('There was an error loading the data.');
}
});
}
The HTML looks like this:
<div data-role="content">
<h3>Places</h3>
<ul data-role="listview" id="placeList" data-inset="true">
</ul>
</div><!-- /content -->
This code works in Chrome & Safari, however when run in the xCode simulator with Phonegap it doesn't load the JSON.
Any help would be much appreciated :)
This has probably something to do with the whitelisting, Apple has no faith in any type of uncontrollable data (like iframes or feeds). So they reject every external connection.
Take a look at phonegap.plist in your project rootfolder (xcode) and add your website url to the array 'ExternalHosts'. This will probably work fine after.
I am working on a PhoneGap with Android project. I have designed a login page in which I want to show an alert box for a valid and invalid user. I am using PHP for database validation.
This is my php page:
<?php
header('Content-type: application/json');
$server = "localhost";
$username = "root";
$password = "";
$database = "mymusic";
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$id=$_GET["id"];
$pass=$_GET["password"];
//$id='ram';
//$pass='ram';
$sql = "SELECT id, name,password FROM login where userid='$id' and password='$pass'";
$result = mysql_query($sql) or die ("Query error: " . mysql_error());
$records = array();
while($row = mysql_fetch_assoc($result)) {
$records[] = $row;
}
mysql_close($con);
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
?>
This is my java script function:
function onDeviceReady(){
var output = $('#output');
var id = document.getElementById('userid').value;
var pass = document.getElementById('password').value;
// webcam.set_api_url( 'test.php?filename=' + escape(filename));
$.ajax({
url: 'http://192.168.1.214/sample/dologin.php?id='+id+'&password='+pass,
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
console.log('entered success============');
$.each(data, function(i,item){
var logi=item.id;
if(logi!=null)
alert("valid user");
else
alert("invalid user");
});
},
error: function(){
console.log('entered success====================');
output.text('There was an error loading the data.');
}
});
}
This is not working properly for an invalid user. Whenever I enter a valid user name and password then it displays the valid user message box. When I enter an invalid user name and password then it doesn't display anything.
Thank you in advance...
Try debugging this in a browser and perhaps send the returned jsonp data to the console from within your ajax's success call console.log(data).
It's quite possible that your jsonp is returning some data as opposed to null... even if it is simply undefined or an empty string. Your conditional is most likely the culprit.