Synchronous XMLHttpRequest on the main thread is deprecated AJAX - javascript

I am having this error in my console that is preventing my validation in two different forms in AJAX Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user’s experience.. My forms are working fine but this console log is bothering me.
I'll only add in code in the scripts to avoid confusion.
These are the two forms (onblur invokes the ajax validation)
edit.blade.php
<div class="main-content">
<!-- You only need this form and the form-basic.css -->
<form class="form-basic" method="post" id="myEditForm" action="/edit">
<div class="form-title-row">
<h1>Edit User</h1>
</div>
<input type="hidden" name="userid" id="editFormUserId">
<div class="form-row">
<label>
<span>Firstname</span>
<input type="text" name="firstname" id="editFormFirstName" onblur="validateEditForm('divfirstnameEditForm', this.value)">
</label>
</div>
<div id="divfirstnameEditForm"></div>
<div class="form-row">
<label>
<span>Lastname</span>
<input type="text" name="lastname" id="editFormLastName" onblur="validateEditForm('divlastnameEditForm', this.value)">
</label>
</div>
<div id="divlastnameEditForm"></div>
<div class="form-row">
<label>
<span>Password</span>
<input type="password" name="password" id="editFormPassword" onblur="validateEditForm('divpasswordEditForm', this.value)">
</label>
</div>
<div id="divpasswordEditForm"></div>
<div class="form-row">
<input class="button" type="button" onclick="fetchUser()" value="Submit" />
<input type="hidden" name="_token" value="{{ csrf_token() }}">
</div>
</form>
</div>
create.blade.php
<div class="main-content">
<!-- You only need this form and the form-basic.css -->
<form class="form-basic" method="post" id="myForm" action="/create">
<div class="form-title-row">
<h1>Create User</h1>
</div>
<div class="form-row">
<label>
<span>Firstname</span>
<input type="text" name="firstname" id="firstname1" onblur="validate('firstname', this.value)">
</label>
</div>
<div id="firstname"></div>
<div class="form-row">
<label>
<span>Lastname</span>
<input type="text" name="lastname" id="lastname1" onblur="validate('lastname', this.value)">
</label>
</div>
<div id="lastname"></div>
<div class="form-row">
<label>
<span>Password</span>
<input type="password" name="password" id="password1" onblur="validate('password', this.value)">
</label>
</div>
<div id="password"></div>
<div class="form-row">
<input class="button" onclick="checkForm()" type="button" value="Submit" />
<input type="hidden" name="_token" value="{{ csrf_token() }}">
</div>
</form>
</div>
scripts.js (contains fetchuser, checkform, validation methods for each form)
//start of checkuser
function fetchUser() {
console.log('fetchuser');
//fetch values from edit blade
var firstname = document.getElementById("editFormFirstName").value;
var lastname = document.getElementById("editFormLastName").value;
var password = document.getElementById("editFormPassword").value;
//Check input Fields Should not be blanks.
if (firstname == '' || lastname == '' || password == '') {
alert("Fill All Fields");
} else {
//Notifying error fields
var firstname = document.getElementById("divfirstnameEditForm");
var lastname = document.getElementById("divlastnameEditForm");
var password = document.getElementById("divpasswordEditForm");
//Check All Values/Informations Filled by User are Valid Or Not.If All Fields Are invalid Then Generate alert.
if (firstname.innerHTML == 'Firstname must be 2+ letters' || lastname.innerHTML == 'Lastname name must be 2+ letters' || password.innerHTML == 'Must be a combination of special character, number and letters') {
alert("Fill Valid Information");
} else {
//Submit Form When All values are valid.
document.getElementById("myEditForm").submit();
}
}
}
//end of checkuser
//checkform validation
function checkForm() {
console.log('checkform');
// Fetching values from all input fields and storing them in variables.
var firstname = document.getElementById("firstname1").value;
var lastname = document.getElementById("lastname1").value;
var password = document.getElementById("password1").value;
//Check input Fields Should not be blanks.
if (firstname == '' || lastname == '' || password == '') {
alert("Fill All Fields");
} else {
//Notifying error fields
var firstname = document.getElementById("firstname");
var lastname = document.getElementById("lastname");
var password = document.getElementById("password");
//Check All Values/Informations Filled by User are Valid Or Not.If All Fields Are invalid Then Generate alert.
if (firstname.innerHTML == 'Firstname must be 2+ letters' || lastname.innerHTML == 'Lastname name must be 2+ letters' || password.innerHTML == 'Must be a combination of special character, number and letters') {
alert("Fill Valid Information");
} else {
//Submit Form When All values are valid.
document.getElementById("myForm").submit();
}
}
}
// AJAX code to check input field values when onblur event triggerd.
function validate(field, query) {
var xmlhttp;
if (window.XMLHttpRequest) { // for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState != 4 && xmlhttp.status == 200) {
document.getElementById(field).innerHTML = "Validating..";
} else if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById(field).innerHTML = xmlhttp.responseText;
} else {
document.getElementById(field).innerHTML = "Error Occurred. <a href='index.php'>Reload Or Try Again</a> the page.";
}
}
xmlhttp.open("GET", "/php/validation.php?field=" + field + "&query=" + query, false);
xmlhttp.send();
}
// AJAX code to check input field values when onblur event triggerd.
function validateEditForm(field, query) {
var xmlhttp;
if (window.XMLHttpRequest) { // for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState != 4 && xmlhttp.status == 200) {
document.getElementById(field).innerHTML = "Validating..";
} else if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById(field).innerHTML = xmlhttp.responseText;
} else {
document.getElementById(field).innerHTML = "Error Occurred. <a href='index.php'>Reload Or Try Again</a> the page.";
}
}
xmlhttp.open("GET", "/php/validationEditForm.php?field=" + field + "&query=" + query, false);
xmlhttp.send();
}
Can you help me why it is showing up in my log?

