Blog

Newest Post
Blog Archives
Blog Categories

Portfolio

3D Models
Banners
Brochures
Business Cards
Custom Programming
Environments
Flash Projects
Game Design
Image Altering
Web Design

About

Resume
Recommendation Letters

Contact

May 10, 2010

Prevent Spam without Captcha

Filed under: JavaScript,The Coding World — admin @ 7:13 pm

The following will show you how to prevent spam without the use of those annoying captcha images. I use javascript, which according to W3C, approximately 95% of the people browsing the web have it enabled. The odds of one of your visitors having it disabled is slim. If it does concern you however, you could always place a notice to turn on javascript before using the form or you could always use another method, just place the other method in <noscript> </noscript> tags.

Below is how you could prevent spam with simple javascript.

TESTED IN THE LATEST BROWSERS: Internet Explorer 8.x, Firefox 3.x, Chrome 4.x, Safari 4.x

 

Step 1: Create a separate javascript file and link to it in the <head> section of your page. I will call my file “formvalidation.js” and I will link to it from my form page “form.html”.

Example of the “head” section of “form.html”:

  <head>
    <script language="JavaScript" src="formvalidation.js" type="text/javascript"></script> 
  </head>
  <body>
  Your form would be here.
  </body>

 

Step 2: Remove the form’s action=”" attribute

Some Spam bots will submit directly to the form’s source, this step prevents that.

Example of the form’s attributes:

 
  <form name="exampleform" method="POST" id="exampleform">

 

Step 3: Add some simple requirements to our form. I will use first name and last name.

Example:

<input type="hidden" id="req_id" name="req_id[]" value="first_name">
<input type="hidden" id="req_id" name="req_id[]" value="last_name">

 

Step 4: Add a hidden field called “human” and set its value to “0″. We will change this value once we determine a human is filling out the form.

Example:

<input type="hidden" id="human" name="human" value="0">

 

Step 5: On one of your required fields, add a javascript function to call once something is typed into it. This verifies that a human is filling out the form. I will place it on the “Last Name” field.

<input type="text" name="last_name" id="last_name" onchange="validateHuman('exampleform');" />

 

Step 6: Make the form submit button execute a javascript function that will check all the required fields, verify that a human submitted the form, and then submit the form for processing.

Example:

<input type="button" name="Submit" value="Submit" onclick="submitForm('exampleform');" />

 

Step 7: Add the following Javascript to your Javascript file “formvalidation.js”. These two javascript functions, “validateHuman” and “submitForm” will do all the work of preventing spam.

validateHuman – changes the “human” form element to another number once a person has typed into your required field.

submitForm
– validates the required form elements have been filled in, checks to see the value of “human” has changed, and then submits the form for processing.

View Code JAVASCRIPT
 
function submitForm(frm){
 
  //Check is the visitor's browser supports the javascript function
  if (document.forms[frm]) {
    //START function executed
 
	//we will now check to see if all required fields were filled in
    var error = '';
 
	if(document.forms[frm].elements['req_id'] != null || document.forms[frm].elements['req_id'] != '') {
        //store all of the required fields into "reqs"
		var reqs=document.forms[frm].elements['req_id[]'];
        //count the number of required fields
		var nbr_fields = reqs.length;
        //set a variable "req" to make sure all the "reqs" stay true
		var req = true;
		//loop through all the required fields, making sure they are not blank
		for(var i=0;i<nbr_fields;i++){
		  if(document.forms[frm].elements[reqs[i].value].value.length <= 0){
		   //the field is blank
		   req = false;
		   //list what field has been left blank to inform the user
		   if (reqs[i].value == 'first_name') error += "\n - First Name";
		   if (reqs[i].value == 'last_name') error += "\n - Last Name";
          }
        }
 
        //if all required fields are filled in
		//and the "human" form element has changed
		//submit the form
		if(req==true && document.forms[frm].elements['human'].value == '42'){
            document.forms[frm].action = "http://somewebsite.com/submit.php";
			document.forms[frm].submit();
            return true;
        } else {
          alert('Opps, it looks like some fields are blank:\n'+error);
          return false;
        }
        return false
     }
 
    //END function executed
  } else { 
    //START the browser does not support the function
    alert('Your browser lacks the capabilities required to run this script!\n\nPlease call 555-555-5555 and we will gladly take your information over the phone.');
    //END the browser does not support the function
  }
 
}
 
function validateHuman(frm){
	document.forms[frm].elements['human'].value = "42";
}

