Javascript two submit buttons in one form almost complete - javascript

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.

Related

Checking form fields with AJAX and PHP

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

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

Form submission - confirmation

I am currently using the dotmailer to generate a new form (simple textbox and submit button) that automatically adds the email address to the dotmailer address book.
When someone submits an email address - they can be taken to a webpage.
<input type="hidden" name="ReturnURL" id="returnValueHidden" value="URL">
I have been trying to work out a way to present an alert box saying "submitted" and not take take the user to a thank you page.
Solution?
document.getElementById('returnValueHidden').value = alert("Email successfully submitted.");
But all this does, it displays an alert box and then redirects to the following url (even when the value is inserted or not).
http://dmtrk.net/undefined?result=success
404 The page you are looking for could not be found
Is there anyway i can adjust this so it submits the email but does not redirect.
Full Code:
<script language="javascript">
<!--
function validate_signup(frm) {
var emailAddress = frm.Email.value;
var errorString = '';
if (emailAddress == '' || emailAddress.indexOf('#') == -1) {
errorString = 'Please enter your email address';
}
var els = frm.getElementsByTagName('input');
for (var i = 0; i < els.length; i++)
{
if (els[i].className == 'text' || els[i].className == 'date' || els[i].className == 'number')
{
if (els[i].value == '')
errorString = 'Please complete all required fields.';
}
else if (els[i].className == 'radio')
{
var toCheck = document.getElementsByName(els[i].name);
var radioChecked = false;
for (var j = 0; j < toCheck.length; j++)
{
if (toCheck[j].name == els[i].name && toCheck[j].checked)
radioChecked = true;
}
if (!radioChecked)
errorString = 'Please complete all required fields.';
}
}
document.getElementById('returnValueHidden').value = alert("Email successfully submitted.");
var isError = false;
if (errorString.length > 0)
isError = true;
if (isError)
alert(errorString);
return !isError;
}
//-->
</script>
HTML:
<form name="signup" id="signup" action="http://dmtrk.net/signup.ashx" method="post" onsubmit="return validate_signup(this)">
<input type="hidden" name="addressbookid" value="">
<input type="hidden" name="userid" value="41929">
<input type="hidden" name="ReturnURL" id="returnValueHidden" value="URL">
<input type="text" name="Email" onfocus="if(this.value=='Email')this.value='';" class="blueTextBox">
<input type="Submit" name="Submit" class="submit">
</form>
To send information without doing a full page reload you need to use AJAX. It's easiest to use an existing javascript library, for example jQuery.
Check out these pages:
http://api.jquery.com/jQuery.ajax/
http://api.jquery.com/on/

JS validation fails at normal speed but works when stepping through the code

js validation works perfectly when I step through it, but fails at "normal speed." SPECIFICALLY: if a dup email is caught but the other fields are filled in correctly, the form can be submitted (but no error is forthcoming when stepping through the code). Has anyone seen this before? I know I could just code it a different way, but I cannot simply walk away from this simple problem that's even become a bottle kneck without first understanding why this isn't working.
My approach is to validate onblur and onsubmit. I am using the jquery selector only for convenience and then again for an ajax call, but otherwise i'm using js. I am doing a loop through the fields but only operating on text and password fields.
checking for blanks
checking for no numbers in name
checking for email address properly formatted
and then checking for unique email in the email field
annotated code below for js and form below:
//registration validation
$('.validate').blur(function() {
var theForm = document.registerNewUserForm;
//removes error messages from html before the run
clearAllErrors(theForm);
var msg = "";
var mdiv;
theForm.submit.disabled=true;
document.getElementById("submitButton").disabled = true;
for (var i = 0; i < theForm.elements.length; i++) {
//mdiv is set to form element being evaluated at the time
mdiv = document.getElementById(theForm.elements[i].name + "Message");
msg = validateField(theForm.elements[i]);
if(msg != "") {
mdiv.innerHTML = msg;
break;
}
}
if(msg == "") {
theForm.submit.disabled=false;
document.getElementById("submitButton").disabled = false;
}
});
$('#registerNewUserForm').submit(function() {
var theForm = document.registerNewUserForm;
clearAllErrors(theForm);
var msg = "";
var mdiv;
for (var i = 0; i < theForm.elements.length; i++) {
//mdiv is set to form element being evaluated at the time
mdiv = document.getElementById(theForm.elements[i].name + "Message");
msg = validateField(theForm.elements[i]);
if(msg != "") {
break;
}
}
if (msg != ""){
mdiv.innerHTML = msg;
return false;
} else {
theForm.submit();
}
});
function validateField(theField) {
msg = "";
//all fields are required
if (theField.type == "text" || theField.type == "password") {
if (theField.value == "") {
msg = "The " + theField.name + " field is required.";
}
}
//name fields are non-numeric
if (theField.name == "fullName"){
if (hasNumber(theField.value) == true){
msg= "The Name field is non-numeric.";
}
}
//email must be correctly formatted
if (theField.name == "email") {
msg = emailCheck (theField.value);
if (msg == "") {
//email address must also be unique
chkEmail();
msg = document.getElementById('emailMessage').innerHTML;
}
}
return msg;
}
function chkEmail() {
emailAddr = document.getElementById("email").value;
$.ajax({
url: '/chkEmail',
type: 'POST',
data: 'emailAddr=' + encodeURIComponent(emailAddr),
dataType: "xml",
context: document.body,
success: function(data) {
document.getElementById('emailMessage').innerHTML = $(data).find("message").text();
}
});
}
<form name="registerNewUserForm" id="registerNewUserForm" action="/register" method="post">
<br/>
<div>Create an Account and join the fun!</div>
<div><input class="validate" type="text" id="fullName" required placeholder="Full Name" name="fullName" value="" size="30"></div>
<div id="fullNameMessage" class="error"></div>
<div><input class="validate" type="text" id="email" required placeholder="Email Address" name="email" value="" size="30"></div>
<div id="emailMessage" class="error"></div>
<div><input class="validate" type="password" id="passWord" required placeholder="Password" name="passWord" value="" size="30"></div>
<div id="passWordMessage" class="error"></div>
<div style="position:relative;left:173px;"><input id="submitButton" type="submit" value="Signup for PastelPlanet"></div>
<input type="hidden" name="formName" value="registerNewUserForm">
<input type="hidden" name="urlDestination" value="">
</form>
Your "chkEmail" function involves a call to the server, and it's asynchronous. The call to the server will not be complete when the function returns, when you're running at "full speed".

Categories

Resources