Showing posts with label AJAX. Show all posts
Showing posts with label AJAX. Show all posts

Jul 25, 2012

AJAX Contact Form With Validation

Today I am going to share a simple tutorial on How to make a AJAX contact form with validation.

JQUERY-AJAX



What is AJAX?
AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.


The flow of the form is :


AJAX Process Diagram

So here I am using twitter bootstrap, so files which we need are :-

  • data.php - (here we will write our PHP code)

  • script.js - (here we will write our ajax jquery code)

  • validate.js - (jqueryvalidation plugin)

  • index.php and style.css



So the fields of our form will be Name, Email, Number, City, Area, Message, Submit

Here our city and area will also be using AJAX i.e. on city change area will also be changed.

index.php


[html]
<?php require_once('data.php'); ?>
<div class="hero-unit">
<h2>Contact Us</h2>

<form id="contactUs" name="contactUs" onsubmit="return false;">


<table cellspacing="5" cellpadding="5">
<tr>
<td><label for="name">Name:</label></td>
<td><input type="text" value="" name="name" id="name" class="required name"/></td>
</tr>
<tr>
<td><label for="email">Email:</label></td>
<td><input type="text" value="" name="email" id="email" class="required email"/></td>
</tr>
<tr>
<td><label for="number">Contact Number:</label></td>
<td><input type="text" value="" name="number" id="number" class="required number" minlength="8"/></td>
</tr>
<tr>
<td><label for="city">City:</label></td>
<td>
<select id="city" name="city" onchange="javascript:changeArea('#city', '#area');">
<option value="Any">Any</option>
<?php echo getCities();?>
</select>
</td>
</tr>
<tr>
<td><label for="area">Area:</label></td>
<td><select id="area" name="area" disabled="disabled"></select></td>
</tr>
<tr>
<td><label for="message">Message:</label></td>
<td><textarea id="message" name="message" class="required"></textarea></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="hidden" name="contactFormSubmit" value="Yes" />
<input type="submit" value="Submit" class="btn" onclick="javascript:formSubmit('#contactUs','#responseText');"/>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<div id="responseText"></div>
</td>
</tr>

</form>
</div>
[/html]



Here we just made a simple html structure of form inside a table.

To make a field mandatory, just add class="required" to input.

If you want to validate it with only email or number then add class="required email" or class="required number"

If I add a attribute minlength="8" to the number field then that field should contain at least 8 digits of number.

data.php


[php]
<?php
$cities = array('1'=>'Mumbai',
'2'=>'Chennai',
'3'=>'Noida',
'4'=>'Bangalore');

$areas = array( 'Airoli' => '1',
'Andheri' => '1',
'Bandra' => '1',
'Bhandup' => '1',
'Bhayandar' => '1',
'Boisar' => '1',
'Borivali' => '1',
'Chembur' => '1',
'Gopalapuram' => '2',
'Mount Road' => '2',
'Noida Expressway' => '3',
'Sector 1' => '3',
' Sector 128' => '3',
'Sector 129' => '3',
'Yamuna Expressway' => '3',
'Anekal ' => '4',
'Banashankari ' => '4',
'Banasvadi ' => '4',
'Banaswadi ' => '4',
'Begur ' => '4',
'Bellary Road ' => '4',
'Dobespet ' => '4',
'Electronics City' => '4');


if(isset($_REQUEST['cityID']) && $_REQUEST['cityID'] != 'Any'){

getAreas($_REQUEST['cityID']);

}

