Checking form fields with AJAX and PHP - javascript

I am trying to write a code that will check in a php file if username/mail has already been registered. The following code doesn't work because in check_fields() when check_field() is fired for both files the return is sent immediately, without waiting for the asynchronous query to finish. I don't want to use JQuery so I thought about doing the following :
a function is linked to the onsubmit of the form
a AJAX call is made to the server to launch a php file
this file analyses the input and return a error response if it needs to : "field is empty", "email already used", "incorrect email adress", ect...
when the AJAX call is finished a function (or callback) will be fired. This function will check the .textContent of the <span id="username_err"></> and <span id="mail_err"></> to see if the php has noticed to errors. If it's not blank (there's a problem in the input) the function return false to the initial function.
the return value is sent back to the form
if true, form is submitted to server...
That's what I would like to try out, is this ok ? Is there a way to do this without a promise ?
[Original code]
<html>
<body>
<form style="text-align:center" action="mama.php" method="post" onsubmit="return check()">
<div class="username">
<span id="label_username">Username :</span>
<input type="text" id="username" name="username">
<p id="username_err"></p>
</div><br />
<div class="mail">
<span id="label_mail">Mail :</span>
<input type="text" id="mail" name="mail"></input>
<p id="mail_err"></p>
</div><br />
<input type="submit" id="envoyer" value="Envoyer" />
</form>
</body>
<script>
function check() {
return check_fields(['username', 'mail']);
}
function check_fields(items) {
var check = true;
for (i = 0; i < items.length; i++) {
check_field(items[i]);
};
for (i = 0; i < items.length; i++) {
var value = document.getElementById(items[i] + '_err').textContent;
if (value != '') {
check = false
}
};
return check
}
function check_field(id) {
var value = document.getElementById(id).value;
ajax_php(id, value, 'check_field.php', function(returned_value) {
document.getElementById(id + '_err').innerHTML = returned_value;
});
}
function ajax_php(id, value, file, fn) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
fn(xmlhttp.responseText);
}
};
xmlhttp.open('GET', file + '?' + id + '=' + value, true);
xmlhttp.send();
}
</script>
</html>
[Possible solution]
<html>
<body>
<form style="text-align:center" action="mama.php" method="post" onsubmit="check(this)">
<div class="username">
<span id="label_username">Username :</span>
<input type="text" id="username" name="username">
<p id="username_err"></p>
</div><br />
<div class="mail">
<span id="label_mail">Mail :</span>
<input type="text" id="mail" name="mail"></input>
<p id="mail_err"></p>
</div><br />
<input type="submit" id="envoyer" value="Envoyer" />
</form>
</body>
<script>
function check_fields(form, items) {
var success = true;
function check_field(i) {
var id = items[i];
var value = document.getElementById(id).value;
ajax_php(id, value, 'check_field.php', function(returned_value) {
document.getElmentById(id + '_err').textContent = returned_value;
if (returned_value != '') {
success = false;
}
if (++i < items.length) {
check_field(i); // Check the next field
} else if (success) { // reached the last field with no errors
form.submit();
}
});
}
check_field(0);
}
function check(form) {
check_fields(form, ['username', 'mail']);
return false; // prevent form submission
}
function ajax_php(id, value, file, fn) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
fn(xmlhttp.responseText);
};
};
xmlhttp.open('GET', file + '?' + id + '=' + value, true);
xmlhttp.send();
};
</script>
</html>

Chain the AJAX calls for each field. The callback for field i submits the AJAX call to check field i+1, and so on. The last callback submits the form if all were successful.
function check_fields(form, items) {
var success = true;
function check_field(i) {
var id = items[i];
var value = document.getElementById(id).value;
ajax_php(id, value, 'check_field.php', function(returned_value) {
document.getElementById(id + '_err').textContent = returned_value;
if (returned_value != '') {
success = false;
}
if (++i < items.length) {
check_field(i); // Check the next field
} else if (success) { // reached the last field with no errors
form.submit();
}
});
}
check_field(0);
}
function check(form) {
check_fields(form, ['username', 'mail']);
return false; // prevent form submission
}
The form should contain:
onsubmit="return check(this)"

Related

what is the correct way to validate form with javascript

