how to post and get response from server using ajax - javascript

I am designing a basic registration form in html and css, and on click of submit button the data will be adding into the server database through post method n accordingly the response will be display on same registration page with json object. For that purpose i am using javascript and ajax but its not working properly.
html
<div class="column1" style="background-color:lightgrey;">
<div class="form">
<div class="formdetail">
<h3>Individual Registration</h3>
<label for="fname"> Name</label><br>
<input type="text" size="40" id="name" name="name" placeholder="Enter your
name.." required><br><br>
<label for="phonenumber">Mobile Number</label>
<br/>
<input type="text" id="mobileno" name="mobileno" maxlength="13"
size="40" placeholder="Enter your mobile number..." class =
"numeric" /><br>
<span class="error" style="color: red; display: none">Input digits (0 -
9)</span>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
var specialKeys = new Array();
specialKeys.push(8); //Backspace
$(function () {
$(".numeric").bind("keypress", function (e) {
var keyCode = e.which ? e.which : e.keyCode
var ret = ((keyCode >= 48 && keyCode <= 57) ||
specialKeys.indexOf(keyCode) != -1);
$(".error").css("display", ret ? "none" : "inline");
return ret;
});
$(".numeric").bind("paste", function (e) {
return false;
});
$(".numeric").bind("drop", function (e) {
return false;
});
});
</script>
<br>
<label for="email">Email</label><br>
<input type="text" size="40" id="email" name="email" pattern="[^
#]*#[^ #]*" name="email" placeholder="Enter your email-id..."
required><br><br>
<label for="Name">Password</label>
<br/>
<input type="password" id="password" name="password" size="40" placeholder="Enter your password" id="username" required>
<br/>
<br/>
<input type="date" id="dt" onchange="mydate1();" hidden/>
<input type="text" id="dob" name="dob" onclick="mydate();" hidden />
<input type="button" Value="Date of Birth" onclick="mydate();" />
<script>
function mydate()
{
//alert("");
document.getElementById("dt").hidden=false;
document.getElementById("dob").hidden=true;
}
function mydate1()
{
d=new Date(document.getElementById("dt").value);
dt=d.getDate();
mn=d.getMonth();
mn++;
yy=d.getFullYear();
document.getElementById("dob").value=dt+"/"+mn+"/"+yy
document.getElementById("dob").hidden=false;
document.getElementById("dt").hidden=true;
}
</script>
<br><br>
<label for="address">Address</label><br>
<input type="text" id="address" size="40" name="address"
placeholder="Enter your address..." required><br><br>
<label for="country">Country</label><br>
<input type="text" id="country" size="40" name="country"
placeholder="Enter your country name....." required><br><br>
<label for="State">State</label><br>
<input type="text" id="state" size="40" name="state"
placeholder="Enter your state name....." required><br><br>
<label for="city">City</label><br>
<input type="text" id="city" size="40" name="city"
placeholder="Enter your city name....." required><br><br>
<input type="hidden" id="category" name="category"
value="Individual">
<input type="button" id="submit"
onclick="myFunction();" value="Submit" ><br>
javascript
<script>
function myFunction(){
var name=document.getElementById("name").value;
var mobileno=document.getElementById("mobileno").value;
var email=document.getElementById("email").value;
var password=document.getElementById("password").value;
var dob=document.getElementById("dob").value;
var address=document.getElementById("address").value;
var country=document.getElementById("country").value;
var state=document.getElementById("state").value;
var city=document.getElementById("city").value;
var country=document.getElementById("country").value;
var dataString ='name='+ name + '&mobileno=' + mobileno + '&email=' +
email + '&password=' + password + '&dob=' + dob + '&address=' + address +
'&country=' + country + '&state=' + state + '&city=' + city + '&country=';
if(name == '' || mobileno == '' || email == '' || password == '' || dob == '' || address == '' || country == '' || state == '' || city == '' || country == '') {
alert("Please Fill All Fields");
}
else
{
$.ajax({
type:"POST",
url:"https://smilestechno.000webhostapp.com/Register.php",
data: dataString,
cache: false,
success: function(html){
alert(html);
}
});
}
return false;
}

Related

If statement that if two values from input match do something

