Thursday, June 13, 2013

How to navigate forward and back to the pages using JavaScript

Follow the steps to navigate forward and back to the pages using JavaScript.
<html>
<head>
<script language='JavaScript' type='text/javascript'>
function goBack() {
     window.history.back();
}
</script>
</head>
<body>
<input type='button' name='back' value='Go Back' title='Click here to go back' onClick='goBack()'>
</body>
</html>
When the user click on the button it will go back to last visited page which means previous page.
We can write this code in another way.
<script language='JavaScript' type='text/javascript'>
function goBack() {
     window.history.go(-1);
}
</script>
This script is also works same as the above script. This is the same as the back button functionality of the browser. Here '-1' represents the previous page.

And we can use this script to load the next URL in in the history list.
<html>
<head>
<script language='JavaScript' type='text/javascript'>
function goForward() {
     window.history.forward();
}
</script>
</head>
<body>
<input type='button' name='forward' value='Go Forward' title='Click here to go Forward' onClick='goForward()'>
</body>
</html>
This is the same as the forward button functionality of the browser.

Thank you...

Wednesday, June 12, 2013

How to do HTTP redirect to a URL using JavaScript

Follow the simple steps to do HTTP redirect to a URL using JavaScript.
<html>
<head>
<script type='text/javascript'>
forwardUrl(); // calling the function to redirect
function forwardUrl() {
     window.location.href = 'http://www.phpboyz.com/page1.php';
}
</script>
</head>
<body></body>
</html>
Change the URL to your url to forward. And call the function to forward.

And we can send the parameters along with the url using this script also.
<script type='text/javascript'>
var value1 = 10;
var value2 = 'testing';
     window.location.href = 'http://www.phpboyz.com/page1.php?param1='+value1+'&param2='+value2;
</script>
This script will forward from current page to requested URL location along with the 2 GET parameters param1 and param2. we can use this 2 parameters where ever we need.
Use $param1 = $_GET['param1'] and $param2 = $_GET['param2'] to get the values in the page1.php.

Thank you...

Friday, April 19, 2013

Navigation menu to show current page link as active - jquery

Hi, now am going to share a small article here, that is how to show current page link as active in navigation  menu using JQuery.
First we need to include JQuery library into the page.
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
before that we need to maintain the left menu in separate page and include it the required pages.
assume take a left menu page leftmenu.php
<div id="left_menu_div">
<ul>
<li id="menuitem1" title="menu item 1"><a href="http://localhost/activemenu/page1.php">Page One</a></li>
<li id="menuitem2" title="menu item 2"><a href="http://localhost/activemenu/page2.php">Page Two</a></li>
<li id="menuitem3" title="menu item 3"><a href="http://localhost/activemenu/page3.php">Page Three</a></li>
<li id="menuitem4" title="menu item 4"><a href="http://localhost/activemenu/page4.php">Page Four</a></li>
</ul>
</div>
then add your css in the page
<style type="text/css">
#left_menu_div ul
{
 list-style-type:none;
 font-size:11px;
 line-height:23px;
 border:0px solid #ccc;
}

#left_menu_div ul li {
 margin-bottom:5px;
 outline: 0;
 padding: 3px 3px 3px 6px;
 display: block;
 font-weight: bold;
 border: 1px solid #1c252b;
 border-left:5px solid #ee6e28;
 border-radius: 4px;
 -moz-border-radius: 4px;
 -webkit-border-radius: 4px;
 box-shadow: 1px 1px 1px rgba(0,0,0,0.2); /* CSS3 */
 -moz-box-shadow: 1px 1px 1px rgba(0,0,0,0.2); /* Firefox */
 -webkit-box-shadow: 1px 1px 1px rgba(0,0,0,0.2); /* Safari, Chrome */
 background:#2a69bf;
 width:180px;
 color:white;
}
#left_menu_div ul li a{
 text-decoration:none;
 font-size:14px;
 color:white;
}

