I have a web page on which i have a simple login form consisting of username and password text fields.
I validate the login form using javascript external file and if javascript code returns true, login form is submitted otherwise an error message is displayed via javascript function named displayErrorBlock() that i wrote.
If the form is submitted then using PHP, i verify username and password. If username/password combination is incorrect or doesn't exists in database, i want to call the same javascript function (displayErrorBLock) from PHP code.
To do this, i echo this
else { // if username/password combination is incorrect
echo '<script>displayErrorBlock("Incorrect Username/Password")</script>';
}
but this gives me displayErrorBLock undefined error because javascript is loaded at the end of the body tag of my web page.
Question
How can i call javascript function (displayErrorBlock) that is defined in an external file ?
This is the displayErrorBlock function defined in an external js file
function displayErrorBlock(errorMsg) {
'use strict';
let errorBlock = document.querySelector('.error-msg-block');
errorBlock.style.display = 'block';
errorBlock.firstElementChild.textContent = errorMsg;
setTimeout(function () {
errorBlock.style.height = '48px';
}, 10);
}
Edit
Here my entire web page
<?php
require 'DbConnection.php';
// if login button is clicked
if(isset($_POST['login-btn'])) {
$username = $_POST['username-field'];
$password = $_POST['password-field'];
verifyLoginCredentials($username, $password);
}
// verify admin login credentials
function verifyLoginCredentials($username, $password) {
global $dbConnect;
$query = 'SELECT full_name, username, password FROM admins WHERE username = ?';
$statement = $dbConnect->prepare($query);
if($statement) {
$statement->bind_param('s', $username);
$statement->execute();
$resultSet = $statement->get_result();
// since there will be only one row returned at max, no need of a loop
$row = $resultSet->fetch_assoc();
if($row != null) {
$adminFullName = $row['full_name'];
$adminUsername = $row['username'];
$adminPassword = $row['password'];
// if username/password is correct start session and store
// username, password, full name in the session and login
// admin to his account
if($username === $adminUsername && password_verify($password, $adminPassword)) {
session_start();
$_SESSION['current_admin_fullname'] = $adminFullName;
$_SESSION['current_admin_username'] = $adminUsername;
$_SESSION['current_admin_password'] = $adminPassword;
//take current admin to admin dashboard
header('Location:admin dashboard.php');
}
else { // if username/password combination is incorrect
echo '<script>displayErrorBlock("Incorrect Username/Password")</script>';
}
} else { // if username doesn't exists in the database
echo '<script>displayErrorBlock("Entered Username isn\'t registered")</script>';
}
}
}
?>
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="../Resources/Bootstrap v4.1/css/bootstrap.min.css"/>
<link rel="stylesheet" href="../CSS/admin login.css"/>
<link rel="stylesheet" href="../CSS/common.css"/>
<title>Admin Login</title>
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-sm-12 navbar-container">
<nav class="top-navbar">
<img src="../Resources/images/logo.png" alt="logo"/>
<p>Admin Panel</p>
</nav><!--end of navbar-->
</div><!--end of first column-->
</div><!--end of first row-->
<div class="row">
<div class="col-sm-4 login-form-container">
<p class="error-msg-block">
<span></span>
</p>
<form class="login-form" method="post" action="admin login.php" onsubmit="return validateForm()">
<p>Welcome Back!</p>
<div class="form-group username-group">
<label for="username-field">Username</label>
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text">
<img src="../Resources/images/envelope.png" alt="envelope image"/>
</div>
</div>
<input class="form-control" id="username-field" type="text" name="username-field" id="username-field" placeholder="Username"/>
</div>
</div><!--end of first form group-->
<div class="form-group password-group">
<label for="password-field">Password</label>
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text">
<img src="../Resources/images/lock.png" alt="lock image"/>
</div>
</div>
<input class="form-control" id="password-field" type="password" name="password-field" id="password-field" placeholder="Password"/>
</div>
</div><!--end of second form-group-->
<input type="submit" class="btn" id="login-btn" name="login-btn" value="Login"/>
</form><!--end of login form-->
</div><!--end of first column-->
</div><!--end of second row-->
</div><!--end of container-->
<!--CDN versions of JQuery and Popper.js-->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js" integrity="sha384-cs/chFZiN24E4KMATLdqdvsezGxaGsi4hLGOzlXwp5UZB1LY//20VyM2taTB4QvJ" crossorigin="anonymous"></script>
<script src="../Resources/Bootstrap v4.1/js/bootstrap.min.js"></script>
<script src="../Javascript/admin login form validation.js"></script>
</body>
</html>
Updated Question
I am facing a couple of problems.
I am getting whole web page as a response when i try to log to log .responseText to console inside .onLoad method.
When form is submitted via ajax, main if statement in php file
if(isset($_POST['login-btn'])) {....}
never evaluates to true, hence php code isn't executing.
What am i doing wrong here?
Here's my php code
<?php
require 'DbConnection.php';
// if login button is clicked
if(isset($_POST['login-btn'])) {
$username = $_POST['username-field'];
$password = $_POST['password-field'];
echo '<script>alert(\'form submitted\')</script>'; <---- this alert is never invoked
verifyLoginCredentials($username, $password);
}
// verify admin login credentials
function verifyLoginCredentials($username, $password) {
global $dbConnect;
$query = 'SELECT full_name, username, password FROM admins WHERE username = ?';
$statement = $dbConnect->prepare($query);
if($statement) {
$statement->bind_param('s', $username);
$statement->execute();
$resultSet = $statement->get_result();
// since there will be only one row returned at max, no need of a loop
$row = $resultSet->fetch_assoc();
if($row != null) {
$adminFullName = $row['full_name'];
$adminUsername = $row['username'];
$adminPassword = $row['password'];
// if username/password is correct start session and store
// username, password, full name in the session
if($username === $adminUsername && password_verify($password, $adminPassword)) {
session_start();
$_SESSION['current_admin_fullname'] = $adminFullName;
$_SESSION['current_admin_username'] = $adminUsername;
$_SESSION['current_admin_password'] = $adminPassword;
}
else { // if username/password combination is incorrect
echo 'Incorrect Username/Password Combination';
}
} else { // if username doesn't exists in the database
echo 'Entered username isn\'t registered';
}
} else {
echo 'Error while preparing sql query';
}
}
?>
Here's my relevant javascript code
let loginForm = document.querySelector('.login-form');
let usernameField = document.getElementById('username-field');
let passwordField = document.getElementById('password-field');
// submit login form to server using ajax
function ajaxFormSubmit() {
'use strict';
let ajaxRequest = new XMLHttpRequest();
let url = 'admin login.php';
// login form submitted on server successfully
ajaxRequest.onload = function () {
if (ajaxRequest.readyState === 4 && ajaxRequest.status === 200) {
console.log(ajaxRequest.responseText);
displayInfoMessage(ajaxRequest.responseText, 'success');
}
};
// error while login form submission on server
ajaxRequest.onerror = function () {
if (ajaxRequest.status !== 200) {
console.log(ajaxRequest.responseText);
displayInfoMessage(ajaxRequest.responseText, 'error');
}
};
ajaxRequest.open('POST', url, true);
ajaxRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
ajaxRequest.send(new FormData(loginForm));
}
function validateForm(e) {
'use strict';
// prevent form submission
e.preventDefault();
if (anyEmptyField()) {
displayInfoMessage('Please fill all the empty fields', 'error');
highLightEmptyFields();
//return false;
return;
}
// check if username is in right format
if (!(regexTester(/^[A-Za-z0-9_]+$/g, usernameField.value))) {
displayInfoMessage('Username not valid', 'error');
highLightTextField(usernameField);
//return false;
return;
}
// check if username is atleast 3 characters long
if (usernameField.value.length < 3) {
displayInfoMessage('Username should contain atleast 3 characters', 'error');
highLightTextField(usernameField);
//return false;
return;
}
// check if password is in right format
if (!(regexTester(/^[A-Za-z0-9_]+$/g, passwordField.value))) {
displayInfoMessage('Password not valid', 'error');
highLightTextField(passwordField);
//return false;
return;
}
// check if password is atleast 6 characters long
if (passwordField.value.length < 6) {
displayInfoMessage('Password should contain atleast 6 characters', 'error');
highLightTextField(passwordField);
//return false;
return;
}
//return true;
// submit form information to server via ajax
ajaxFormSubmit();
}
// add submit event listener on login form
loginForm.addEventListener('submit', validateForm);
Inside the <head></head> elements of your HTML structure, add the following code:
<script type="text/javascript">
// Wait for the document to load
document.addEventListener("DOMContentLoaded", function(event) {
// Add event listener to form submit
document.querySelector(".login-form").addEventListener("submit", function(e) {
// Prevent the form from being submitted
e.preventDefault();
// Perform displayErrorBlock() function
validateForm();
// Create native XMLHttpRequest object
var xhr = new XMLHttpRequest();
// Set POST request header leaving second parameter empty because PHP
// code is in the same file.
xhr.open('POST', '');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
// Everything was ok, handle response
if (xhr.readyState === 4 && xhr.status === 200) {
// Succesful login. Redirect user
if(xhr.responseText === 'succes'){
window.location.replace("https://your_website.com/admin dashboard.php");
}
// Wrong username / password
else if(xhr.responseText === 'errorUserPass'){
displayErrorBlock("Incorrect Username/Password");
}
// User doesn't exist
else if(xhr.responseText === 'errorNotRegistered'){
displayErrorBlock("Entered Username isn't registered");
}
// Something else was returned by PHP
else {
displayErrorBlock("Unknown error: "+ xhr.responseText);
}
}
// Request failed, alert error
else if (xhr.status !== 200) {
alert('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send(new FormData(document.querySelector(".login-form")));
});
});
</script>
I've commented on most lines to explain what they do. Next you'll have to change your form to:
<form class="login-form" method="post" action="">
As we've created a custom event handler on the form, everything is controlled from there. So it's no longer needed to do this in your HTML structure.
Lastly you'll need to change your PHP code in such a way that it returns the correct responses:
Replace: header('Location:admin dashboard.php'); with echo 'succes';
Replace: echo '<script>displayErrorBlock("Incorrect Username/Password")</script>'; with echo 'errorUserPass';
Replace: echo '<script>displayErrorBlock("Entered Username isn\'t registered")</script>'; with echo 'errorNotRegistered';
As I said in the comments, it's been a while since I did this in native JS. I was unable to actually test this code, so let me know if something is wrong. Or at least it should help you into the right direction.
Related
I have a php file that retrieves information entered in an html form and saves it into a mysql db. The problem I am facing is that I cannot figure out how to stop the page from redirecting to insertinfo.php. I want the user to stay on the same index.html page where a modal will appear on form submission. Below is my index.html and insertinfo.php
The index.html file:
<div class="form ">
<form class="container" action="insertinfo.php">
<input type="text" id="firstname" class="form_input" placeholder="First Name" name="firstname" required>
<input type="text" id="lastname" class="form_input" placeholder="Last Name" name="lastname" required>
<input type="text" id="email" class="form_input" placeholder="Email Address" name="email" required>
<input type="submit" id="myBtn" class="submit" value="Download eBook">
</form>
</div>
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<div class="modal-header">
<div class="icon-box">
<i class="material-icons">check</i>
</div>
</div>
<div class="modal-body">
<h4>An email with a download link towards the eBook has been sent to you.</h4>
<p>Please check your inbox and your spam/bulk messages.</p>
Continue
</div>
</div>
</div>
<script type="text/javascript">
var modal = document.getElementById("myModal");
// Get the button that opens the modal
var btn = document.getElementById("myBtn");
// When the user clicks the button, open the modal
btn.onclick = function(event) {
var fnameInput = document.getElementById("firstname").value;
var lnameInput = document.getElementById("lastname").value;
var emailInput = document.getElementById("email").value;
if(fnameInput.length == 0 || lnameInput.length == 0 || emailInput.length == 0){
event.preventDefault();
alert("You must complete all existing fields");
} else {
modal.style.display = "block";
}
}
</script>
The insertinfo.php:
if (isset($_POST["submit"])){
// Escape user inputs for security
$first_name = $conn->real_escape_string($_REQUEST['firstname']);
$last_name = $conn->real_escape_string($_REQUEST['lastname']);
$email = $conn->real_escape_string($_REQUEST['email']);
$date_added = 'NOW()';
$sql = "INSERT INTO userinfo (firstname, lastname, email, date_added) "
. "VALUES ('$first_name', '$last_name', '$email', $date_added )";
if ($conn->query($sql) === TRUE) {
echo 'not working';
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
If you want your user to be index.html and submit the form to other php file then you will need to use ajax post request to the insertinfo.php. Ajax can post form data and retrieve PHP processed response
This is a example how you can submit the form with ajax
$(document).ready(function() {
// process the form
$('form').submit(function(event) {
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData = {
'name' : $('input[name=name]').val(),
'email' : $('input[name=email]').val(),
'superheroAlias' : $('input[name=superheroAlias]').val()
};
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'process.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
// here we will handle errors and validation messages
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
The action form attribute describes where the <form> is going to be submitted to.
If you remove it, the form will submit to the current page.
So deleting this part: action="insertinfo.php" will stop the <form> from redirecting you to insertinfo.php
If you still want to submit your data to insertinfo.php without reloading, use an ajax library or check out: How to use XMLHttpRequest.
I have a login form which is validated using javascript and then sent to php file for further processing. Form is submitted via ajax.
Currently, i have an if statement in php file that checks whether form has been submitted, problem is this if statement never evaluates to true. Hence my php code inside my if statement never runs. When request is sent via ajax, .onload event gets invoked without if statement inside php file evaluating to true.
Question
Once the form is submitted to php file via ajax, how can i detect in php file that form has been submitted via javascript.
Here's my php code
<?php
require 'DbConnection.php';
// if form is submitted
if(isset($_POST['login-btn'])) {
$username = $_POST['username-field'];
$password = $_POST['password-field'];
echo '<script>alert(\'form submitted\')</script>';
verifyLoginCredentials($username, $password);
} else {
echo '<script>alert(\'form not submitted\')</script>';
}
// verify admin login credentials
function verifyLoginCredentials($username, $password) {
global $dbConnect;
$query = 'SELECT full_name, username, password FROM admins WHERE username = ?';
$statement = $dbConnect->prepare($query);
if($statement) {
$statement->bind_param('s', $username);
$statement->execute();
$resultSet = $statement->get_result();
// since there will be only one row returned at max, no need of a loop
$row = $resultSet->fetch_assoc();
if($row != null) {
$adminFullName = $row['full_name'];
$adminUsername = $row['username'];
$adminPassword = $row['password'];
// if username/password is correct start session and store
// username, password, full name in the session
if($username === $adminUsername && password_verify($password, $adminPassword)) {
session_start();
$_SESSION['current_admin_fullname'] = $adminFullName;
$_SESSION['current_admin_username'] = $adminUsername;
$_SESSION['current_admin_password'] = $adminPassword;
}
else { // if username/password combination is incorrect
echo 'Incorrect Username/Password Combination';
}
} else { // if username doesn't exists in the database
echo 'Entered username isn\'t registered';
}
} else {
echo 'Error while preparing sql query';
}
}
?>
and here's relevant javascript code
let loginForm = document.querySelector('.login-form');
let usernameField = document.getElementById('username-field');
let passwordField = document.getElementById('password-field');
// submit login form to server using ajax
function ajaxFormSubmit() {
'use strict';
let ajaxRequest = new XMLHttpRequest();
let url = 'admin login.php';
// login form submitted on server successfully
ajaxRequest.onload = function () {
if (ajaxRequest.readyState === 4 && ajaxRequest.status === 200) {
console.log(ajaxRequest.responseText);
displayInfoMessage(ajaxRequest.responseText, 'success');
}
};
// error while login form submission on server
ajaxRequest.onerror = function () {
if (ajaxRequest.status !== 200) {
console.log(ajaxRequest.responseText);
displayInfoMessage(ajaxRequest.responseText, 'error');
}
};
ajaxRequest.open('POST', url, true);
ajaxRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
ajaxRequest.send(new FormData(loginForm));
}
function validateForm(e) {
'use strict';
// prevent form submission
e.preventDefault();
if (anyEmptyField()) {
displayInfoMessage('Please fill all the empty fields', 'error');
highLightEmptyFields();
//return false;
return;
}
// check if username is in right format
if (!(regexTester(/^[A-Za-z0-9_]+$/g, usernameField.value))) {
displayInfoMessage('Username not valid', 'error');
highLightTextField(usernameField);
//return false;
return;
}
// check if username is atleast 3 characters long
if (usernameField.value.length < 3) {
displayInfoMessage('Username should contain atleast 3 characters', 'error');
highLightTextField(usernameField);
//return false;
return;
}
// check if password is in right format
if (!(regexTester(/^[A-Za-z0-9_]+$/g, passwordField.value))) {
displayInfoMessage('Password not valid', 'error');
highLightTextField(passwordField);
//return false;
return;
}
// check if password is atleast 6 characters long
if (passwordField.value.length < 6) {
displayInfoMessage('Password should contain atleast 6 characters', 'error');
highLightTextField(passwordField);
//return false;
return;
}
//return true;
// submit form information to server via ajax
ajaxFormSubmit();
}
// add submit event listener on login form
loginForm.addEventListener('submit', validateForm);
There is no guaranteed way to know that the form was submitted via ajax.
Normally this is done via headers, in our case HTTP_X_REQUESTED_WITH which can be retrieved via the global $_SERVER variable.
Do note that headers can easily be spoofed.
You can check like so:
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{
// code here
}
Here's a few links to look at:
https://paulund.co.uk/use-php-to-detect-an-ajax-request
How to check if the request is an AJAX request with PHP
I have a really simple login form that I want to check if the credentials are right (so I don't have to reload a page if the credentials are wrong) before submitting the form.
The problem I'm running into is the response from the AJAX call. When the program decides that the user has supplied the correct credentials, this code works like a charm. In addition, when performing the two checks prior to the AJAX call (whether the user filled in the password input field or if the username is valid), the code works perfectly. It returns an error message and returns the false boolean value, preventing the form from submitting. But, when the response from the server comes back and it is found that the credentials are not correct, the error message displays, but the page also reloads (therein displaying an additional error message). Why is the form still submitting, even though I'm returning false? I've checked the JavaScript console, there are no errors. I've also tried inverting the if statement, checking if ajax.responseText === "true", to the same result. I've tried adding a return false beneath the ajax.onreadystatechange call, but that just prevents the form from submitting at all (regardless of the response from the server).
Here is the form code:
<form method="POST" action="/afton/" onsubmit="return checkForm()">
<label for="username">Username:</label>
<input type='text' id='username' name='username' placeholder='Enter username...' required>
<label for="password">Password:</label>
<input type='password' id='password' name='password' placeholder='Enter password...' required>
<div class="form-buttons">
<button type='submit' name='action' id="loginButton" value='login'>Login</button>
<button type='button' id='register'>Register</button>
</div>
</form>
Here is the js function:
// Function that checks whether the user supplied correct credentials
function checkForm() {
// Get the password provided and the server message div on the page
const messageBox = document.getElementById("server-message");
const password = document.getElementById("password").value;
// If password is blank, return error message and return false
if (password === "") {
messageBox.innerHTML = "<p class='badMessage'>Please fill in the password!</p>"
return false;
}
// If the username input tag doesn't contain the 'goodBorder' class received upon validation of username, return error and false
if (!usernameInput.classList.contains("goodBorder")) {
messageBox.innerHTML = "<p class='badMessage'>Please provide a valid username!</p>"
return false;
}
// AJAX call that posts the info via JSON to check
const ajax = new XMLHttpRequest();
ajax.open("POST", "index.php?action=ajaxLogCheck", true);
ajax.setRequestHeader("Content-type", "application/json");
ajax.send(JSON.stringify({"username":usernameInput.value, "password":password}));
// Handles the AJAX response
ajax.onreadystatechange = function () {
if (ajax.readyState === 4 && ajax.status === 200) {
if (ajax.responseText !== "true") {
messageBox.innerHTML = ajax.responseText;
return false;
}
return true
}
}
}
And here is the PHP code that handles the AJAX:
// Get posted JSON encoded data
$data = json_decode(trim(file_get_contents("php://input")), true);
// Filter and sanitize the supplied username and password
$username = filter_var($data['username'], FILTER_SANITIZE_STRING);
$password = filter_var($data['password'], FILTER_SANITIZE_STRING);
// Get user data by the username and check the username against the password
$userData = getClient($username);
$hashCheck = password_verify($password, $userData['password']);
// Check response from the hashCheck and return the result
if ($hashCheck) {
echo "true";
exit;
}
logAtt($username, $_SERVER['REMOTE_ADDR'], false, getBrowser($_SERVER['HTTP_USER_AGENT']));
sleep(0.5);
$rands = array("Sorry, the username and/or password doesn't match our database. Please try again.", "Sorry, we don't recognize those login credentials. Please try again.", "Sorry, that login was incorrect. Please try again.", "Incorrect, please try again");
$randResult = array_rand(array_flip($rands));
echo "<p class='badMessage'>$randResult</p>";
// Just the point in AJAX function where you were returning True or
// False...Just Assign RESULT = 0 for False and
// RESULT = 1 for True
// .....SUppose You password matches so you were returning True..
// Dont do that...Instead Just Assign RESULT = 0 in that place and
// and out of the ajax Block paste this 'return Boolean(RESULT)'
// if RESULT = 0 then it will return False else it will return True
// Function that checks whether the user supplied correct credentials
function checkForm()
{
// Initialize a Variable Here Say RESULT
var RESULT = 0;
if (password === "")
{
RESULT = 0;
}
else if (!usernameInput.classList.contains("goodBorder"))
{
messageBox.innerHTML = "<p class='badMessage'>Please provide a valid username!</p>"
RESULT = 0;
}
// After this Put the ajax function and if you want to return False
// then simply assign RESULT = 0 instead of 'return false' else assign
// RESULT = 1 instead of 'return true'
return Booelan(RESULT);
// THis line is main Part this is returned by checkForm() function
}
// If I am still not clear, then I'll be happy to explain it on Google Meet.! :)
Q. Is there a way to pass values from ajax to a certain php class having functions? Let's say validating a username on the registration form whether the user exist or not.
This is a simple form that will accept username and has a span tag to display the message.
<form action="" method="POST">
<input type="text" name="username"><span class="check"></span>
<input type="submit" name="signup">
</form>
And for the php class:
<?php
class User {
function isUserExist($username) {
$query = mysql_query("SELECT username FROM users WHERE username='$username'");
$result = mysql_num_rows($query);
return ($result !== 0 ? true : false);
}
}
?>
It is initialized on the php class that established connection to the database.
So calling to the php page will become like this: $user->isUserExist($_POST['username']);.
So is it possible to pass values from the form to ajax and send it to the php class function?
From Html to ajax
var username = $("input[name='username']").value;
Fetch in ajax & Send it to php(server)
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
//set your span to this -> xhttp.responseText;
}
};
xhttp.open("POST", "your php script url", true);
xhttp.send("username="+username);
Receive it on the server(php)
$mUsername = $_POST['username'];
echo $mUsername;
Read this tutorial for more help
Tutorial on PHP + AJAX
Try this,
<script type="text/javascript">
$(document).ready(function(){
$("input[name = 'signup']").click(function(e) {
var username = $("input[name = 'username']").val();
$.ajax ({
url: "isUserExist_function_existing_file.php",
data: { username : username },
success: function( result ) {
if(result)
alert("Name allready Exist");
else
alert("Name available");
}
});
});
});
</script>
Howdie do,
I have a form that simply takes a username and email from a user. The input is sanitiazed via client and on the server side.
The script is sending the POST with no issue and it's returning the data as it should be as I've checked in the log. However, for some reason, the data isn't being displayed in the browser.
Code is below and I feel it's a stupid item I'm overlooking, but I can't find it anywhere
<!DOCTYPE HTML>
<HEAD>
<TITLE>Jeremy's Form Submit Test </TITLE>
<script type="text/javascript" src="js/jquery-1.11.2.js"></script>
<script>
$(document).ready(function()
{
$("#FormSubmit").click(function() //Set click action on formsubmit button
{
var submit = true;
$('#MainForm input[type="text"]').each(function() //Loop through input fields to ensure data is present
{
if($.trim($('#User').val()) == '') //Remove whitespaces and check if field is empty
{
alert('Input can not be blank');
submit = false;
}
var regex = /^[\w-\.]+#([\w-]+\.)+[\w-]{2,4}$/; //RegEx to test email against
if(!regex.test($.trim($('#Email').val()))) //If supplied email without whitespaces doesn't match pattern, then alert user
{
alert('Please provide a valid email');
submit = false;
}
});
if(submit == true) //If data is present, then prepare email and user values to be submitted to .php page
{
data = {'user_name': $('#User').val(), 'email': $('#Email').val()}; //Add username and email to array
$.post("success.php", data, function(ReturnedData) //post data via ajx to success.php and retrieve response
{
console.log(JSON.stringify(ReturnedData));
if(ReturnedData.Type == 'Error') //If error returned, display error message
{
var results = '<h1>'+ReturnedData.Message+'</h1>';
}
else if(ReturnedData.Type == 'Success') //If success returned, display message and remove submit button
{
var results = '<h1>'+ReturnedData.Message+'</h1>';
$('#FormSubmit').remove();
}
$('div#DataHolder').html(results);
}, 'json');
}
});
});
</script>
</HEAD>
<BODY>
<form id="MainForm">
*UserName: <input type="text" id="User" name="FormUsername" required />
*Email: <input type="email" id="Email" name="FormEmail" required />
<input type="submit" id="FormSubmit" value="Submit">
</form>
<div id="DataHolder"></div>
</BODY>
</HTML>
The PHP file is below that returns a json_encoded response and I've confirmed via the console log that the data is being returned properly, but it's not displaying in the div I've set. The log file is showing the correct response, but it's not displaying:
{"Type":"Error","Message":"UserName must be at least 3 characters!!!"}
<?php
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') //Check apache header to ensure its a json request
{
$ReturnedData = json_encode(array("Type" => "Error", "Message" => "Naughty naughty. This wasn't an ajax request"));
die($ReturnedData);
}
if(isset($_POST)) //Ensure that POST is set
{
//Santiaze the post variables to be double sure no one is up to any funky business
$SaniUser = filter_var($_POST['user_name'],FILTER_SANITIZE_STRING);
$SaniEmail = filter_var($_POST['email'],FILTER_SANITIZE_EMAIL);
//Check that username is at least 3 characters and return error if it's not
if(strlen($SaniUser) != 3)
{
$ReturnedData = json_encode(array("Type" => "Error", "Message" => "UserName must be at least 3 characters!!!"));
die($ReturnedData);
}
//Check that email is a valid email
if(!filter_var($SaniEmail,FILTER_VALIDATE_EMAIL))
{
$ReturnedData = json_encode(array("Type" => "Error", "Message" => "Please supply a valid email address!!!"));
die($ReturnedData);
}
//All variables are good. Return successfully message
$ReturnedData = json_encode(array("Type" => "Success", "Message" => "SUCCESS!!!" .$SaniUser. "Has successfully submitted the form"));
die($ReturnedData);
}
else
{
$ReturnedData = json_encode(array("Type" => "Error", "Message" => "Naughty naughty. No data was submitted!!!"));
die($ReturnedData);
}
?>
WOWOWOW the issue was staring me right in the face.
I didn't initialize var results initially when the data is present. So when I called .html(results), the result variable scope was only in the if/else statement.
Setting the variable at the top of the if statement and then setting the returnedData to that value works
Updated code is below:
if(submit == true) //If data is present, then prepare email and user values to be submitted to .php page
{
var results;
data = {'user_name': $('#User').val(), 'email': $('#Email').val()}; //Add username and email to array
$.post("success.php", data, function(ReturnedData) //post data via ajx to success.php and retrieve response
{
console.log(JSON.stringify(ReturnedData));
if(ReturnedData.Type == 'Error') //If error returned, display error message
{
results = '<h1>'+ReturnedData.Message+'</h1>';
//alert(ReturnedData.Message);
}
else if(ReturnedData.Type == 'Success') //If success returned, display message and remove submit button
{
$('#FormSubmit').hide();
results = '<h1>'+ReturnedData.Message+'</h1>';
}
$('#DataHolder').html(results);
}, 'json');
}