I want to make a Log in form in which user have to enter password "pass" and confirm that password "pass2" and if passwords don't match it should give an alert "pass don't match" and if they match it should alert "pass match", i wrote this but it doesn't work:
<form class="forma">
<p>Registruj se</p>
<hr>
<p id="tekst">Napravi svoj nalog. Besplatno je i traje samo minut.</p><br>
<input id="ime" type="text" name="ime" value="Ime:" onfocus="this.value=''">
<input id="prezime" type="text" name="prezime" value="Prezime:" onfocus="this.value=''"><br><br>
<input id="email" type="text" name="email" value="Email:" onfocus="this.value=''"><br><br>
<input id="pass" type="text" name="pass" value="Šifra:" onfocus="this.value=''"><br><br>
<input id="pass2" type="text" name="pass2" value="Potvrdi šifru:" onfocus="this.value=''"><br><br>
<input id="dugme" type="button" name="registruj" value="Registruj se">
</form>
<script>
let pass = document.querySelector("#pass input").value;
let pass2 = document.querySelector("#pass2 input").value;
let dugme = document.querySelector("#dugme");
let forma = document.querySelector(".forma");
dugme.addEventListener("click", function() {
if (pass === pass2) {
alert("pass match");
} else {
alert("pass don't match");
}
})
</script>
First, you just need to select id, input here is redundant
document.querySelector("#pass")
Moreover, you must move 2 pass getter in the click event handler, to make sure it's always get the latest passwords to match
let dugme = document.querySelector("#dugme");
let forma = document.querySelector(".forma");
dugme.addEventListener("click", function() {
let pass = document.querySelector("#pass").value;
let pass2 = document.querySelector("#pass2").value;
if (pass === pass2) {
alert("pass match");
} else {
alert("pass don't match");
}
})
<form class="forma">
<p>Registruj se</p>
<hr>
<p id="tekst">Napravi svoj nalog. Besplatno je i traje samo minut.</p><br>
<input id="ime" type="text" name="ime" value="Ime:" onfocus="this.value=''">
<input id="prezime" type="text" name="prezime" value="Prezime:" onfocus="this.value=''"><br><br>
<input id="email" type="text" name="email" value="Email:" onfocus="this.value=''"><br><br>
<input id="pass" type="text" name="pass" value="Šifra:" onfocus="this.value=''"><br><br>
<input id="pass2" type="text" name="pass2" value="Potvrdi šifru:" onfocus="this.value=''"><br><br>
<input id="dugme" type="button" name="registruj" value="Registruj se">
</form>
You have to move the statements to get values into the event listener so that you can get the latest values on the button click.
And the query selector is not correct:
dugme.addEventListener("click", function(){
let pass = document.querySelector("input#pass").value;
let pass2 = document.querySelector("input#pass2").value;
if (pass === pass2) {
alert("pass match");
} else {
alert("pass don't match");
}
});
Problem is you are using the value key default way
<form class="forma">
<p>Registruj se</p>
<hr>
<p id="tekst">Napravi svoj nalog. Besplatno je i traje samo minut.</p>
<br>
<input id="ime" type="text" name="ime" value="Ime:" onfocus="this.value=''">
<input id="prezime" type="text" name="prezime" value="Prezime:" onfocus="this.value=''"><br><br>
<input id="email" type="text" name="email" value="Email:" onfocus="this.value=''"><br><br>
<input id="pass" type="text" name="pass" placeholder="Šifra:" onfocus="this.value=''"><br><br>
<input id="pass2" type="text" name="pass2" placeholder="Potvrdi šifru:" onfocus="this.value=''"><br><br>
<input id="dugme" type="button" name="registruj" value="Registruj se">
</form>
<script>
let dugme = document.querySelector("#dugme");
let forma = document.querySelector(".forma");
dugme.addEventListener("click", function() {
let pass = document.querySelector("#pass").value;
let pass2 = document.querySelector("#pass2").value;
if (pass === pass2) {
alert("pass match");
} else {
alert("pass don't match");
}
})
</script>

How to Identify which control is violated in parsleyjs