should i put "submit" instead "form_name" in the last block of code? what is the correct way?
thanks!
function check() {
var title = document.getElementById("title");
var content = document.getElementById("content");
if (title == "") {
alert("title is required");
return false;
}
if (content == "") {
alert("content is required");
return false;
}
var submit = document.getElementById("form_name");
submit.submit();
}
this is my form
<form action="#" method="post" id="form_name" name="form_name">
<input type="text" name="title" id="title" />
<textarea name="content" id="content" cols="30" rows="10"></textarea>
<input type="submit" value="Submit" id="submit" name="submit" onclick="return check();"/>
</form>
First you are selecting an element and acting like it is the value
var title = document.getElementById("title"); <-- DOM element
if (title == "") { <-- checking the DOM against a string.
You should be using .value to get what was entered.
Next you are submitting the form.... but you clicked on a submit button inside of the form so that will submit the form. So that is not needed.
function check() {
var title = document.getElementById("title").value;
var content = document.getElementById("content").value;
if (!title.trim().length) {
alert("title is required");
return false;
else if (!content.trim().length) {
alert("content is required");
return false;
}
return true
}
And never name anything submit, it just leads to problems.
In most recent browsers you have more power to use
function myFunction() {
var inpObj = document.getElementById("id1");
if (inpObj.checkValidity() == false) {
document.getElementById("demo").innerHTML = inpObj.validationMessage;
}else{
document.getElementById("demo").innerHTML = "";
}
}
<input id="id1" type="number" min="100" max="300" required>
<button onclick="myFunction()">OK</button>
<p id="demo"></p>
Reference:
https://www.w3schools.com/js/js_validation_api.asp

Contact form variables are not passing into javascript from section tag

Contact form variables are not passing into javascript. basically javascript fail on validation. On debug, I am getting "undefined is not a function." I have several seperators on this page. If i put identical code inside a seperate page like "contact.html" variables pass into javascript.
My understanding is that HTML tag id="contact-form" for some reason does not pass into the function.
Java Script
function code_contactvalidation() {
// Add form.special data (required for validation)
$('form.special input, form.special textarea').each(function() {
this.data = {};
this.data.self = $(this);
var val = this.data.self.val();
this.data.label = (val && val.length) ? val : null;
this.data.required = this.data.self.attr('aria-required') == 'true';
});
// Special form focus & blur
$('form.special input, form.special textarea').focus(function() {
with (this.data) {
console.log('focusing');
if ( label && self.val() == label) self.val('');
else return;
}
}).blur(function() {
with (this.data) {
if ( label && self.val().length == 0 ) self.val(label)
else return;
}
});
// initialize captcha
var randomcaptcha = function() {
var random_num1=Math.round((Math.random()*10));
var random_num2=Math.round((Math.random()*10));
document.getElementById('num1').innerHTML=random_num1;
document.getElementById('num2').innerHTML=random_num2;
var n3 = parseInt(random_num1) * parseInt(random_num2);
$('#captcharesult').attr('value', n3);
$('#buttonsubmit').attr('value','Submit');
};
randomcaptcha();
//initialize vars for contact form
var sending = false,
sent_message = false;
$('#contact-form').each(function() {
var _this = this;
this.data = {};
this.data.self = $(this);
this.data.fields = {};
this.data.labels = {};
this.data.notification = this.data.self.find('.notification');
_.each(['name','email','subject'], function(name) {
_this.data.fields[name] = _this.data.self.find(_.sprintf('input[name=%s]', name));
_this.data.labels[name] = _this.data.fields[name].val();
});
}).validate({
errorPlacement: function() {},
highlight: function(element) { $(element).addClass('invalid'); },
unhighlight: function(element) { $(element).removeClass('invalid'); },
submitHandler: function(form) {
if (sending) return false;
if ( sent_message ) { alert('Your message has been sent, Thanks!'); return false; }
var field, valid = true;
with (form.data) {
_.each(fields, function(field, name) {
if ( $.trim(field.val()) == labels[name] ) { valid = false; field.addClass('invalid'); } else { field.removeClass('invalid'); }
});
}
if (valid) {
sending = true;
$('#ajax-loader').show();
form.data.self.ajaxSubmit({
error: function(errorres) {
$('#ajax-loader').hide();
randomcaptcha();
form.data.notification.removeClass('sucess').addClass('error').find('span:first-child').html('Unable to send message (Unknown server error)');
form.data.notification.animate({opacity: 100}).fadeIn(500);
},
success: function(res) {
sending = false;
$('#ajax-loader').hide();
if (res == 'success') {
sent_message = true;
form.data.notification.removeClass('error').addClass('success').find('span:first-child').html('Your message has been sent!');
form.data.notification.animate({opacity: 100}).fadeIn(500);
$('#formName').val("");
$('#formEmail').val("");
$('#formSubject').val("");
$('#formMessage').val("");
$('#formcheck').val("");
} else if (res == 'captchaerror') {
randomcaptcha();
form.data.notification.removeClass('sucess').addClass('error').find('span:first-child').html('Captcha Error');
form.data.notification.animate({opacity: 100}).fadeIn(500);
} else {
randomcaptcha();
form.data.notification.removeClass('sucess').addClass('error').find('span:first-child').html('Unable to send message (Unknown server error)');
form.data.notification.animate({opacity: 100}).fadeIn(500);
}
}
});
}
return false;
}
});
}
HTML
<section id="contact">
<div class="container">
<div class="row text-center">
<div id="principal" data-align="left">
<div class="form_group_contact">
<script type="text/javascript" src="js/jquery.validate.pack.js"></script>
<script type="text/javascript" src="js/jquery.form.js"></script>
<form class="contactForm special validate" id="contact-form" action="sendmsg.php" method="post">
<p><input id="formName" name="name" type="text" value="Name" class="required" /></p>
<p><input id="formEmail" name="email" type="text" value="Email" class="required email" /></p>
<p><input id="formSubject" name="subject" class="last required" type="text" value="Subject" /></p>
<p><textarea id="formMessage" name="message" class="required margin20" rows="4" cols="83"></textarea></p>
<div class="form_captcha margin20">
<p>Captcha Recognition (<span id="num1"></span> * <span id="num2"></span>) =
<input type="hidden" id="captcharesult" name="captcha_result" value=""/>
<input type="text" class="required number" maxlength="3" size="3" id="formcheck" name="captcha" value=""/>
</p>
</div>
<p class="notification" style="display: none;"><span></span> <span class="close" data-action="dismiss"></span></p>
<p><input type="submit" value="" class="margin20" id="buttonsubmit" /><img id="ajax-loader" alt="" src="./images/ajax-loader.gif" /></p>
</form>
</div>
</div>
</div>
</div>
</section>
if ( label && self.val().length == 0 ) self.val(label)
There needs to be a semicolumn (;) to end that line ;)
Also, you call "each" on the contact-form which makes me think you expect more than one contact-form. You will need to set the identifier as "class" rather than "id" in the HTML and use "." in the jQuery selector rather than "#".
Now you got those little things fixed, please try it out in Firefox. Google is very vague with javascript errors, Firefox will give you a better error message. Please share it with us so I can edit this post with a final solution.

Javascript : How to check multiple empty values

I have four input elements in my form. I don't have submit button in my form. I want to check all the values and if all the values are not empty then I want to post that all values to php page by using ajax.
This is my form input elements.
<form method="post" action="getAllDteails.php" name="dashboard">
Manager Name<input type="text" id="managername" onchange="getDetails(this.value)" name="managername"/>
Project Name<input type="text" id="projectname" onchange="getDetails(this.value)" name="projectname"/>
Task Name<input type="text" id="taskname" onchange="getDetails(this.value)" name="taskname"/>
Completion Date<input type="date" id="date" onchange="getDetails(this.value)" name="date"/>
<div id="cool"></div>
</form>
This is my script.
function getDetails()
{
var mname = document.getElementById('managername').value;
var pname = document.getElementById('projectname').value;
var tname = document.getElementById('taskname').value;
var cdate = document.getElementById('date').value;
//alert(mname);
if(mname!==null&&pname!==null&&tname!==null&&cdate!==null)
{
alert("true");
var jsonobj = {"mname" : mname, "pname" : pname, "tname" : tname, "cdate" : cdate};
var js = JSON.stringify(jsonobj);
alert(js);
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert(js);
document.getElementById("cool").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","getAllDetails.php?js="+js,true);
xmlhttp.send();
}
}
Just am getting all the values and assigning to four variables. If the four variables are not null then I want to assign all that in single object. But the problem is every time it is coming inside the condition and showing alert.
At fourth time also it is showing the alert. But the values are not going to php page. I'am a beginner Please guide me if I approached in a wrong way.
1.Change Html Code to new code
<form method="post" action="getAllDteails.php" name="dashboard">
Manager Name<input type="text" id="managername" name="managername" class="v1"/>
Project Name<input type="text" id="projectname" name="projectname" class="v1"/>
Task Name<input type="text" id="taskname" name="taskname" class="v1"/>
Completion Date<input type="date" id="date" name="date" class="v1"/>
<input id="Button1" type="button" value="button" onclick="return checkData();" />
</form>
2.Change Script Code to new script code (for checking multipe value)
function checkData() {
var _v = document.getElementsByClassName("v1"); // get all field
var _empty = false; // default has false;
var _jsParm = '';
for (var i = 0; i < _v.length; i++) {
if (_v[i].value == '') {
_empty = true; // if value of null or empty; *
break;
}
_jsParm += _v[i].id + ':\'' + _v[i].value + '\',';
}
//* if any field is null , show alert
if (_empty == true) {
alert('Error!!!!! \r\n Please enter data in all field.');
return false;
}
alert('OK! all field has data.' + '\r\n' + _jsParm)
_jsParm = _jsParm.substr(0, _jsParm.length - 1);
var jsonobj = '{' + _jsParm + '}';
var js = JSON.stringify(jsonobj);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(js);
document.getElementById("cool").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "getAllDetails.php?js=" + js, true);
xmlhttp.send();
}
3.Save
4.Enjoy Now!