You can either remove the last boolean value:
xmlhttp.open("Method", "URL");
or just use the true:
xmlhttp.open("Method", "URL", true);
From the docs at MDN:
An optional Boolean parameter, defaulting to true, indicating whether or not to perform the operation asynchronously. If this value is false, the send() method does not return until the response is received. If true, notification of a completed transaction is provided using event listeners. This must be true if the multipart attribute is true, or an exception will be thrown.

Related

Validating form from ajax call with php

I have a farm that loads when an option is seleceted with ajax call, however i want to validate my form, immediately when i submit, it and there is error upon validation, the ajax called form dissapears.
This is my ajax
<script>
function salesType(str) {
if (str == "") {
document.getElementById("txtHint2").innerHTML = "";
return;
} else {
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 = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint2").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","showsalestype.php?&q="+str,true);
xmlhttp.send();
e.preventDefault();
}
}
</script>
my php
$q = $_GET['q'];
if($q == 'POS'){ ?>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12">POS Referece No <span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input id="atmref" name="atmref" class="form-control col-md-7 col-xs-12" type="text" value=" ">
</div>
<p><font size="2" color="#ff0000"> <?php echo $form->error("atmref"); ?> </font></p>
</div>
<?php } ?>
How do i prevent the ajax call to remain upon validation error

Trying to use PHP and Ajax to do form validation, not working