if(isset($_REQUEST['contactFormSubmit'])){
if(!isValidEmail($_REQUEST['email'])){
echo 'Enter a valid email ID';
}elseif(!is_mobileNumber($_REQUEST['number'])){
echo 'Enter a valid number';
}elseif($_REQUEST['name'] == '' || $_REQUEST['message'] == ''){
echo 'Enter valid name or message';
}else{
?>
<p><b>Thank you for contacting us, your given information : </b></p>
<table cellspacing="5" cellpadding="5" border="1">
<tr>
<td>Name:</td>
<td><?php echo $_REQUEST['name']?></td>
</tr>
<tr>
<td>Email:</td>
<td><?php echo $_REQUEST['email']?></td>
</tr>
<tr>
<td>Contact Number:</td>
<td><?php echo $_REQUEST['number']?></td>
</tr>
<tr>
<td>City:</td>
<td><?php echo $_REQUEST['city']?></td>
</tr>

<?php if(isset($_REQUEST['area'])) : ?>
<tr>
<td>Area:</td>
<td><?php echo $_REQUEST['area']?></td>
</tr>
<?php endif; ?>

<tr>
<td>Message:</td>
<td><?php echo $_REQUEST['message']?></td>
</tr>
</table>
<?php
}
}



function getCities(){
global $cities;
foreach($cities as $Idx => $city){

echo '<option value="'.$Idx.'">'.$city.'</option>';

}
}

function getAreas($cityID = ''){
global $areas;
foreach($areas as $area => $Idx){

if($Idx == $cityID){

echo '<option value="'.$Idx.'">'.$area.'</option>';

}

}
}

function isValidEmail($email){
return eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email);
}

function is_mobileNumber($mobile) {
$regex1 = '123456789';
$regex2 = '1234567890';
$regex3 = '0123456789';

if(preg_match('/^([0-9])\1*$/', $mobile)){
return false;
}elseif($mobile == $regex1){
return false;
}elseif($mobile == $regex2){
return false;
}elseif($mobile == $regex3){
return false;
}elseif(preg_match("/[^0-9]/", $mobile)){
return false;
}else{
return true;
}
}
?>
[/php]



PHP code is simple, I am making an array of cities and area, made 2 functions to get areas and cities and getting the parameters from URL and passing it to functions.

Now the ajax function :

script.js


[js]
function changeArea(cityBox, areaBox) {
jQuery(function($) {

$(areaBox).attr('disabled','disabled');

$(areaBox).addClass('loading');
$.ajax({ //Starting the AJAX
url : 'data.php', //File to be called or pass the data
data : { //Extra paramters
"cityID" : $(cityBox+' option:selected').attr('value')
},
success : function(data) { // The result from data.php file comes as data
window.setTimeout(function(){
$(areaBox).removeAttr('disabled');

$(areaBox).removeClass('loading');

$(areaBox).html('');

$(areaBox).html(data);

}, 2000);
}
});
});
}
[/js]



The above function is is taking two parameters, the select id of City and area. Then I am saving the value of city in a variable, and inside ajax I am passing the value of city to data.php file.

Inside data.php I wrote a function to return areas according to the city ID. Inside success function I am inserting entire result into the area select box.

Simlarly I am going to make another function which will validate the form and if no error then ajax is called and mail is sent.

script.js


[js]
/* Submission of form */

function formSubmit(formID, displayMssgID) {
jQuery(function($) {

var qstring = $(formID).serialize();

var val = $(formID).validate().form();
if (val) {
$(displayMssgID).html('Registering your Request ... Please Wait ...');
$.ajax( {
url : "data.php",
data : qstring,
success : function(data) {

$(displayMssgID).html('');
$(displayMssgID).html(data);
window.setTimeout(function() {

$(displayMssgID).fadeOut();

}, 6000);

}
});
}
});
}
[/js]



This function takes two parameters, ID of the form and result message div. First I am serializing the form, which will take all the form data and store it in a variable. Then I am validating it, if validation is true then our AJAX is called and entire form data is passed to data.php file.

This is return will give some output which I am showing it in id="responseText"

This is a simple way to make AJAX forms, there might be many other tutorials on other websites but I find this very simple. This way you can make any AJAX form. Try out the demo.



Thanks to Jacob for server validation tip.

Jan 15, 2012

Google Maps Server Side Geocoding Using PHP and Infobox Fully AJAX