That’s it! Your form should now prevent spam bots from submitting directly to it. Below is just a total picture of how “form.html” will look according to this demo.

Example of form.html:

 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Example Form</title>
<script language="JavaScript" src="formvalidation.js" type="text/javascript"></script>
</head>
 
<body>
 
<form name="exampleform" id="exampleform" action="submit.php" method="POST">
<input type="hidden" id="req_id" name="req_id[]" value="first_name">
<input type="hidden" id="req_id" name="req_id[]" value="last_name">
<input type="hidden" id="human" name="human" value="0">
First Name: <input type="text" name="first_name" id="first_name" /><br />
Last Name: <input type="text" name="last_name" id="last_name" onchange="validateHuman('exampleform');" /><br />
<input type="button" name="Submit" value="Submit" onclick="submit_form('exampleform');" />
</form>
 
 
</body>
</html>

October 22, 2009

Latitude and Longitude of a location using Javascript and Google

Filed under: JavaScript,The Coding World — admin @ 2:54 pm

The following Javascript will help you acquire the latitude and longitude of a location (using an address, zip code, or city).

Note: You will need to have a Google API key which is domain specific.

Place the following code in the <head> section:

View Code JAVASCRIPT
var geocoder;
geocoder = new GClientGeocoder();
 
function submitForm() {
  var address = document.getElementById("address").value + ", " + document.getElementById("city").value + ", " + document.getElementById("state").value + ", " + document.getElementById("zip").value;
  geocoder.getLocations(address, getCoords);
}
 
function getCoords(response) {
  if (!response || response.Status.code != 200) {
    alert("Unable to Create Lat and Lng for plotting.");
  } else {
    place = response.Placemark[0];
    var lat = place.Point.coordinates[1];
	var lng = place.Point.coordinates[0];
  }
 alert("Lat:"+lat+" - Lng:"+lng);
}

Here is the HTML that was used to pass the data:

Address: <input id="address" name="address" type="text" />
 
City: <input id="city" name="city" type="text" />
 
State: <input id="state" name="state" type="text" />
 
Zip: <input id="zip" name="zip" type="text" />
 
<input onclick="submitForm();" type="button" value="Submit" />

August 5, 2008

Javascript broke with multiple line variables from PHP

Filed under: JavaScript,PHP,The Coding World — admin @ 7:26 am

I have several sites where I use a pop up table to display information if the user rolls over and image. Example, if the user wants to view notes on a certain client, they can roll over a little “note” image to view the notes about the client pulled from a SQL database. The code I use for a message may be:

View Code JAVASCRIPT
note[0] = new Array("","<?php echo $message; ?>;");

That would work if $message was all one line. But as with all notes fields, you can never determine when the person entering data hits “Enter”. If the person did hit enter, your javascript would be broke and it would look like this in the source code.

View Code JAVASCRIPT
note[0] = new Array("","This is the start of the note field. I hit enter after this sentence twice.
 
Then I started typeing again");

This broke the Javascript. To fix this you can just swap the hidden special characters with a html line break.

Working code:

View Code JAVASCRIPT
note[0] = new Array("","<?php echo str_replace("\r\n","<br>;", $message); ?>;");

This would return:

View Code JAVASCRIPT
note[0] = new Array("","This is the start of the note field. I hit enter after this sentence twice<br><br>;Then I started typeing again");

July 18, 2008

Creating a Pop Up Window with Javascript

Filed under: JavaScript,The Coding World — admin @ 10:37 am

Here is how to create a simple pop-up window using java script.

This will create a pop-up window on page load:
Place this javascript in the <head>  section of the webpage.

View Code JAVASCRIPT
onload = function () {
  PopUpURL    = "page.php";
  PopUpLeft   =  100;
  PopUpTop    =  100;
  PopUpWidth  =  600;
  PopUpHeight =  300;
   popO='left='+PopUpLeft+',top='+PopUpTop+',width='+PopUpWidth+',height='+PopUpHeight
  window.open(PopUpURL,'nrc',popO);
}

Here is how to create a Pop Up Window from a link:
Place the following code in the <head> section

View Code JAVASCRIPT
var newwindow;
function popup(url)
{
newwindow=window.open(url,'name','height=500,width=333');
if (window.focus) {newwindow.focus()}
}

This part goes in the link tag:

 <a href="javascript:popup('poppedexample.html');">Pop it</a>
© - Digital Epiphany Designs, Online Portfolio for Web Design, Custom Programming, Grapic Design and Game Design.