I have been trying to figure out how to do php form validation and using ajax to get the results back so I don't have to refresh page. I'm new to ajax and having a hard time.
This is my registration.php form
<h1>Sign Up</h1>
<form id="registration_form" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="first_name">First name</label>
<input type="text" class="form-control" id="first_name" name="first_name" onblur="validate('first_name', this.value)" placeholder="First name">
</div>
</div>
<div id="textFirstName" class="col-md-6">
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="last_name">Last name</label>
<input type="text" class="form-control" id="last_name" name="last_name" onblur="validate('last_name', this.value)" placeholder="Last name">
</div>
</div>
<div id="textLastName" class="col-md-6">
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="email1">Email address</label>
<input type="email" class="form-control" id="email1" name="email1" onblur="validate('email1', this.value)" placeholder="Email">
</div>
</div>
<div id="textEmail" class="col-md-6">
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="Password1">Password</label>
<input type="password" class="form-control" id="password1" name="password1" onblur="validate('password1', this.value)" placeholder="Password">
</div>
</div>
<div id="textPass1" class="col-md-6">
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="Password2">Confirm Password</label>
<input type="password" class="form-control" id="password2" name="password2" onblur="validate('password2', this.value)" placeholder="Retype Password">
</div>
</div>
<div id="textPass2" class="col-md-6">
</div>
</div>
<div class="row">
<div class="col-md-6">
<button type="submit" class="btn btn-default">Submit</button>
</div>
<div class="col-md-6">
</div>
</div>
</form>
This is my validation php script:
<?php
$value = $_POST['query'];
$formfield = $_POST['field'];
// Check Valid or Invalid first name when user enters user name in username input field.
if ($formfield == "first_name") {
if (strlen($value) < 1) {
echo "<p style=\"color:red\">Error: Must be 1+ letters</p>";
} else {
echo "<p style=\"color:green\">Valid</p>";
$_SESSION['reg']['first_name'] = $value;
}
}
if ($formfield == "last_name") {
if (strlen($value) < 1) {
echo "<p style=\"color:red\">Error: Must be 1+ letters</p>";
} else {
echo "<p style=\"color:green\">Valid</p>";
$_SESSION['reg']['last_name'] = $value;
}
}
// Check Valid or Invalid password when user enters password in password input field.
if ($formfield == "password1") {
if (strlen($value) < 8) {
echo "<p style=\"color:red\">Error: Password too short. Must be at least 8 characters long, contain one lower case letter, one uppercase letter, and one number.</p>";
}
else if (!preg_match("#.*^(?=.{8,20})(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).*$#", $value)){
echo "<p style=\"color:red\">Error: Your password must be at least 8 characters long, contain one lower case letter, one uppercase letter, and one number.</p>";
}
else {
echo "<p style=\"color:green\">Your password is good.</p>";
$_SESSION['reg']['password1'] = $value;
}
}
if ($formfield == "password2") {
if (strlen($value) < 8) {
echo "<p style=\"color:red\">Error: Password too short. Must be at least 8 characters long, contain one lower case letter, one uppercase letter, and one number.</p>";
}
else if (!preg_match("#.*^(?=.{8,20})(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).*$#", $value)){
echo "<p style=\"color:red\">Error: Your password must be at least 8 characters long, contain one lower case letter, one uppercase letter, and one number.</p>";
}
else if ($_SESSION['password1'] != $value) {
echo "<p style=\"color:red\">Error: Your passwords don't match.</p>";
}
else {
echo "<p style=\"color:green\">Your password is good.</p>";
}
}
// Check Valid or Invalid email when user enters email in email input field.
if ($formfield == "email1") {
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $value)) {
echo "<p style=\"color:red\">Invalid email.</p>";
} else {
echo "<p style=\"color:red\">Valid</p>";
$_SESSION['reg']['email1'] = $value;
}
}
?>
And this is my javascript file with the ajax:
function checkForm() {
// Fetching values from all input fields and storing them in variables.
var first_name = document.getElementById("first_name").value;
var last_name = document.getElementById("last_name").value;
var password1 = document.getElementById("password1").value;
var password2 = document.getElementById("password2").value;
var email = document.getElementById("email1").value;
//Check input Fields Should not be blanks.
if (first_name == '' || last_name == '' || password1 == '' || password2 == '' || email1 == '') {
alert("Fill All Fields");
} else {
//Notifying error fields
var textFirstName = document.getElementById("first_name");
var textLastName = document.getElementById("last_name");
var textPass1 = document.getElementById("password1");
var textPass2 = document.getElementById("password2");
var textEmail = document.getElementById("email1");
//Check All Values/Informations Filled by User are Valid Or Not.If All Fields Are invalid Then Generate alert.
str1 = textFirstName.innerHTML; str2 = textLastName.innerHTML; str3 = textPass1.innerHTML; str4 = textPass2.innerHTML; str5 = textEmail.innerHTML;
if (str1.substr(0,4) == 'Error' || str2.substr(0,4) == 'Error' || str3.substr(0,4) == 'Error' || str4.substr(0,4) == 'Error' || str5.substr(0,4) == 'Error') {
alert("Fill Valid Information");
} else {
//Submit Form When All values are valid.
document.getElementById("myForm").submit();
}
}
}
// AJAX code to check input field values when onblur event triggerd.
function validate(field, query) {
var xmlhttp;
if (window.XMLHttpRequest) { // for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState != 4 && xmlhttp.status == 200) {
document.getElementById(field).innerHTML = "Validating..";
} else if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById(field).innerHTML = xmlhttp.responseText;
} else {
document.getElementById(field).innerHTML = "Error Occurred. <a href='index.php'>Reload Or Try Again</a> the page.";
}
}
xmlhttp.open("POST", "lib/validate_registration_form.php?field=" + field + "&query=" + query, false);
xmlhttp.send();
}
When I enter values in the form there is no response regardless of whether i input valid or invalid information. I am sure the problem lies in the JS file with the ajax, but I don't know what it is. Any help would be greatly appreciated.
You have two issue :
First, in your html/javascript the onblur event calls
validate('first_name', this.value)
But there is not HTML element with ID = first_name, your div is called textFirstName
So you should change your onblur with proper parameter value such as
validate('textFirstName', this.value)
Next, you use POST method for your ajax but send your parameter in the URL which are stored in the $_GET array
Change :
<?php
$value = $_POST['query'];
$formfield = $_POST['field'];
To :
<?php
$value = $_GET['query'];
$formfield = $_GET['field'];
Final note : you may want to use isset($_GET['query']) in your php script to avoid notice message of undefined or at least a way to debug :
if (!isset($_GET['query']))
{
die ("missing parameter, report to admin that he should debug the JS");
}
EDIT
Following your comment, here is how to send POST data
var params = "field=" + field + "&query=" + query;
xmlhttp.open("POST", "lib/validate_registration_form.php", false);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.send(params);