Recently I got a new project of real estate where I had to display about 1000 of projects on the google map. I was having the address of 1000 projects, so I started with my php and js code. When I coded and started testing, I found that on the map only 20-30 markers were shown. When I debugged I found an error of OVER_QUERY_LIMIT. I started googling and found that Geocoding has some limitations on converting address into lat long. In API there are two ways of getting LAT LONG.

  • Client Side

  • Server Side


Client side geocoding has some limitation of 20 queries per minute or sec. Server side geocoding also has limitations but after 2500 queries.

google-map

 

So in this tutorial we will first code our simple HTML then PHP and finally our AJAX.

HTML is pretty short and simple.

Filename: index.php

 
[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" xml:lang="en" lang="en">
<head>
<title>Google Server Side Geocoding Using PHP and Infobox Fully AJAX</title>

<style>
#wrapper{width:1002px; margin:0px auto;}
#loading {
position: relative;
text-align: center;
top: 45%;
}
</style>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&language=en"></script>
<script type="text/javascript" src="http://google-maps-utility-library-v3.googlecode.com/svn-history/r290/trunk/infobox/src/infobox.js"></script>
<script type="text/javascript" src="http://localhost:8080/gmap/google.js"></script>

</head>

<body>
<div id="wrapper">
<div id="googlemaps" style="width:500px; height:500px;position:relative;border:1px solid #888888;margin: 0 auto;">
</div>
</div>
</body>
</html>
[/html]
 

Here we are leaving a blank div, which will be filled with our google map.

In our PHP code, we can call the addresses either from database or an array. I am using array in this tutorial.

In server side geocoding we actually pass our address through an URL which returns a CSV or json formatted data.

Then we extract the lat long from this data using explode function and store it in an array. This array is passed to our AJAX function in json formatted.

Filename: gmap.php
 
[php]
<?php
$address = array(
"1" => array("Address" => "Bandra, Mumbai, India" , "Name" => "Bandra"),
"2" => array("Address" => "Khar, Mumbai, India" , "Name" => "Khar"),
"3" => array("Address" => "Santacruz, Mumbai, India" , "Name" => "Santacruz"),
"4" => array("Address" => "Andheri, Mumbai, India" , "Name" => "Andheri"),
"5" => array("Address" => "Jogeshwari, Mumbai, India" , "Name" => "Jogeshwari"),
"6" => array("Address" => "Goregaon, Mumbai, India" , "Name" => "Goregaon"),
"7" => array("Address" => "Malad, Mumbai, India" , "Name" => "Malad"),
"8" => array("Address" => "Kandivili, Mumbai, India" , "Name" => "Kandivili"),
"9" => array("Address" => "Borivali, Mumbai, India" , "Name" => "Borivali"),
"10" => array("Address" => "Dahisar, Mumbai, India" , "Name" => "Dahisar"),
"11" => array("Address" => "Mira Road, Mumbai, India" , "Name" => "Mira Road"),
"12" => array("Address" => "Bhayander, Mumbai, India" , "Name" => "Bhayander"),
"13" => array("Address" => "Naigaon, Mumbai, India" , "Name" => "Naigaon"),
"14" => array("Address" => "Vasai, Mumbai, India" , "Name" => "Vasai"),
"15" => array("Address" => "Nallasopara, Mumbai, India" , "Name" => "Nallasopara"),
"16" => array("Address" => "Virar, Mumbai, India" , "Name" => "Virar"),
"17" => array("Address" => "Churchgate, Mumbai, India" , "Name" => "Churchgate"),
"18" => array("Address" => "Charni Road, Mumbai, India" , "Name" => "Charni Road"),
"18" => array("Address" => "Grant Road, Mumbai, India" , "Name" => "Grant Road"),
"19" => array("Address" => "Dadar, Mumbai, India" , "Name" => "Dadar"),
"20" => array("Address" => "Mahim, Mumbai, India" , "Name" => "Mahim"),
"21" => array("Address" => "King Circle, Mumbai, India" , "Name" => "King Circle"),
"22" => array("Address" => "Worli, Mumbai, India" , "Name" => "Worli"),
);

