POST payload not being read by PHP page - php

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");

Related

Updating JSON file with PHP & AJAX

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

Login check with ajax

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

Why send data using ajax by input `type="password"` not work?

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.

ajax post method and php

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;

PHP - verify if user exist in DB and display the result without reloading the page

I want to check if a user exists in DB, and if exist display some error without reload the page (modify a div). Any idea what is wrong in this code? Or any other idea how to do it? Thank you
HTML:
<div style="width:510px; height:500px;">
<div class="message">
<div id="alert"></div>
</div>
<form id="signup_form" method="post" action="register.php">
<label class="label">username</label>
<p><input class="signup_form" type="text" name="username"></p>
<label class="label">parola</label>
<p><input class="signup_form" type="text" name="password"></p>
<label class="label">name</label>
<p><input class="signup_form" type="text" name="name"></p>
<label class="label">telefon</label>
<p><input class="signup_form" type="text" name="phone"></p>
<label class="label">email</label>
<p><input class="signup_form" type="text" name="email"></p>
<p><input class="signup_button" type="submit" value="inregistrare">
</form>
<div class="clear"></div>
</div>
register.php
<?php
include "base.php";
$usertaken = '<li class="error">username used</li><br />';
$alert = '';
$pass = 0;
if(!empty($_POST['username']) && !empty($_POST['password']))
{
$username = mysql_real_escape_string($_POST['username']);
$password = md5(mysql_real_escape_string($_POST['password']));
$name = mysql_real_escape_string($_POST['username']);
$phone = mysql_real_escape_string($_POST['phone']);
$email = mysql_real_escape_string($_POST['email']);
$checkusername = mysql_query("SELECT * FROM details WHERE user = '".$username."'");
if(mysql_num_rows($checkusername) == 1)
{
$pass = 1;
$alert .="<li>" . $usertaken . "</li>";
}
else
{
$registerquery = mysql_query("INSERT INTO details (user, pass, name, phone, email) VALUES('".$username."', '".$password."','".$name."','".$phone."', '".$email."')");
if($registerquery)
{
echo "<h1>Success</h1>";
echo "<p>Your account was successfully created. Please click here to login.</p>";
}
else
{
echo "<h1>Error</h1>";
echo "<p>Sorry, your registration failed. Please go back and try again.</p>";
}
}
if($pass == 1) {
echo '<script>$(".message").hide("").show(""); </script>';
echo "<ul>";
echo $alert;
echo "</ul>";
}
}
?>
SOLUTION (add this in head and hide .message div)
<script type="text/javascript" src="jquery-latest.pack.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var options = {
target: '#alert',
beforeSubmit: showRequest,
success: showResponse
};
$('#signup_form').ajaxForm(options);
});
function showRequest(formData, jqForm, options) {
var queryString = $.param(formData);
return true;
}
function showResponse(responseText, statusText) {
}
$.fn.clearForm = function() {
return this.each(function() {
var type = this.type, tag = this.tagName.toLowerCase();
if (tag == 'form')
return $(':input',this).clearForm();
if (type == 'text' || type == 'password' || tag == 'textarea')
this.value = '';
else if (type == 'checkbox' || type == 'radio')
this.checked = false;
else if (tag == 'select')
this.selectedIndex = -1;
});
};
</script>
You need to use AJAX to do a dynamic page update.
Take a look here: http://api.jquery.com/jQuery.ajax/ for how to do it with jQuery.
Your current code uses a form submit, which always reloads the page.
You need to use ajax. Write something like this as a JavaScript:
var xmlHttp;
function checkUser(user) {
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null) {
alert ("Browser does not support HTTP Request.");
return;
}
var url = "check.php"; //This is where your dynamic PHP file goes
url = url + "?u=" + user;
url = url + "&sid=" + Math.random();
xmlHttp.onreadystatechange = getData;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
function getData () {
if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") {
if (xmlHttp.responseText == 1) {
alert('Username free'); //action if username free
} else {
alert('This username is taken'); //action if its not
}
}
}
function GetXmlHttpObject() {
var xmlHttp=null;
try {
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
} catch (e) {
//Internet Explorer
try {
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
And in your check.php file, just check against your database if the username is taken or not, if not and simply echo('1') if its free, else echo('0') o whatever you want. that single number will be handled as the xmlHttp.responseText. you can also do something fancy instead of the alerts, like an image. also you need to run the check() fumction either when the user is typing, or when the form is submitted, with the username form field as a parameter. Hope this helps.
EDIT: Oh, also I forgot that in the check.php file, the $_GET['u'] variable contains the the entered username. Check that against the database.
If that's all in a single page, you'll have to structure it like this:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
... do form retrieval/database stuff here ...
if (error) {
$message = 'Something dun gone boom';
}
}
if ($message != '') {
echo $message;
}
?>
form stuff goes here

Categories