What's the quickest way to build sign ups, logins and passwords for real users?

I'd like to learn how to password protect my sites, with custom login credentials that I chose.
Using custom html, css, and javascript to create the interface gets me to a point like this -> http://codepen.io/lexeckhart/pen/RPLPwX
But everything on that page is accessible to everyone. I risk being an idiot in saying I remember using php and mysql or sql to do the next part. Maybe.
To add onto the title question I would like to know is where I start creating this database? Can I do it with ftp?
HTML
<div id="successful_login" class="fix-middle">
<div class="container text-center">
<h1>Welcome back to the internet!</h1>
<p>You've successfully managed to log into a nonexistant account in order to test a login dialog box.<br> If you like it, you are welcomed to use it wherever you want, no strings attached.<br><br>Rerun the whole thing.</p>
</div>
</div>
<div id="successful_registration" class="fix-middle">
<div class="container text-center">
<h1>Welcome to the internet!</h1>
<p>You've successfully managed to register for a nonexistant account in order to test a registration dialog box.<br> If you like it, you are welcomed to use it wherever you want, no strings attached.<br><br>Rerun the whole thing.</p>
</div>
</div>
<div id="dialog" class="dialog dialog-effect-in">
<div class="dialog-front">
<div class="dialog-content">
<form id="login_form" class="dialog-form" action="" method="POST">
<fieldset>
<legend>Log in</legend>
<div class="form-group">
<label for="user_username" class="control-label">Username:</label>
<input type="text" id="user_username" class="form-control" name="user_username" autofocus/>
</div>
<div class="form-group">
<label for="user_password" class="control-label">Password:</label>
<input type="password" id="user_password" class="form-control" name="user_password"/>
</div>
<div class="text-center pad-top-20">
<p>Have you forgotten your<br><strong>username</strong> or <strong>password</strong>?</p>
</div>
<div class="pad-top-20 pad-btm-20">
<input type="submit" class="btn btn-default btn-block btn-lg" value="Continue">
</div>
<div class="text-center">
<p>Do you wish to register<br> for <strong>a new account</strong>?</p>
</div>
</fieldset>
</form>
</div>
</div>
<div class="dialog-back">
<div class="dialog-content">
<form id="register_form" class="dialog-form" action="" method="POST">
<fieldset>
<legend>Register</legend>
<div class="form-group">
<label for="user_username" class="control-label">Username:</label>
<input type="text" id="user_username" class="form-control" name="user_username"/>
</div>
<div class="form-group">
<label for="user_password" class="control-label">Password:</label>
<input type="password" id="user_password" class="form-control" name="user_password"/>
</div>
<div class="form-group">
<label for="user_cnf_password" class="control-label">Confirm password:</label>
<input type="password" id="user_cnf_password" class="form-control" name="user_cnf_password"/>
</div>
<div class="form-group pad-top-20 form-group-checkbox">
<div class="checkbox">
<label>
<input type="checkbox" id="user_terms" name="user_terms">
I have read and I agree with the Terms and Conditions
</label>
</div>
</div>
<div class="pad-btm-20">
<input type="submit" class="btn btn-default btn-block btn-lg" value="Continue"/>
</div>
<div class="text-center">
<p>Return to <strong>log in page</strong>?</p>
</div>
</fieldset>
</form>
</div>
</div>
</div>
JAVASCRIPT
// The "getFormData()" function retrieves the names and values of each input field in the form;
function getFormData(form) {
var data = {};
$(form).find('input, select').each(function() {
if (this.tagName.toLowerCase() == 'input') {
if (this.type.toLowerCase() == 'checkbox') {
data[this.name] = this.checked;
} else if (this.type.toLowerCase() != 'submit') {
data[this.name] = this.value;
}
} else {
data[this.name] = this.value;
}
});
return data;
}
// The "addFormError()" function, when called, adds the "error" class to the form-group that wraps around the "formRow" attribute;
function addFormError(formRow, errorMsg) {
var errorMSG = '<span class="error-msg">' + errorMsg + '</span>';
$(formRow).parents('.form-group').addClass('has-error');
$(formRow).parents('.form-group').append(errorMSG);
$('#dialog').removeClass('dialog-effect-in');
$('#dialog').addClass('shakeit');
setTimeout(function() {
$('#dialog').removeClass('shakeit');
}, 300);
}
// FORM HANDLER:
// form_name - This attribute ties the form-handler function to the form you want to submit through ajax. Requires an ID (ex: #myfamousid)
// custom_validation -
function form_handler(form_name, custom_validation, success_message, error_message, success_function, error_function) {
$(form_name).find('input[type="submit"]').on('click', function(e) { // if submit button is clicked
window.onbeforeunload = null; // cancels the alert message for unsaved changes (if such function exists)
$(form_name).find('.form-group .error-msg').remove();
var submitButton = this;
submitButton.disabled = true; // Disables the submit buttton until the rows pass validation or we get a response from the server.
var form = $(form_name)[0];
// The custom validation function must return true or false.
if (custom_validation != null) {
if (!custom_validation(form, getFormData(form))) {
submitButton.disabled = false;
return false;
}
}
e.preventDefault(); //STOP default action
});
$(document).click(function(e) { // Whenever the user clicks inside the form, the error messages will be removed.
if ($(e.target).closest(form_name).length) {
$(form_name).find('.form-group').removeClass('has-error');
setTimeout(function() {
$(form_name).find('.form-group .error-msg').remove();
}, 300);
} else {
return
}
});
}
// LOGIN FORM: Validation function
function validate_login_form(form, data) {
if (data.user_username == "") {
// if username variable is empty
addFormError(form["user_username"], 'The username is invalid');
return false; // stop the script if validation is triggered
}
if (data.user_password == "") {
// if password variable is empty
addFormError(form["user_password"], 'The password is invalid');
return false; // stop the script if validation is triggered
}
$('#dialog').removeClass('dialog-effect-in').removeClass('shakeit');
$('#dialog').addClass('dialog-effect-out');
$('#successful_login').addClass('active');
//return true;
}
// REGISTRATION FORM: Validation function
function validate_registration_form(form, data) {
if (data.user_username == "") {
// if username variable is empty
addFormError(form["user_username"], 'The username is invalid');
return false; // stop the script if validation is triggered
}
if (data.user_password == "") {
// if password variable is empty
addFormError(form["user_password"], 'The password is invalid');
return false; // stop the script if validation is triggered
}
if (data.user_cnf_password == "" || data.user_password != data.user_cnf_password) {
// if password variable is empty
addFormError(form["user_cnf_password"], "The passwords don't match");
return false; // stop the script if validation is triggered
}
if (!data.user_terms) {
// if password variable is empty
addFormError(form["user_terms"], "You need to read and accept the Terms and Conditions before proceeding");
return false; // stop the script if validation is triggered
}
$('#dialog').removeClass('dialog-effect-in').removeClass('shakeit');
$('#dialog').addClass('dialog-effect-out');
$('#successful_registration').addClass('active');
//return true;
}
form_handler("#login_form", validate_login_form, null, null, null, null, null, null);
form_handler("#register_form", validate_registration_form, null, null, null, null, null, null);
var dialogBox = $('#dialog');
dialogBox.on('click', 'a.user-actions', function() {
dialogBox.toggleClass('flip');
});
$('#successful_login,#successful_registration').on('click', 'a.dialog-reset', function() {
$('#successful_login,#successful_registration').removeClass('active');
dialogBox.removeClass('dialog-effect-out').addClass('dialog-effect-in');
document.getElementById('login_form').reset();
document.getElementById('register_form').reset();
});
Store the credentials in MySQL in a database table (hashed), access the database via php, redirect the user using either php or javascript.