foreach($address as $Idx => $key){
$addr = urlencode($key['Address']);
$url = 'http://maps.google.com/maps/geo?q='.$addr.'&output=csv&sensor=false';
$get = file_get_contents($url);
$records = explode(",",$get);
$lat = $records['2'];
$lng = $records['3'];

$data[] = array('Lat'=>$lat, 'Lng'=>$lng, 'Name'=>$key['Name']);

}
echo json_encode($data);
?>
[/php]
 

Now we call our ajax function on the load of the page.

Filename: google.js

 
[js]
jQuery(function($) {
$(document).ready(function() {
getAdress();//On page load initialize our map function.
});
});
[/js]
 

We will use infobox to create stylish markers and windows. When we load our function on page load, this function consists with an AJAX call, which gets the data from our gmap.php file, which will be in JSON formatted. We convert it into normal array using JSON.parse(). Finally we throw this array into foreach loop and store the lat, long values in a variable.

 

These lat long variables are also an array so one more for loop and then we pass it to our createmarker function which will be creating the markers on map.

Filename: google.js

 
[js]
function getAdress() {
jQuery(function($) {
$("#googlemaps").html('<div id="loading"><img src="loading.gif" /></div>');
$.ajax( {
url : "gmap.php",
type : "GET",
success : function(data) {
// get the data string and convert it to a JSON object.
var jsonData = JSON.parse(data);
var latitude = new Array();
var longitude = new Array();
var name = new Array();
var logo = new Array();
var i = 0;
var j = 0;
var k = 0;
$.each(jsonData, function(Idx, Value) {
$.each(Value, function(x, y) {
//Creating an array of latitude, logitude
if(x == 'Lat')
{
i = i + 1;
latitude[i] = y;
}
if(x == 'Lng')
{
j = j + 1;
longitude[j] = y;
}
if(x == 'Name')
{
k = k + 1;
name[k] = y;
}
});
});
$("#googlemaps").html('');
//passing the array to initialize function, where our map will be formed
initialize(latitude,longitude,name, logo);
}
});
});
}
function initialize(latitude,longitude, name, logo) {

//initialization of map.
var geocoder = new google.maps.Geocoder();
var initCenter = new google.maps.LatLng(19.0759837, 72.87765590000004);//By default Mumbai is loaded
var map = new google.maps.Map(document.getElementById('googlemaps'), {
zoom: 11,
center: initCenter,
mapTypeId: google.maps.MapTypeId.ROADMAP
});

//initialization of infowindow
var infoWindow = new google.maps.InfoWindow;
var boxText = document.createElement("div");

var j = 1;
var image = new google.maps.MarkerImage('icon-home.gif');//Setting the marker image

//Infowindow is fully customizable, here we make our infowindow stylish by adding css styles to it.

var myOptions = {
content: boxText
,disableAutoPan: false
,maxWidth: 181
,zIndex: null
,boxStyle: {
background: "#000000"
,color: "#fff"
,width: "auto"
,padding: "10px"
,borderRadius: "20px"
,fontFamily: "Tahoma"
,opacity: "0.5"
}
,infoBoxClearance: new google.maps.Size(1, 1)
,isHidden: false
,pane: "floatPane"
,closeBoxURL: ""
,enableEventPropagation: false
};
var ib = new InfoBox(myOptions);

//Final for loop for creating the markers
for(var a = 1; a < latitude.length; ++a)
{
createMarkers(geocoder, map, name[a], latitude[a], longitude[a], ib, image);
}
}