I want to know which control is violated...
function validate()
{
vldt = $('#frmInt').parsley().validate();
alert(" is Submitted : "+ vldt );
if(vldt == false)
{
alert(" Violdated Control is : " + ? )
}
}
A first alert box will display 'is Submitted : false',
but, how can we get why the form is violated and which control is violated...
You can listen for the field:error event or look for elements having the class parsley-error:
$('#demo-form').parsley().on('field:error', function(e) {
var attrName = this.$element.attr('name');
var lblTxt = this.$element.siblings('label[for="' + attrName + '"]').text()
console.log('Validation failed for: ', lblTxt);
});
$('#demo-form [type="submit"]').on('click', function (e) {
vldt = $('#demo-form').parsley().validate();
return vldt;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://parsleyjs.org/dist/parsley.js"></script>
<form id="demo-form" data-parsley-validate="">
<label for="fullname">Full Name * :</label>
<input type="text" class="form-control" name="fullname" id="fullname" required="">
<label for="email">Email * :</label>
<input type="email" class="form-control" name="email" data-parsley-trigger="change" id="email" required="">
<br>
<input type="submit" class="btn btn-default" value="validate">
</form>

My register form keeps refreshing the page

on my local server it works just fine but as soon as I take it live it starts only refershing the page instead of calling the validation.
This is my jquery:
<script>
$("form#registerform").submit(
function (e) {
e.preventDefault();
function validateForm() {
var RegisterUsername = document.forms["contactForm"]["RegisterUsername"].value;
var FirstName = document.forms["contactForm"]["FirstName"].value;
var LastName = document.forms["contactForm"]["LastName"].value;
var Email = document.forms["contactForm"]["Email"].value;
var RegisterPassword = document.forms["contactForm"]["RegisterPassword"].value;
if (RegisterUsername == null || RegisterUsername == "") {
$(".error-messages").text("Username required").fadeIn(300).delay(1000).fadeOut(300);
return false;
}
else if (FirstName == null || FirstName == "") {
$(".error-messages").text("First name required").fadeIn(300).delay(1000).fadeOut(300);
return false;
} else if (LastName == null || LastName == "") {
$(".error-messages").text("Last name required").fadeIn(300).delay(1000).fadeOut(300);
return false;
}
else if (Email == null || Email == "") {
$(".error-messages").text("Email required").fadeIn(300).delay(1000).fadeOut(300);
return false;
}
else if (RegisterPassword == null || RegisterPassword == "") {
$(".error-messages").text("Password required").fadeIn(300).delay(1000).fadeOut(300);
return false;
}
}
}
</script>
This is my html:
<form id="registerform" name="contactForm" action="" onsubmit="return validateForm()" method="post">
<div class="pl-land-input">
<input class="email text-input" id="RegisterUsername" pattern=".{3,}" title="3 characters minimum" name="RegisterUsername" placeholder="Username" type="text" value="">
</div>
<div class="pl-land-input">
<input class="email text-input" id="FirstName" name="FirstName" placeholder="First Name" type="text" value="">
</div>
<div class="pl-land-input">
<input class="email text-input" id="LastName" name="LastName" placeholder="Last Name" type="text" value="">
</div>
<div class="pl-land-input">
<input class="email text-input" type="email" placeholder="Email" name="Email" id="Email">
</div>
<div class="pl-land-input">
<input class="email text-input" id="RegisterPassword" name="RegisterPassword" placeholder="Password" type="password">
</div>
<button type="submit" value="Submit" class="signup-plland">Sign up</button>
</form>
I have been trying to get my head around it and kept customizing it but I couldn't figure out the problem there was no problem in console for calling the Jquery libs.
I hope I can solve this asap.

javascript validation - Javascript not running

I'm trying to validate the inputs, so far I've created only two rules. One to test the phone number and another to test if the passwords entered at the same.
My problem is that for some reason my javascript isn't validating input. I have it referenced in <script>, I call it in the form onsubmit="return validate()". For some reason even with using an alert test to check that its run, that fails. So, I'm not really sure what's wrong, I could do with some extra eyes.
function validate() {
var errMsg = ""; /* stores the error message */
var result = true; /* assumes no errors */
var phonetest1 = true;
var phonetest2 = true;
/*get values from the form*/
var FirstName = document.getElementById("FirstName").value;
var Lastname = document.getElementById("Lastname").value;
var Email = document.getElementById("Email").value;
var Password = document.getElementById("Password").value;
var ConPassword = document.getElementById("ConPassword").value;
var Phone = document.getElementById("Phone").value;
var phonepatt1 = (/\(|0|\d|\)|\d|\d|\d|\d|\d|\d|\d|\d/);
var phonepatt2 = (/0|\d|\s|\d|\d|\d|\d|\d|\d|\d|\d/);
/* Rule one */
if (!phonepatt1.test(Phoneno)) {
phonetest1 = false;
}
if (!phonepatt2.test(Phoneno)) {
phonetest2 = false;
}
if (phonetest1 == false && phonetest2 == false) {
errMsg += "Your Phone number is incorrect .\n";
result = false;
}
alert("I'm running"); /* This isn't working */
/* Rule two */
if (ConPassword != Password) {
errMsg += "Please confirm your password .\n";
result = false;
}
if (errMsg != "") { //only display message box if there is something to show
alert(errMsg);
}
return result;
}
<H1>store Home Page</H1>
<p>Customer Registration: Register
<p>Customer Login: Login
<p>Manager Login Administrators
<form id="UserDetails" method="post" onsubmit="return validate()" action="index.htm">
<fieldset id="Details">
<legend>Your details:</legend>
<p>
<label for="FirstName">First Name</label>
<input type="text" name="FirstName" id="FirstName" pattern="[a-zA-Z]+" size="20" maxlength="20" required="required" />
</p>
<p>
<label for="Lastname">Last Name</label>
<input type="text" name="LastName" id="Lastname" pattern="[a-zA-Z]+" size="20" maxlength="20" required="required" />
</p>
<p>
<label for="Email">Email</label>
<input type="text" name="Email" id="Email" size="20" maxlength="20" required="required" />
</p>
<p>
<label for="Password">Password</label>
<input type="text" name="Password" id="Password" size="20" maxlength="20" required="required" />
</p>
<p>
<label for="ConPassword">Confirm Password</label>
<input type="text" name="ConPassword" id="ConPassword" size="20" maxlength="20" required="required" />
</p>
<p>
<label for="Phone">Phone Number</label>
<input type="text" name="Phone" id="Phone" maxlength="12" size="12" placeholder="(03)92251515" />
</p>
<input type="submit" value="Register Now!" />
<input type="reset" value="Reset" />
</fieldset>
</form>
You have wrog name in your JavaScript (should be Phone instead of Phoneno):
if (!phonepatt1.test(Phone)) {
phonetest1 = false;
}
if (!phonepatt2.test(Phone)) {
phonetest2 = false;
}

trouble validating various inputs with jQuery

for a class project I have to build a website for a pet store, featuring a pet grooming service. This involves a form, php and a mysql server on my localhost. I have been unable to correctly validate this form via a jQuery validator plugin for some unknown (to me) reason.
I've had no luck via regular jQuery code beyond getting the form to not submit blank input values. So as it is, anybody can put 'sadklfhsdk' in any of the fields (except for email, unless it has a '#') and it will validate and submit to the server.
So after I going through a couple of tutorials this is what I have so far:
The HTML:
<body>
<div id="h2Groom"><h2>Grooming Request Form</h2></div>
<form id="groom_form" method="post" action="insertPS.php">
<div id="result"></div>
<label for="firstName"><span>First Name:</span>
<input type="text" name="firstName" id="firstName" placeholder="Enter Your First Name" class="required"/>
</label>
<label for="lastName"><span>Last Name:</span>
<input type="text" name="lastName" id="lastName" placeholder="Enter Your Last Name" class="required"/>
</label>
<label for="email"><span>Email Address:</span>
<span id="error"></span>
<input type="email" name="email" id="email" placeholder="Enter a Email"/>
</label>
<label for="phone"><span>Phone Number:</span>
<span id="error"></span>
<input type="text" name="phone" id="phone" placeholder="Enter a phone number" class="required"/>
</label>
<label for="address"><span>Address:</span>
<input type="text" name="address" id="address" placeholder="Enter your address" class="required"/>
</label>
<label for="city"><span>City:</span>
<input type="text" name="city" id="city" placeholder="Enter your city" />
</label>
<label for="state"><span>State:</span>
<input type="text" name="state" id="state" placeholder="Enter your state" class="required"/>
</label>
<label for="zipcode"><span>Zipcode:</span>
<input type="text" name="zipcode" id="zipcode" placeholder="Enter your zipcode" class="required"/>
</label>
<label for="petType"><span>Type of Pet:</span>
<ul>
<li><label><input name="petType" type="radio" value="dog" id="dog">Dog</label></li>
<li><label><input name="petType" type="radio" value="cat" id="cat">Cat</label></li>
<li><label><input name="petType" type="radio" value="bird" id="bird">Bird</label></li>
</ul>
</label>
<select id="breed" name="breed">
<option value="0">--Please Choose Dog Breed--</option>
<option value="AlaskanMal">Alaskan Malamute</option>
<option value="Bichon">Bichon Frise</option>
<option value="WelshCorgi">Corgi, Welsh</option>
<option value="Dalmation">Dalmation</option>
<option value="EnglishToySpan">English Toy Spaniel</option>
<option value="FrenchBull">French Bull Dog</option>
<option value="Greyhound">Greyhound</option>
<option value="Papillon">Papillon</option>
<option value="Rottweiler">Rottweiler</option>
<option value="YorkshireTerr">Yorkshire Terrier</option>
</select>
<label for="neut"><span>Check box if your pet has been neutered/spayed (leave unchecked if not).</span></label>
<ul>
<label>
<li><input type="checkbox" name="neut" id="neut" />Yes</li></label>
</ul>
<br />
<br />
<br />
<label for="petname"><span>Pet Name:</span>
<input type="text" name="petname" id="petname" placeholder="Enter your pet's name" class="required" />
</label>
<label for="petBday"><span>Pet's Birthday:</span>
<input type="date" id="petBday" name="petBday"/>
</label>
<span> </span>
<input type="submit" id="submitBttn" value="Submit" /><input type="reset" id="resetBttn" value="Reset" />
</form>
</body>
The jQUERY (except the script to send values to server, see jsfiddle link):
$(document).ready(function() {
$('input[name=petType]').click(function() {
if(this.id=='dog') {
$('#breed').show('slow');
}
else {
$('#breed').hide('slow');
}
});
$('input[name=phone]').blur(function() {
if (validatePhone('phone')) {
$('#error').html('Valid');
$('#error').css('color', 'green');
}
else {
$('#error').html('Invalid');
$('#error').css('color', 'red');
}
});
$('input[name=email]').blur(function() {
if (validateEmail('email')) {
$('#error').html('Valid');
$('#error').css('color', 'green');
}
else {
$('#error').html('Invalid');
$('#error').css('color', 'red');
}
});
$("#submitBttn").click(function() {
//get input field values
var user_firstName = $('input[name=firstName]').val();
var user_lastName = $('input[name=lastName]').val();
var user_email = $('input[name=email]').val();
var user_address = $('input[name=address]').val();
var user_phone = $('input[name=phone]').val();
var user_city = $('input[name=city]').val();
var user_state = $('input[name=state]').val();
var user_zipcode = $('input[name=zipcode]').val();
var user_petname = $('input[name=petname]').val();
var checked_radio = $('input:radio[name=petType]').is(':checked');
var user_neut = $('input:checkbox[name=neut]').is(':checked');
var user_breed = $('input:select[name=breed]').is(':selected');
var txtVal = $('#petBday').val();
if(isDate(txtVal))
alert('Valid Date');
else
alert('Invalid Date');
var proceed = true;
//Validation functions, executed when user hits "submit"
function validatePhone(phone) {
var a = document.getElementById(phone).value;
var filter = /^[0-9-+]+$/;
if (filter.text(phone)) {
return true;
}
else {
return false;
}
}
function validateEmail(email) {
var filter = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (filter.test(email)) {
return true;
}
else {
return false;
}
}
function isDate(txtDate)
{
var currVal = txtDate;
if(currVal == '')
return false;
//declare regex
var rxDatePattern = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
var dtArray = currVal.match(rxDatePattern); //is the format ok?
if(dtArray ==null)
return false;
//checks for mm/dd/yyyy format
dtMonth = dtArray[1];
dtDay = dtArray[3];
dtYear = dtArray[5];
if(dtMonth < 1 || dtMonth > 12)
return false;
else if (dtDay < 1 || dtDay > 31)
return false;
else if ((dtMonth==4 || dtMonth==6 || dtMonth==9 || dtMonth==11) && dtDay ==31)
return false;
else if (dtMonth == 2)
{
var isleap = (dtYear % 4 == 0 && (dtYear % 100 != 0 || dtYear % 400 == 0));
if(dtDay > 29 || (dtDay ==29 && !isleap))
return false;
}
return true;
}
EDIT: corrected if(filter.text()) to if(filter.test(phone)). None of my java validation code works.
validatePhone: filter.text should be spelled test

Categories

Resources