why is ajax and php script not posting back into original form

I have this form and I'm using ajax to send data to a simple php script (just trouble shooting with simple php script) but it is not posting back data to original html form... here are the two scripts
contact.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>Contact Us</title>
<!-- Bootstrap -->
<link href="bootstrap.min.css" rel="stylesheet">
<!-- stylesheet for this form -->
<link href="contact-stylesheet.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<script type="text/javascript">
function validateForm()
{
var message = "";
var letters = /^[A-Za-z]+$/;
//do validation
var jname = document.forms["myForm"]["name"].value;
var jemail = document.forms["myForm"]["email"].value;
var jsubject = document.forms["myForm"]["subject"].value;
var jtext = document.forms["myForm"]["text"].value;
var joutputMsg = "";
//checking for empty fields
if (jname == null || jname == "") {
message += "name field empty!\n";
}
if (jname != "" && !jname.match(letters)) {
message += "Invalid name: only letters allowed!\n";
}
if (jemail == null || jemail == "") {
message += "email field is empty!\n";
}
if (jsubject == null || jsubject == "") {
message += "Subject field is empty!\n";
}
if (jtext == null || jtext == "") {
message += "Text field is empty!\n";
}
if (message != "" ) {
alert(message);
return false;
}
//send data to php form--------------------->
// create the XMLHttpRequest object, according browser
// create the variable that will contain the instance of the XMLHttpRequest object (initially with null value)
var xmlHttp = null;
if(window.XMLHttpRequest) { // for Forefox, IE7+, Opera, Safari, ...
xmlHttp = new XMLHttpRequest();
}
else if(window.ActiveXObject) { // for Internet Explorer 5 or 6
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
// sends data to a php file, via POST, and displays the received answer
// create pairs index=value with data that must be sent to server
var parameters="name="+jname+"&email="+jemail;
request.open("POST", "contact.php", true); // set the request
// adds a header to tell the PHP script to recognize the data as is sent via POST
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(the_data); // calls the send() method with datas as parameter
// Check request status
// If the response is received completely, will be transferred to the HTML tag with tagID
request.onreadystatechange = function() {
if (request.readyState == 4) {
document.getElementById("output-data").innerHTML = request.responseText;
}
}
return false;
}
</script>
</head>
<body>
<div class="row">
<div class="hero-unit" style="padding:20px 100px">
<h1>Contact Us</h1>
<p>aldkfjasdkfjaskdfasdfkasdkfjadsfjsdkfjaskfjasdkfjasjfaskdfjsdkfjsksdsdkjsd</p>
</div>
<div class="col-sm-6">
<div class="my-form">
<form class="form-horizontal" name="myForm" action="contact.php" onsubmit="return validateForm(event)" method="post">
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Name:</label>
<div class="col-sm-8">
<input type="name" name="name" class="form-control" id="inputEmail3" placeholder="Name">
</div>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-2 control-label">Email:</label>
<div class="col-sm-8">
<input type="email" name="email" class="form-control" id="inputPassword3" placeholder="Email">
</div>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-2 control-label">Subject:</label>
<div class="col-sm-8">
<input type="text" name="subject" class="form-control" placeholder="Subject">
</div>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-2 control-label">Text:</label>
<div class="col-sm-8">
<textarea name="text" class="form-control" rows="7" placeholder="Text"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">Send</button>
</div>
</div>
</div>
</form>
</div>
<div class="col-sm-6">
<div style="width:500px;heigth:350px;border:solid 1px brown">
<h1>GOOGLE MAP HERE!</h1>
</div>
<!-- <img sytle="padding:0px 20px" src="https://maps.googleapis.com/maps/api/staticmap?center=Miami+Downtown,Miami,FL&zoom=13&size=500x350&maptype=roadmap&markers=color:red%7CMiami+Downtown,Miami,FL"> -->
</div>
</div>
<div class="col-sm-6" id="msg-result" style="padding:10px 140px">
<p id="output-data">
</p>
<!-- display form result message here! -->
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>
</body>
</html>
contact.php
<?php
if (isset($_POST['name'])) {
$name = $_POST['name'];
}
if (isset($_POST['email'])) {
$email = $_POST['email'];
}
echo "Name: " . $name . "<br> Email: " . $email;
?>
There is so many errors but I've got it working, you might want to look at the naming convention on your input fields. For example on name you have the id of id="inputEmail13". Use the browser console to see error messages as you're developing.
function validateForm(event)
{
event.preventDefault();
var message = "";
var letters = /^[A-Za-z]+$/;
//do validation
var name = document.forms["myForm"]["name"].value;
var email = document.forms["myForm"]["email"].value;
var subject = document.forms["myForm"]["subject"].value;
var text = document.forms["myForm"]["text"].value;
var outputMsg = "";
//checking for empty fields
if (name == null || name == "") {
message += "name field empty!\n";
}
if (name != "" && !name.match(letters)) {
message += "Invalid name: only letters allowed!\n";
}
if (email == null || email == "") {
message += "email field is empty!\n";
}
if (subject == null || subject == "") {
message += "Subject field is empty!\n";
}
if (text == null || text == "") {
message += "Text field is empty!\n";
}
if (message != "" ) {
alert(message);
return false;
}
//send data to php form--------------------->
// create the XMLHttpRequest object, according browser
// create the variable that will contain the instance of the XMLHttpRequest object (initially with null value)
var xmlHttp = null;
if(window.XMLHttpRequest) { // for Forefox, IE7+, Opera, Safari, ...
xmlHttp = new XMLHttpRequest();
}
else if(window.ActiveXObject) { // for Internet Explorer 5 or 6
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
// sends data to a php file, via POST, and displays the received answer
// create pairs index=value with data that must be sent to server
var parameters="name="+name+"&email="+email;
xmlHttp.open("POST", "contact.php", true); // set the request
// adds a header to tell the PHP script to recognize the data as is sent via POST
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.send(parameters); // calls the send() method with datas as parameter
// Check request status
// If the response is received completely, will be transferred to the HTML tag with tagID
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
document.getElementById("output-data").innerHTML = xmlHttp.responseText;
}
}
return false;
}
In the html you want to remove the visibility:hidden; on the output div
<div class="col-sm-6" id="msg-result" style="padding:10px 140px;">
<p id="output-data">
</p>
<!-- display form result message here! -->
</div>
Edit:
Cause of the request is undefined is because you're never creating a variable called request, yet you're calling one.
request.open("POST", "contact.php", true);
This line will throw the first error saying it's undefined, this can be fixed easily by changing request to xmlHttp or modifying xmlHttp = new XMLHttpRequest(); to be request = new .... same should be done to the other xmlHttp assignment.

