Ho all, here I explain my problem (as far as i red i didnt find any working solution).
here I link my files:
progetto.html
<html>
<head>
<script type="text/javascript" src="funzioni.js"></script>
<title>Pagina iniziale</title>
</head>
<body align='center'>
<p>Gymnasium</p>
<p>icona</p>
<form id="ajaxForm" name="ajaxForm">
<table align="center">
<tr>
<td><label>Utente</label></td>
<td><input type="text" name="user" id="user" value="" /></td>
</tr>
<tr>
<td><label>Password</label></td>
<td><input type="password" name="password" id="password" value="" /></td>
</tr>
</table>
<input type="button" id="submit" name="submit" value="Accedi" onclick='submitForm()' />
</form>
<div id="risultato"></div>
</body>
javascript file
function createXMLHttpRequestObject(){
if (window.XMLHttpRequest) { return new XMLHttpRequest(); }
if (window.ActiveXObject) { return new ActiveXObject(Microsoft.XMLHTTP); }
return null;
}
function submitForm(){
var ajax = createXMLHttpRequestObject();
ajax.onreadystatechange = function () {
if (ajax.readyState==4 && ajax.status==200){
var response = ajax.responseText;
document.getElementById("risultato").innerHTML = response;
}
}
ajax.open("post", "ajaxLogin.php", true);
var data = "utente=" + document.getElementById('user').value + "&password=" + document.getElementById('password').value;
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajax.send(data);
}
ajaxLogin.php
<?php
if (!isset($_POST["user"]) || !isset($_POST["password"])){
die("Bad login");
}
$user = $_POST['user'];
$pwd = $_POST['password'];
if ( (($user == "angel") && ($pwd == "devil")) || (($user == "john") && ($pwd == "smith")) ){
$response = "Benvenuto " . $user;
echo $response;
}
?>
Problem is I always receive Bad Login message even if I use the right user and password.
It's a POST problem with I'm really having hard time figuring out the solution.
This is your data:
var data = "utente=" + document.getElementById('user').value + "&password=" + document.getElementById('password').value;
And this is what you are checking:
if (!isset($_POST["user"]) || !isset($_POST["password"])){
You should change utente to user or the other way around. In your form you are using user as well so I would recommend using that everywhere.
So:
var data = "user=" + document.getElementById('user').value + "&password=" + document.getElementById('password').value;
Related
I'm making a game and to use it, you must register. So I'm trying to append a username and password that has been entered into a form to my JSON file which looks like:
{
"LogIns":[
{
"Username":"mikehene",
"password":"123"
},
{
"Username":"mike",
"password":"love"
}
]
}
My PHP reads:
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$str = file_get_contents('logins.json'); // Save contents of file into a variable
$json = json_decode($str, true); // decode the data and set it to recieve data asynchronosly - store in $json
array_push($json, $username, $password);
$jsonData = json_encode($json);
file_put_contents('logins.json', json_encode($json));
?>
AJAX:
function callAJAX(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange=function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
console.log(xhttp.responseText);
document.getElementById("PHPid").innerHTML = xhttp.responseText;
}
}
xhttp.open("POST", "reg.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("username=" + usernamePassed + "&password="+ userPassword);
}
HTML:
<fieldset>
<legend>Please register before playing</legend>
<form>
Username: <br>
<input type="text" placeholder="Enter a Username" id="username1" name="username"><br>
Password: <br>
<input type="password" placeholder="Enter a password" id="password" name="password"><br>
<input type="submit" value="Submit" onclick="return checkLogin();">
</form>
</fieldset>
<div id="PHPid"><div>
<script>
var usernamePassed = '';
var userPassword = "";
function checkLogin(){
usernamePassed = document.getElementById("username1").value;
userPassword = document.getElementById("password").value;
console.log(usernamePassed);
console.log(userPassword);
callAJAX();
return false;
}
function callAJAX(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange=function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
console.log(xhttp.responseText);
document.getElementById("PHPid").innerHTML = xhttp.responseText;
}
}
xhttp.open("POST", "reg.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("username=" + usernamePassed + "&password="+ userPassword);
</script>
So for example if I inputted username: mike, password:123 into the HTML field it should update my json file but my json file is not changing.
I'm running it on localhost and I have checked the permissions, which are set to read and write for all users.
Any ideas why?
Thanks in advance
The problem here is that you are missing a closing brace } for your callAJAX() function.
Having looked at your developer console, you would have seen the following:
SyntaxError: missing } after function body
Fixed script code:
<script>
var usernamePassed = '';
var userPassword = "";
function checkLogin(){
usernamePassed = document.getElementById("username1").value;
userPassword = document.getElementById("password").value;
console.log(usernamePassed);
console.log(userPassword);
callAJAX();
return false;
}
function callAJAX(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange=function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
console.log(xhttp.responseText);
document.getElementById("PHPid").innerHTML = xhttp.responseText;
}
}
xhttp.open("POST", "reg.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("username=" + usernamePassed + "&password="+ userPassword);
}
</script>
- Using a code editor with bracket/brace matching, would have helped ;-)
You are already using one as pointed out in comments.
What I tested this with was:
<fieldset>
<legend>Please register before playing</legend>
<form>
Username: <br>
<input type="text" placeholder="Enter a Username" id="username1" name="username"><br>
Password: <br>
<input type="password" placeholder="Enter a password" id="password" name="password"><br>
<input type="submit" value="Submit" onclick="return checkLogin();">
</form>
</fieldset>
<div id="PHPid"><div>
<script>
var usernamePassed = '';
var userPassword = "";
function checkLogin(){
usernamePassed = document.getElementById("username1").value;
userPassword = document.getElementById("password").value;
console.log(usernamePassed);
console.log(userPassword);
callAJAX();
return false;
}
function callAJAX(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange=function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
console.log(xhttp.responseText);
document.getElementById("PHPid").innerHTML = xhttp.responseText;
}
}
xhttp.open("POST", "reg.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("username=" + usernamePassed + "&password="+ userPassword);
}
</script>
and
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$str = file_get_contents('logins.json'); // Save contents of file into a variable
$json = json_decode($str, true); // decode the data and set it to recieve data asynchronosly - store in $json
array_push($json, $username, $password);
$jsonData = json_encode($json);
file_put_contents('logins.json', json_encode($json));
?>
I have an ajax function in my index file:
var xmlhttp;
function loadocget(url, func)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = func;
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function verifyLogin() {
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
var formdata = "username=" + username + "&password=" + password;
loadocget("verify.php?" + formdata, function ()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var result = xmlhttp.responseText;
if (result != "true"){
document.getElementById("ack").innerHTML = "<p>Your username or password is invalid</p>";
});
}
}
}
And a form also in my index file:
<div id="ack"></div>
<form action="member.php" method="post" onsubmit="return verifyLogin();" name="login-form" id="login-form">
<div>
<div class="form-group">
<label for="username">Username: </label>
<input name="username" id="username" class="form-control" type="text" placeholder="Username" required/>
</div>
<div class="form-group">
<label for="password">Password: </label>
<input name="password" id="password" class="form-control" type="password" placeholder="Password" required/>
</div>
</div>
<div>
<div class="form-group">
<input type="submit" class="btn btn-danger form-control" id="login-submit" name="login-submit" value="Sign In" />
</div>
<div class="form-group">
<input type="button" class="btn btn-primary form-control" id="signup-button" name="signup-button" value="Sign Up"/>
</div>
</div>
<div class="form-group">
<div id="forgot" class="link-div"><p style="cursor: pointer;">Forgot your username or password?</p></div>
</div>
</form>
And a verify.php file to check username and password:
<?php
$username = $_GET['username'];
include_once 'connectDB.php';
$Table = "users";
$temp = $_GET['password'];
$password = md5($username . $temp);
$SQLstring = "SELECT * FROM $Table WHERE username='$username' AND password='$password'";
$result = mysql_query($SQLstring, $DBConnect);
if (mysql_num_rows($result) == 0) {
echo false;
} else {
echo true;
}
?>
When I debug these codes with firebug, I could see the warning message appeared, but the form still took user to the member.php page. Please help. Thanks a lot.
Javascript is checking the response for the character string "true", but your PHP code is sending the boolean true or false. When you echo these, true becomes 1 and false is an empty string.
Change it to:
if (mysql_num_rows($result) == 0) {
echo "false";
} else {
echo "true";
}
You also need to modify verifyLogin so that it prevents normal form submission (by returning false). After it gets a successful response it can submit the form for real.
function verifyLogin() {
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
var formdata = "username=" + username + "&password=" + password;
loadocget("verify.php?" + formdata, function ()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var result = xmlhttp.responseText;
if (result != "true"){
document.getElementById("ack").innerHTML = "<p>Your username or password is invalid</p>";
} else {
document.getElementById("login-form").submit();
}
}
}
return false;
}
I'm sending data to a PHP page in the form of a POST request. On chrome dev tools I can see the POST with payload of:
"username=T&password=t&cpassword=t&email=t&cemail=t"
My PHP file starts with the following:
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$cpassword = $_POST['cpassword'];
$email = $_POST['email'];
$cemail = $_POST['cemail'];
echo("Username: $username <br>Password: $password <br>cPassword: $cpassword <br>Email: $email <br>cEmail: $cemail");
....
However, the page just shows:
Username: Password: cPassword: Email: cEmail:
Why is this and how can I make it so that $username, $password, $cpassword, $email and $cemail are set?
EDIT: method for generating post data is as follows:
<script>
function validateForm() {
window.alert("Form submitted");
var username = encodeURIComponent(document.getElementById("username").value);
var password = encodeURIComponent(document.getElementById("password").value);
var cpassword = encodeURIComponent(document.getElementById("cpassword").value);
var email = encodeURIComponent(document.getElementById("email").value);
var cemail = encodeURIComponent(document.getElementById("cemail").value);
var postData = "username=" +username + "&password=" + password + "&cpassword=" + cpassword + "&email=" + email + "&cemail=" + cemail;
window.alert(postData);
if (email != cemail) {
window.alert("Emails do not match");
document.getElementById("response").innerHTML = "Emails do not match";
return false;
}
if (password != cpassword) {
window.alert("Passwords do not match");
document.getElementById("response").innerHTML = "Passwords do not match";
return false;
}
if (email == "" || email == null) {
window.alert("Email is blank");
document.getElementById("response").innerHTML = "Email cannot be blank";
return false;
}
if (password == "" || password == null) {
window.alert("Password is blank");
document.getElementById("response").innerHTML = "Password cannot be blank";
return false;
}
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
var response=xmlhttp.responseText;
window.alert("Response recieved: " + response);
if (response == "New record created successfully") {
window.alert("Registration successful");
document.getElementById("response").innerHTML = "Registration successful!";
} else {
window.alert("Something went wrong... :(");
document.getElementById("response").innerHTML = "Something went wrong... :(";
}
}
}
xmlhttp.open("POST", "./handleRegistration.php", true);
window.alert("xmlhttp open");
xmlhttp.send(postData);
window.alert("POSTED");
return false;
}
</script>
<form name="heliosRegister" onsubmit="return validateForm()" method="POST">
Username:<br>
<input id="username" type="text" name="username" required>
<br><br>
Passsword:<br>
<input id="password" type="password" name="password" required>
<br><br>
Confirm Passsword:<br>
<input id="cpassword" type="password" name="cpassword" required>
<br><br>
Email:<br>
<input id="email" type="text" name="email" required>
<br><br>
Confirm Email:<br>
<input id="cemail" type="text" name="cemail" required>
<br><br>
<input type="submit" value="Register"> <p id="response"></p>
</form>
EDIT 2:
Problem solved, forgot to add the header information when sending the POST.
The problem was that I forgot to add the header info before POSTing:
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", postData.length);
xmlhttp.setRequestHeader("Connection", "close");
replace
var username = encodeURIComponent(document.getElementById("username").value);
var password = encodeURIComponent(document.getElementById("password").value);
var cpassword = encodeURIComponent(document.getElementById("cpassword").value);
var email = encodeURIComponent(document.getElementById("email").value);
var cemail = encodeURIComponent(document.getElementById("cemail").value);
var postData = "username=" +username + "&password=" + password + "&cpassword=" + cpassword + "&email=" + email + "&cemail=" + cemail;
with
var fd=new FormData();
fd.append("username",document.getElementById("username").value);
fd.append("password",document.getElementById("password").value);
fd.append("cpassword",document.getElementById("cpassword").value);
fd.append("email",document.getElementById("email").value);
fd.append("cemail",document.getElementById("cemail").value);
then use
xmlhttp.send(fd);
and i think it should work.
btw, $cpassword = $_POST['cpassword'];
should have given you an obvious error! (Undefined index),
while developing, use this code! much easier to spot several types of errors during development:
error_reporting(E_ALL);
function exception_error_handler($errno, $errstr, $errfile, $errline ) {
if (!(error_reporting() & $errno)) {
// This error code is not included in error_reporting
return;
}
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
set_error_handler("exception_error_handler");
Hello
I know this subject has been proposed before, but no one has done the AJAX manipulation standard like i did. I'm newbie to AJAX and jQuery
The problem I have here is that I'm not sure that the js function "ajaxPostCallManip()" reaches to "login.php"!!
I've made a couple of alert()s but nothing appears...Please help
HTML CODE
<link rel="stylesheet" type="text/css" href="jQuery-Files/jquery.mobile-1.3.1.css"/>
<script type="text/javascript" src="jQuery-Files/jquery-2.0.2.js"></script>
<script type="text/javascript" src="jQuery-Files/jquery.mobile-1.3.1.js"></script>
<script type="text/javascript" src="js/ajax.js"></script>
<div data-role="page" id="loginDialog">
<header data-role="header">
<h3 style="margin-left: auto; margin-right: auto;">Login or <a href="#regpage"
data-transition="flip">Register</a></h3>
</header>
<div data-role="content">
<form method="POST" action="" onsubmit="check_login(); return false;">
<fieldset data-role="contolgroup">
<div data-role="fieldcontain">
<label for="login_username">Username</label>
<input type="text" name="login_username" id="login_username"
placeholder="username" />
<label for="login_pwd">Password</label>
<input type="password" name="login_pwd" id="login_pwd"
placeholder="password" />
<div style="margin: auto; text-align: center;">
<label for="login_submit" class="ui-hidden-accessible">
Submit</label>
<button onclick="this.form.submit()" value="Submit"
data-inline="true"></button>
<span class="error" id="login_err" name="login_err"
style="display: none; font-size: 12px;
text-align: center;">status</span>
</div>
</div>
</fieldset>
</form>
</div>
</div>
js CODE
// AJAX Call handler using method="POST"
function ajaxPostCallManip( str, url, toDoFunc )
{
var xmlhttp; // Request variable
if( window.XMLHttpRequest ) // For modern browsers
xmlhttp = new XMLHttpRequest;
else // For old browsers
xmlhttp = new ActiveXOBject("Microsoft.XMLHttp");
xmlhttp.onreadystatechange=toDoFunc;
xmlhttp.open("POST", url, true);
xmlhttp.send(str);
}
function check_login()
{
// Construct the POST variables [username, password]
var postStr = "username=" + $('#login_username').val() + "&"
+ "password=" + $('#login_pwd').val();
// Call the general purpose AJAX Handler Function
ajaxPostCallManip(postStr, "login.php", function()
// toDoFunc to be performed when server response is ready
{
if( xmlhttp.readyState == 4 && xmlhttp.status == 200 )
{
alert(xmlhttp.responseText);
switch(xmlhttp.responseText)
{
case "1":
$('#login_err').css({'color':'green','display':'block'})
.html('Successful Login');
break;
case "2":
$('#login_err').css({'color':'red','display':'block'})
.html('incorrect username/password')
break;
case "3":
$('#login_err').css({'color':'red','display':'block'})
.html('please fill in all fields')
break;
}
}
});
}
PHP CODE
<?php
include('dbManip.php');
echo '<script> alert("Inside login.php"); </script>';
$username = $_POST['username'];
$password = $_POST['password'];
// Just to check that the POST variables arrived safely
echo "<script> alert('username = ' + $username); </script>";
if(!empty($username) && !empty($password))
{
// Fetch data from database
$query = "
SELECT username,password
FROM users
WHERE username = '$username' and password = '$password';
";
// Execute query
$res = mysql_query($query);
// If there is a match for the credentials entered with the database
if(mysql_num_rows($res) == 1)
{
// Fetch information and double check credentials
while($row = mysql_fetch_assoc($res))
{
$db_username = $row['username'];
$db_password = $row['password'];
}
// Compare results with user input
if( $username == $db_username && $password == $db_password)
{
// Credentials are correct - response = 1
echo '1';
}
else
{
// Credentials are incorrect - response = 2
echo '2';
}
}
else
{
// There is no match in the database
// Credentials are incorrect - response = 2
echo '2';
}
}
else
{
// If one or both fields are empty - response = 3
echo '3';
}
?>
First, you need to rewrite the submit button:
<button type="Submit" value="Submit"data-inline="true"></button>
Second, move the variable from a function that would make it a global:
var xmlhttp; // Request variable
function ajaxPostCallManip( str, url, toDoFunc )
{
if( window.XMLHttpRequest ) // For modern browsers
xmlhttp = new XMLHttpRequest;
else // For old browsers
xmlhttp = new ActiveXOBject("Microsoft.XMLHttp");
xmlhttp.onreadystatechange=toDoFunc;
xmlhttp.open("POST", url, true);
xmlhttp.send(str);
}
I think you need to rewrite this line of code:
<form method="POST" action="" onsubmit="check_login(); return false;">
And change it to:
<form method="POST" action="login.php" onsubmit="check_login(); return false;">
Make sure to save login.php in the same folder as your html file.
remove the method="post" and action="" attribute from the form tag because you are defining it in the ajax call
<button type="Submit" value="Submit"
var xmlhttp; // Request variable
function ajaxPostCallManip( str, url, toDoFunc )
{
if( window.XMLHttpRequest ) // For modern browsers
xmlhttp = new XMLHttpRequest;
else // For old browsers
xmlhttp = new ActiveXOBject("Microsoft.XMLHttp");
xmlhttp.onreadystatechange=toDoFunc;
xmlhttp.open("POST", url, true);
xmlhttp.send(str);
}
In the following code, on successful login, I am trying to open admin.htm. the content is loaded into the same page using AJAX, how can I instead open it in a new window but retain any error messages in the original window in case of error?
login.htm
<form>
Username:<input type="text" name= "username" size="15" />
Password:<input type="password" name= "passwrd" size="15" />
<input name="submit" type = "button" onClick = "getdata('login.php','display',username.value,passwrd.value)" value = "Login" />
</form>
<div id="display"></div>
login.js
function getdata(dataSource, divID, usrname, pwd) {
if (xhr) {
var obj = document.getElementById(divID);
var requestbody = "username=" + encodeURIComponent(usrname) + "&password=" + encodeURIComponent(pwd);
xhr.open("POST", dataSource, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
obj.innerHTML = xhr.responseText;
}
}
xhr.send(requestbody);
}
}
the form is using AJAX on purpose to display the result on the page you are on...
To open the result in a new page, remove the onclick and the script and give a target:
<form action="login.php" target="_blank" method="post">
Username:<input type="text" name= "username" size="15" />
Password:<input type="password" name= "passwrd" size="15" />
<input type="submit" value = "Login" />
</form>
If all you want is to NOT see the form after submit, wrap the form in the display div:
<div id="display">
<form>.....
</form>
</div>
UPDATE:
to get the error message into the page, do
if (xhr.readyState == 4 && xhr.status == 200) {
var text = xhr.responseText;
if (text.indexOf("You must") == 0) obj.innerHTML = text;
else window.open(text,"_blank")
}
<?php
$usernam = $_POST["username"];
$pwd = $_POST["password"];
if (empty($usernam) || empty($pwd)) {
echo "You must enter both username and password to login.";
} else {
echo 'admin.htm';
}
?>