function createMarkers(geocoder, map, name, latitude, longitude, ib, image) {

//Setting the onclick marker function
var onMarkerClick = function() {
var marker = this;
var latLng = marker.getPosition();
ib.setContent(name);
ib.open(map, marker);
};

google.maps.event.addListener(map, 'click', function() {
ib.close();
});

//In array lat long is saved as an string, so need to convert it into int.
var lat = parseFloat(latitude);
var lng = parseFloat(longitude);

var marker = new google.maps.Marker({
map: map,
icon: image,
position: new google.maps.LatLng(lat, lng),
title: name
});

//Adding the marker.
google.maps.event.addListener(marker, 'click', onMarkerClick);
}
[/js]
 

This above js file can be minified further, there are other ways of getting the data, but I found this very simple and easy. You can check the live demo. Any suggestions are welcome. Happy geocoding

Oct 26, 2011

Insert Record Into Database Using AJAX | How To Insert Data Into Database Using AJAX

In todays tutorial, I am going to teach you, HOW AJAX WORKS. This tutorial is good for people who are seeking on internet to learn AJAX with PHP and MYSQL.

I am going to share a AJAX Driven tutorial with you, in which we will insert a record in our Database through AJAX, which means data will be added into database, without refreshing the page and we will also show the added values.

So lets start this, first we need to setup a folder structure.
Make a folder and inside it, add three files,

  • index.php

  • data.php

  • ajax.gif


Now we will add basic html code into our index.php file

[html]

<body>
<div id="wrapper">
<input type="text" id="name" value="Your Name" />
<input type="button" value="Submit" onclick="addRecord()" />
<div id="propspectDiv"></div>
<table id="data" border="1" cellspacing="0" cellpadding="0" width="75" style="display:none;"></table>
</div>

</body>

[/html]

Now comes the main AJAX code.

Inside your head tag, add the following code:

[html]

<script src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">

function addRecord()
{
var term_name = $('#name').val();        //Storing the value of textbox into a variable

if(term_name == '')        //Checking for NULL
{
$('#propspectDiv').html('Enter A Valid Name');    //Prints the progress text into our Progress DIV
$('#name').addClass('error');                    //Adding the error class to the progress DIV
return;
}
else{
$('#name').removeClass('error');
$('#propspectDiv').removeClass('error'); //Removing the error class from the progress DIV
$('#propspectDiv').html('Submitting your Request.<img src="ajax.gif" />');//Prints the progress text into our Progress DIV

$.ajax({
url : 'data.php', //Declaration of file, in which we will send the data
data:{
"name" : term_name                //we are passing the name value in URL
},
success : function(data){
window.setTimeout(function(){
$('#propspectDiv').html('Your Name is added to our records'); //Prints the progress text into our Progress DIV
$('#data').css("display","block");  //Changes the style of table from display:none to display:block
$('#data').html(data);                //Prints the data into the table
}, 2000);
}
});
}
}

</script>

[/html]

Explanation:

In our AJAX function first we are storing the value of textbox in a variable.
Then we check whether the variable is not passed NULLED, if condition is satisfied, then it enters to a condition, where it adds some HTML code into progress div.

Finally we call our AJAX function, where we pass the "name" value to our file data.php through URL. data.php file echoes some values and inserts name into our database.

We call this echoed values and display it in our table.

data.php code

[php]

<?php
$name = $_REQUEST['name'];

$con = mysql_connect("localhost","root","");

mysql_select_db("test", $con);

$sql = 'INSERT INTO `test`.`name` (`ID`, `Name`) VALUES (NULL,"'.$name.'")';

if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
else{
$sqlnew = 'SELECT * from name;';
$res = mysql_query($sqlnew);
echo '<tr><th>Name:</th></tr>';
while($row = mysql_fetch_array($res))
{
echo '<tr><td>'.$row['Name'].'</td></tr>';
}
}

mysql_close($con);
?>

[/php]

Conclusion:
Here we are learning the basics of JQUERY AJAX, if you understand the main concept and the flow of AJAX with PHP, then with the help of google you can make many ajax driven programs.

Final Output:


download


download

Sep 11, 2011

Fully AJAX Alphabetical Sorting | Sorting Titles Alphabetical Using AJAX