How to trigger AJAX from a search button

I have the following Javascript:
<script>
function showtickets(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
}
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "/processes/editticket.php?WTNum=" + str, true);
xmlhttp.send();
}
It works perfectly if I use a selectbox and trigger the function with "onchange". However, my client requested a searchbox instead. I cannot get it to work with a search box. Here is my HTML for the search box and the div where the results should go.
<form class='form-horizontal col-xs-12 col-md-12 col-lg-12' name="editticket" method="post" action="/processes/updateticket.php">
<div class='panel panel-primary'>
<div class='panel-heading'>
<h3 class='panel-title'>Edit Work Tickets</h3>
</div>
<div class='panel-body'>
<div class="input-group">
<span class="input-group-addon">Enter Ticket #</span>
<input type="text" class="form-control" id="search" name="WTNum" >
<span class="input-group-btn">
<button class="btn btn-default" type="button" onclick="showtickets(document.getElementById('search').value)">Search</button>
</span>
<div id="txtHint"><b></b></div>
</form>
Am I missing something!! This is driving me INSANE!!
Thank you all in advance. It is greatly appreciated.
Why not just call the showtickets function without arguments and then inside the function you do this
str = document.getElementById('search').value;
I think you must you javascript debug or alert in some scope to find where error

Categories

Resources