Javascript/ajax is passing all form textfield values to the php but not the last textfield value

This is my html with form and javascript/ajax function. All the textfield values are passed to the test.php. When I do so, if i enter the first three textfields then test.php will successfully display the form values. But on the other hand, if I fill all the four textfield and send then nothing will happen. Since, I am new in the programming, i could not figure this issue out. I would be thankful for the solution of this issue.
#form.html
<html>
<SCRIPT language="javaScript">
function sendData(){
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXobject ('Mircosoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById('message').innerHTML = xmlhttp.responseText;
}
}
var i=0;
var arr = new Array();
while ((document.getElementById(i).value)) {
if ((document.getElementById(i).value)!=""){
var activity = document.getElementById(i).value;
arr[i] = activity;
}
i++;
}
var params = 'activity='+JSON.stringify(arr);
xmlhttp.open('POST','test.php', true);
xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xmlhttp.send(params);
document.getElementById("message").innerHTML = "Sending...";
}
</script>
<form action="#" method="POST">
<tr>Name1:<td> <input type="text" id="0"/> </td></tr><br>
<tr>Name2:<td> <input type="text" id="1"/> </td></tr><br>
<tr>Name3:<td> <input type="text" id="2"/> </td></tr><br>
<tr>Name4:<td> <input type="text" id="3"/> </td></tr><br>
<input type="button" value="Send" onclick="sendData()";/>
</form>
<div id="message">
</div>
</html>
This is the test.php file where the form value will be displayed.
#test.php
<?php
$activity = $_POST['activity'];
$activity = json_decode($activity);
if (is_array($activity)){
foreach ($activity as $value){
echo $value."<br>";
}
}
else {
echo "error";
}
?>
The issue is with
while ((document.getElementById(i).value)) {
It works just fine until i === 4, then getElementById returns null, and null.value is an error, so the whole thing errors out.
Using a while loop for this doesn't really seem like a good idea, but something like this should at least work
while (document.getElementById(i)) {
if ((document.getElementById(i).value) != "") {
arr[i] = document.getElementById(i).value;
}
i++;
}
Getting the elements by class, tagname or something else other than numeric ID's seems better
var arr = new Array();
var elems = document.querySelectorAll('.inputs'); // class
for ( var i=0; i<elems.length; i++ ) {
arr.push(elems[i].value)
}

Javascript two submit buttons in one form almost complete

I have a form with two submit buttons with onClick events attached. The form action is a paypal form.
If make a payment button is pressed the form is emailed and then redirects to paypal for payment.
If the invoice button is pressed an email is sent with the form details but the default action of redirecting to PayPal is stopped.
It all seems to work fine but when the invoice buttin is pressed it still redirects to paypal.
If the invoice button is pressed i want it to send the email but then stop and not continue on with the form action.
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" id="paymentform" name="paymentform">
<input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="currency_code" value="GBP">
<fieldset id="your_details" class="">
<legend>Your Details</legend>
<ol>
<li><label for="your_name">Your Name</label><input type="text" name="your_name" value="" id="your_name" class="large "></li>
<li><label for="your_position">Your Position</label><input type="text" name="your_position" value="" id="your_position" class="large"></li>
<li><label for="your_company">Your Company</label><input type="text" name="your_company" value="" id="your_company" class="large "></li>
<li><label for="your_telephone">Your Telephone</label><input type="text" name="your_telephone" value="" id="your_telephone" class="medium "></li>
<li><label for="your_mobile">Your Mobile</label><input type="text" name="your_mobile" value="" id="your_mobile" class="medium"></li>
</ol>
</fieldset>
<input type="submit" value="Pay by Credit Card →" id="cc" onclick="return email_me(document.paymentform);" class="submit_button">
<input type="submit" value="Pay by Invoice →" id="invoice" class="submit_button" onclick="return email_me(document.paymentform,true);">
var xmlHttp;
var formname;
var invoiceonly_var
function email_me(Form,invoiceonly)
{
formname = Form.name;
var params = "";
var i;
var Element;
var type;
var name;
var fieldvalue;
var optional;
var BadFields = "";
var Title;
var Titles = new Array();
Titles['item_name'] = "Course Title";
var outMessage = "";
invoiceonly_var = invoiceonly;
//alert(formname);
//alert(Form.length);
var Optional = new Array();
// optional fields
Optional['your_position'] = true;
Optional['your_mobile'] = true;
for(i = 0; i < Form.length; i++)
{
Element = Form.elements[i];
type = Element.type;
name = Element.name;
//alert("name:"+name+" type:"+type);
if(type == "text")
{
fieldvalue = Element.value;
params = params + name + "=" + fieldvalue + "&";
optional = Optional[name];
if ( (fieldvalue == '' || fieldvalue == name ) && typeof(optional) == "undefined")
{
Title = getTitle(name,Titles);
BadFields += "- " + Title + "\n";
}
//alert(params);
}
if(type == "textarea")
{
fieldvalue = Element.value;
params = params + name + "=" + fieldvalue + "&";
optional = Optional[name];
if ( (fieldvalue == '' || fieldvalue == name ) && typeof(optional) == "undefined")
{
Title = getTitle(name,Titles);
BadFields += "- " + Title + "\n";
}
//alert(params);
}
}
if(BadFields)
{
outMessage = "We are unable to proceed as the following \n";
outMessage += "required fields have not been completed:\n\n";
outMessage += BadFields;
alert(outMessage);
return false;
}
//alert(params);
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request");
return;
}
url="/payment/ajax_email_me.php?";
if (invoiceonly_var == true)
{
params = params + "Payment_Method=Invoice";
}
else
{
params = params + "Payment_Method=PayPal&";
}
url=url+params;
//alert(url);
xmlHttp.onreadystatechange = Finished;
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
return true;
}
function Finished()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
//document.getElementById('search').innerHTML = xmlHttp.responseText;
var response = xmlHttp.responseText;
//alert(response);
if (invoiceonly_var == true)
{
alert("Thank you. Your message has been sent.");
}
else
{
document.paymentform.submit();
}
document.body.innerHTML = document.body.innerHTML + "<span></span>";
}
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
// alert("Mozilla");
}
catch (e)
{
//Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
// alert("IE");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
// alert("IEError");
}
}
return xmlHttp;
}
function selectval(Sel)
{
return Sel.options[Sel.selectedIndex].value;
}
function getTitle(name,Titles)
{
Title = Titles[name];
if (typeof(Title) == "undefined")
{
Title = name;
Title = Title.replace(/_/g," ");
}
return Title;
}
First of all, your code could be greatly simplified with the use of jQuery to abstract away much of the AJAX logic here.
Secondly, you have return true at the bottom of your email_me function - try changing this to:
return !invoiceonly;
Returning false from this function will prevent the form from submitting. When the invoice button is clicked (and the invoiceonly parameter is set to true) you do not want the form to submit, so the above logic will make the function return false.
Usually I would suggest adding ";return false" after the Javascript you want to run, but since you're already returning a value, I'm not sure that will work. Give it a shot, though, and if it doesn't work, can I ask what the return value is doing?
Something like this:
<input type="submit" value="Pay by Invoice →" id="invoice" class="submit_button" onclick="return email_me(document.paymentform,true);return false">
Did you try adding "return false" to the end of the onclick event which you don't want to submit?
Or you can change the type to "button" from "submit" - that might do the trick.

Categories

Resources