AJAX? What the hell is AJAX? In short, the script which fetches data from database without refreshing the page is AJAX. AJAX's full form is Asynchronous JavaScript And XML. The best AJAX example you can find is GMAIL.

OK, so today I am sharing with you a tutorial where with the help of AJAX you will call all titles from the database and display it in Alphabetical order.

First, we will create a database, in my case its ci. inside it we will create two fields ID and title. Give ID as primary key and set it to auto increment.

Then fill the tables with some dummy data.

After that make a folder named as ajax and create following files in it.

  1. newContent.php

  2. index.php


Now Open index.php and paste the following code in it:-

[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" xml:lang="en" lang="en">
<head>
<title>WebsTutorial Fully AJAX Sorting</title>
<style type="text/css">

.letter{
cursor: pointer;
text-decoration:underline;
font-size:18px;
text-transform:uppercase;
font-family:tahoma;
padding:2px;
}
#ajax{padding:10px;
background:#e9e9e9;
width:190px;
height:auto;
}
#content1{border:2px solid #e7e7e7; background:#e3e3e3;padding:8px;
width:190px;
height:auto;
text-transform:uppercase;
background-image:url("grey-gradient.jpg");
background-repeat:repeat-x;
background-position:left top;
}

#Loading{}
</style>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
</head>

<script type="text/javascript">

jQuery(function($) {
$(document).ready(function() {
$("#Loading").hide();
$(".letter").bind('click', function(){
$("#Loading").fadeIn(); //show when submitting
var val = $(".letter").val;
$.ajax({
url:'newContent.php?letter='+$(this).html(),

success:function(data){
$("#Loading").fadeOut('fast'); //hide when data's ready
$("#content").html(data);
}
});
});
});
});
</script>

<div id="ajax">
<span>a</span>
<span>b</span>
<span>c</span>
<span>d</span>
<span>e</span>
<span>f</span>
<span>g</span>
<span>h</span>
<span>i</span><br>
<span>j</span>
<span>k</span>
<span>l</span>
<span>m</span>
<span>n</span>
<span>o</span>
<span>p</span>
<span>q</span>
<span>r</span><br>
<span>s</span>
<span>t</span>
<span>u</span>
<span>v</span>
<span>w</span>
<span>x</span>
<span>y</span>
<span>z</span>
<span>#</span>
</div>

<div id="Loading"><img src="loader.gif" /></div>
<div id="content"></div>
</html>

[/html]

Explanation:-
In the above code, rest is just basic HTML but the main thing is AJAX calling.

  • First we are creating a function where, onclick event of letter class, a variable is declared and the clicked letter value is stored in newly created variable.

  • Then we call AJAX and pass the variable to the newContent.php file.

  • newContent.php file takes the value and checks into database and returns back database value to the AJAX function.

  • Then finally database passed value is displayed in #content div.


Now we will write some code in newContent.php file.

Paste the following code in it:-

[php]
<?php
echo $_GET['letter'];
echo '<br>';
echo '<br>';
$getLetter = $_GET['letter'];

$con = mysql_connect('localhost', 'root', '');
mysql_select_db("ci", $con);
$result = mysql_query('SELECT * FROM test where title LIKE "'.$getLetter.'%"');

while($row = mysql_fetch_array($result))
{
echo $row['title'] . '<br>';
}
?>
[/php]

Explanation:

  • First we store the value of letter passed from AJAX to a variable named as $getLetter.

  • Then we open a connection to the database, please edit this piece of code according to your database name, user and password.

  • After opening the connection, we fire a SQL query where we state, fetch all the title where the first letter starts from $getLetter.

  • As it will return in array, so we will split it with the help of while loop.

  • Done the echoed value will be displayed in the index.php file.


This tutorial explain how basic AJAX works, you will find that in some place the image loading code is written, thats nothing but a loading image, which will appear when data is heavy and takes time to fetch.

Final Output:

AJAX


download