.active {
    background: #0186ba;
 background: -moz-linear-gradient(#04acec,  #0186ba); 
 background: -webkit-gradient(linear, left top, left bottom, from(#04acec), to(#0186ba));
 background: -webkit-linear-gradient(#04acec,  #0186ba);
 background: -o-linear-gradient(#04acec,  #0186ba);
 background: -ms-linear-gradient(#04acec,  #0186ba);
 background: linear-gradient(#04acec,  #0186ba);
 color:red;
 border-radius:0px 3px 3px 0px;
 padding: 3px 0px 3px 5px; 
 margin:-4px -4px -4px -7px;
 width:180px;
}
</style>
and finally include this jquery code in the leftmenu page
<script type="text/javascript">
$(document).ready(function() {
  $currenturl = window.location.href;
  $("#left_menu_div ul li a").each(function() {
   $uurl = $(this).attr('href');
   if($(this).attr('href') == $currenturl){
    $(this).addClass('active');
    }
  });
});
</script>

its over... now you can see the active page link in different than all links.

Thank you...

Monday, April 1, 2013

Find the place name using latitude and longitude in PHP with google geocoder


We can find the place name using google geocoder by giving the Latitude and Longitude.

For example we want to get the place name of the latitude: '17.434545' and longitude: '82.124575' we need to pass this values to the google api to get the place details.

Following code explains how to work with that.

function getPlaceName($latitude, $longitude)
{
   //This below statement is used to send the data to google maps api and get the place
 name in different formats. we need to convert it as required. 
   $geocode=file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?latlng='
                                         .$latitude.','.$longitude.'&sensor=false');

   
   $output= json_decode($geocode);

   //Here "formatted_address" is used to display the address in a user friendly format.
   echo $output->results[0]->formatted_address;
}


We can use this function in PHP. when we execute the above method the following output will be displayed.

call the function as
<?php getPlaceName(17.434545, 82.124575); ?>

Output : Andhra Pradesh 533436, India

Thank you.

Submit Form data using JQuery


Using $.post() method we can post the data to the server and as per the user needs can receive the response from the server.

$.post() method takes 4 parameters.
1. URL : This is the url of a page where we want to send the data to server
2. FormData : This FormData contains all fields data of the form to post
3. Function : This function is used to execute after successful submission of form data, we can receive the response from the server also using this function by taking a parameter.
4. JSON : This parameter is optional to Post method. If we want to receive the JSON encoded response to the Jquery then we need to enable this parameter as 'json', other wise ignore it.

For example take a form like below : (Save this file as textData.php)
<html>
<head>
<title>Test Post</title>
<script type="text/javascript">
//Below JQuery function is used to execute the code when page loads, with out calling any 
functions.
$(document).ready(function() {

    //This is executed when the user click on submit button, here form id is 'myForm'.
    $("#myForm").submit(function() { 

       //This statement will take the url/page name which is defined in the form of action 
       //   attribute. or we can directly give the url/page name here.
        var url = $(this).attr("action"); 

        //This statement is used to collect the form data which is given by user and create 
        //   as a string. example: it will generate as "username=somevalue&password=somevalue".
        var dataString = $(this).serialize();

        //This statement is the post method it will take 4 parameters the first 
//parameter is to where the data need to send, and the second parameter contains the 
//data of form, and the third parameter is used to execute when the JQuery successfully 
//submitted the formdata and receives the response. and the fourth parameter is optional 
//if we want to receive the json data we can use it otherwise ignore it.
        $.post(url, dataString, function(o) { alert(o.message); },'json'); 

        return false;
    });
});
</script>

<form name="myForm" id="myForm" action="serverPage.php" method="post">
User Name : <input type="text" name="username">
Password : <input type="password" name="password">
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>


In the above statement function(o) means after successful submission of the form data the server page can send return data to JQuery in that case this parameter will take it. Initially this parameter is an array. using the array index value we can access the data of the return parameter.

For example: We are taking the parameter name as "o". In this example am sending a $response array to JQuery back after getting the data to server. It contains a "message" value. To use this message in JQuery we need to write like o.message in function.

When user fill the form data and click on submit it will send the data to "serverPage.php" using JQuery Post method.
serverPage.php:
if(isset($_POST['submit']))
{
  $data = array();
  $response = array();

  //Here verifying the data is given or not by the user, we can write this for required fields
  if(isset($_POST['username']) && isset($_POST['password'])) 
  { 
    $data['username'] = $_POST['username'];
    data['password'] = $_POST['password'];
    //Here we can perform any Database operations using this parameters and send 
    // the response as user needs
    $response['message'] = "Data received successfully";
    echo json_encode($response);
  }
  else
  {
    //This will execute if any required fields are not filled by the user, 
    // write any statements here in failed cases
    $response['message'] = "Data not received. Try again!";
    echo json_encode($response);
  }
}

After submitting the form JQuery will show a alert message. if the username and password values is given in the form then it will show "Data received successfully" if any one data is not given by user it will show alert as "Data not received". Thank you.

Thursday, December 27, 2012

JavaScript Form Validations


JavaScript is also used to validate the Form data of HTML pages before sending the data to server.

JavaScript can be validate any type of data.
(Ex. NULL values, Text, Numeric, Email, Date etc.)
For example take a HTML Form like below : ( Save this file as textData.php)
<form name="myForm" action="send_data.php" onsubmit="return validateForm()" method="post">
User Name : <input type="text" name="username">
First Name: <input type="text" name="firstname">
Password : <input type="password" name="password">
Mobile : <input type="text" name="mobile">
Gender : <select name="gender">
               <option value="">Select</option>
               <option value="male">Male</option>
               <option value="female">Female</option>
               </select>
Date of Birth (yyyy/mm/dd) :  <input type="text" name="dateofbirth">
Email Id : <input type="text" name="emailid">
<input type="submit" name="submit" value="Submit">
</form>
Note: If you want to validate any data you should write in the below function only as per the above html code. You can change the function names and field names as per your needs.
function validateForm()
{
      //write below code here if required
      return true;
}
To Test Required Fields :
   
     This script is used to check the username is empty or not, if empty it will promt an alertbox to user with message "User Name Required" and it will focus on the particular username field.
if( document.myForm.username.value == null || document.myForm.username.value == "" )
{
      alert("User Name Required");
      document.myForm.username.focus();
      return false;
}
To Test Text Data or Digits(Numbers) Only:
 
     This script is used to check the field value is text or digits, based on the condition it will prompt an error, other wise ignores.
Here we need to create two expressions based on our requirements to test whether the field value is Text or Number.
var numbexp = /^[0-9]+$/;
var charexp = /^[a-zA-Z]+$/;

if( !document.myForm.firstname.value.match(charexp) )
{
      alert("Please Enter Text Data Only");
      document.myForm.firstname.value = "";  //This is used to remove the data from the field
     document.myForm.firstname.focus();
     return false;
}

if( !document.myForm.mobile.value.match(numbexp) )
{
     alert("Please Enter Numbers Only");
     document.myForm.mobile.value = "";  //This is used to remove the data from the field
     document.myForm.mobile.focus();
     return false;
}
To Test Email Fields :
     This script is used to check the field contains value is valid email or not, it will accept the value only if contains a '@' symbol, a '.' symbol and 2 to 3 charactors after dot symbol. Other wise prompt alert to user.
var emailexp = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if( !document.myForm.emailid.value.match(emailexp) )
{
     alert("Please Enter Valid Email Id");
     document.myForm.emailid.value = "";
     document.myForm.emailid.focus();
     return false;
}
To Check Length of the Field :
     This script used to check the length of the field value, if it has more than 10 characters it will show an alert message, other wise it will ignore.
if( document.myForm.username.value.length >= 10 )
{
     alert("Maximum 10 Characters only");
     document.myForm.username.value = "";
     document.myForm.username.focus();
     return false;
}
     This script is used to validate a value between a given range i.e, minimun and maximum value. Assume username should be Minimum 6 Characters and Maximum 12 Characters
if( document.myForm.username.value.length < 6 || document.myForm.username.value.length >12 )
{
     alert("User Name should contain min 6 characters and max 12 characters");
   document.myForm.username.value = "";
   document.myForm.username.focus();
   return false;
}
To Test Date Format :
     This script is used to check the date format according to your needs. using this expression we can validate the date field mostly.
var dateexp = /^[0-9]{4}\/(0[1-9]|1[012])\/(0[1-9]|[12][0-9]|3[01])+$/;
if( document.myForm.dateofbirth.value.match(dateexp) )
{
     alert("Invalid Date Format... Correct it");
     document.myForm.dateofbirth.focus();
     return false;
}
To Test Select Boxes :
     This script is used to check the select box is selected or not.
if(document.myForm.gender.selectedIndex == 0)
{
      alert("Please Select Gender");
      document.myForm.gender.focus();
      return false;
}

Tuesday, December 25, 2012

Installing and Configuring PHP and MySql with XAMPP in Windows

Xampp is a free web server that interprets php and perl programming language. It's mainly used to test the web application during the development.

Downloading xampp:

Go to the official website of xampp "http://www.apachefriends.org/en/xampp-windows.html" and download the xampp installer.

Installing the xampp:

  • Click on the downloaded xampp installer.
  • A Warning window will opens, click yes
  • Select a language and click OK
  • In the xampp installation wizard click next
  • Click browse, select local disk C or D(Your wish) to install xampp and click OK
  • Click Next
  • Check the buttons for install Apache, MySql and Filezilla as service
  • Click Install
  • Wait till the installation process is complete then click finish
  • Wait for these messages which shows "Congratulations! The installation was successful! Start XAMPP Control Panel now?" and click Yes and OK
  • Then xampp control panel will be opened with running Apache, MySql and FileZilla Services.

If you want to access Xampp control panel manually you can open it from C: or D: Drive >> xampp >> double click on xampp-control file.

Test the Xampp Installation:

  • Open browser and type this url "http://localhost"
  • Choose a language
  • After choosing a language, you should get a page which displays with a left menu of xampp
  • Click on Status on left menu of xampp page to check the status of xampp

Creating a PHP file:

Open Notepad and write the below code:

<?php
phpinfo();
?>

Save the above file in the xampp installed directory.
Example: "C:\xampp\htdocs\index.php"

Executing the PHP file:

Open the browser and type the below URL to execute the above saved php file.
"http://localhost/index.php"

Then the complete information about the installed softwares of xampp will be shown in the html page. here you can check the status of all the things.

Now you can write and execute any number php files in the htdocs.

Happy Coading...