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));
?>
Related
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");
Why send data using ajax by input type="password" not work ?
Main idea When i fill password less 6 char it's will display Password minimum 6 characters
OK, when i test on this code it not work, and then i edit code index.php from
<input type="password" name="password" id="password"
to
<input type="text" name="password" id="password"
it's work ok.
my question is , how to apply this code for using on <input type="password" name="password" id="password"
index.php
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script language="JavaScript">
var HttPRequest = false;
function doCallAjaxpassword() {
HttPRequest = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
HttPRequest = new XMLHttpRequest();
if (HttPRequest.overrideMimeType) {
HttPRequest.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) { // IE
try {
HttPRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
HttPRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!HttPRequest) {
alert('Cannot create XMLHTTP instance');
return false;
}
var url = 'check_password_lenght.php';
var pmeters = "CPassword=" + encodeURIComponent( document.getElementById("password").value);
HttPRequest.open('POST',url,true);
HttPRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
HttPRequest.setRequestHeader("Content-length", pmeters.length);
HttPRequest.setRequestHeader("Connection", "close");
HttPRequest.send(pmeters);
HttPRequest.onreadystatechange = function()
{
if(HttPRequest.readyState == 3) // Loading Request
{
document.getElementById("mySpanpassword").innerHTML = "..";
}
if(HttPRequest.readyState == 4) // Return Request
{
if(HttPRequest.responseText == 'Y')
{
window.location = 'AjaxPHPRegister3.php';
}
else
{
document.getElementById("mySpanpassword").innerHTML = HttPRequest.responseText;
}
}
}
}
</script>
<input type="password" name="password" id="password" onchange="JavaScript:doCallAjaxpassword();" value="<?php echo htmlspecialchars($_POST['password']); ?>"> <span id="mySpanpassword"></span>
check_password_lenght.php
<?php
$strPassword = $_POST[CPassword];
// ฟังก์ชันตรวจสอบว่า password มีความยาวเกิน 6 ตัวหรือไม่
$strlen_password = strlen($strPassword);
if ( $strlen_password < 6 )
{
echo "Password minimum 6 characters";
}
?>
Better not to use XMLHttpRequest object when you have jQuery loaded on the page, its a waste of time.
HTML
<input type="password" name="password" id="password"/>
JS
$.ajax({
type: "POST",
url: "check_password_lenght.php",
data: { password : $('#password').val() }
}).done(function( response ) {
alert( response );
});
Edit it as you like.
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;
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';
}
?>