Recent Articles

Monday, January 6, 2014

Easy to use Bootstrap Date Range Picker

Monday, January 6, 2014 - 0 Comments

Hiiii, Being a developer ,many times it happen that you need a date picker on your website mainly on forms. jQuery has provide a very simple date picker to apply on input fields but that date picker is not so attractive CSS wise and it selects only a single  date. What if you want to select both "from date" and "to date", "from date" and "to date" with time or you want to select dates like : yesterday date, last seven days, last month.For the selection of these different types of date, Bootstrap has introduced a daterange picker to provide all the above discussed functionality and one more good thing about this daterangepicker is that it looks attractive due to bootstrap CSS.
So, in this post ,I will be giving a one by one demo of three different types of date range pickers with one picking just "from date" and "to date", second one will also choose the time and third one will select dates like last month, last week, yesterday,etc.

To run the tutorials given below , download the complete set of Javascript and css from here.

Fistly, include all the Javascript and CSS files in this package from the link above and some extra files needed for this tutorial in your code as shown below :
 <link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">
 <link rel="stylesheet" type="text/css" media="all" href="daterangepicker-bs3.css" />      // Provided in the package
 <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
 <script type="text/javascript" src="moment.js"></script>      // Provided in the package
 <script type="text/javascript" src="daterangepicker.js"></script>      // Provided in the package 



Date Range Pickers:

1. Simple Date Range Picker:

This is just a date picker which gives you a functionality of just adding "to date" and "from date". This is very easy to implement and it is just applied by giving id attribute to an input field and then applying a daterangepicker on that particular id. Code and screen shot as given below : 

Simple Date Range Picker:


<form class="form-horizontal">
  <fieldset>
    <div class="control-group">
      <label class="control-label" for="selectdaterange">Select Date Range:</label>
      <div class="controls">
        <div class="input-prepend">
          <span class="add-on"><i class="icon-calendar"></i></span><input type="text" name="selectdaterange" id="selectdaterange" />
        </div>
      </div>
    </div>
  </fieldset>
</form>
 
<script type="text/javascript">
$(document).ready(function() {
    $('#selectdaterange').daterangepicker();
});
</script>


2. Date Range Picker with Time :

This is a date range picker which gives you an additional functionality of adding a Time  with that provided by the simple Date Range Picker. This is also easy to implement and is implemented in the same way as the Date Range Picker shown above by applying it on form input field. Code and screen shot as given below : 

Date Range Picker with Time

<form class="form-horizontal">
  <fieldset>
    <div class="control-group">
      <label class="control-label" for="dateandtime">Reservation dates:</label>
      <div class="controls">
        <div class="input-prepend">
          <span class="add-on"><i class="icon-calendar"></i></span><input type="text" name="dateandtime" id="dateandtime"/>
        </div>
      </div>
    </div>
  </fieldset>
</form>
 
<script type="text/javascript">
$(document).ready(function() {
  $('#dateandtime').daterangepicker({ timePicker: true, timePickerIncrement: 30, format: 'MM/DD/YYYY h:mm A' });
});
</script>


3. Date Range Picker With Custom Dates :

This is a date range picker which gives you a functionality of choosing different types of date range like last month , last week, yesterday etc. It is somewhat easy and may be difficult for those who are unaware of jQuery implementation as this date range picker is not applied to form input field rather it is implemented on some div but to enter the value of date selected to the form input values, you have to use jQuery. Code and screen shot as given below : 

Date Range Picker With Custom Dates

            <h4>Select Date Range With Options</h4>

            <div class="well" style="overflow: auto">

               <div id="reportrange" class="pull-left" style="background: #fff; cursor: pointer; padding: 5px 10px; border: 1px solid #ccc">
                  <i class="glyphicon glyphicon-calendar icon-calendar icon-large"></i>
                  <span></span> <b class="caret"></b>
               </div>

               <script type="text/javascript">
               $(document).ready(function() {
                  $('#reportrange').daterangepicker(
                     {
                        startDate: moment().subtract('days', 29),
                        endDate: moment(),
                        minDate: '01/01/2012',
                        maxDate: '12/31/2014',
                        dateLimit: { days: 60 },
                        showDropdowns: true,
                        showWeekNumbers: true,
                        timePicker: false,
                        timePickerIncrement: 1,
                        timePicker12Hour: true,
                        ranges: {
                           'Today': [moment(), moment()],
                           'Yesterday': [moment().subtract('days', 1), moment().subtract('days', 1)],
                           'Last 7 Days': [moment().subtract('days', 6), moment()],
                           'Last 30 Days': [moment().subtract('days', 29), moment()],
                           'This Month': [moment().startOf('month'), moment().endOf('month')],
                           'Last Month': [moment().subtract('month', 1).startOf('month'), moment().subtract('month', 1).endOf('month')]
                        },
                        opens: 'left',
                        buttonClasses: ['btn btn-default'],
                        applyClass: 'btn-small btn-primary',
                        cancelClass: 'btn-small',
                        format: 'MM/DD/YYYY',
                        separator: ' to ',
                        locale: {
                            applyLabel: 'Submit',
                            fromLabel: 'From',
                            toLabel: 'To',
                            customRangeLabel: 'Custom Range',
                            daysOfWeek: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr','Sa'],
                            monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
                            firstDay: 1
                        }
                     },
                     function(start, end) {
                      console.log("Callback has been called!");
                      $('#reportrange span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
                     }
                  );
                  //Set the initial state of the picker label
                  $('#reportrange span').html(moment().subtract('days', 29).format('MMMM D, YYYY') + ' - ' + moment().format('MMMM D, YYYY'));
               });
               </script>

            </div>

This above defined Date Range Picker with options doesn't apply on input fiield as it is applied on <div> so to use the values of the dates selected with options in this div, we have to insert the values of the selected date to the hidden input fields in the form and then when you submit that form , then you can use that values via GET or POST method to get the data. So you have to update the above provided code with the modied code a shown below :

Firstly you have to create to hidden input fields as shown below :
<input type="hidden" name="to" id="to" value="">
<input type="hidden" name="from" id="from" value="">

Secondly you have to update the  function (start, end) highlighted above to the function as shown below :
function(start, end) {
                      console.log("Callback has been called!");
                      $('#reportrange span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
       $('#to').val(start.format('MMMM D, YYYY'));
       $('#from').val(end.format('MMMM D, YYYY'));
                     }



Hope you like this post……..Please Comment…………!!!!!!!!!

Sunday, December 22, 2013

How to Set and Use Cookies in PHP

Sunday, December 22, 2013 - 0 Comments

Hiiiiii, as the title of this post suggests, this post is all about the concept of COOKIES as provided by PHP. We will here first see what does cookies means in php and then we'll see some examples of how to use these cookies in you code.

PHP Cookies

What are Cookies :

Cookies are mainly the files stored at you computer when you run any website in your browser. Usually these cookies files contains information about the user' login details when he/she login with "Remember Me" option, user id and name of a person logged in, user's current status or progress on any particular site so that whenever he login again he will be resumed from that particular progress. Cookies are stored in users browser for a limited span of time which is defined by the developer of a site which is setting a cookies in your computer system.

 

Using Cookies in PHP :

Syntax-

Cookies are having a very simple for their usage as shown below :

setcookie(name, value, expire, path, domain);

Here, setcookie is the php function to set cookies,
name is the name of the cookie variable (mandatory),
value is the value of that cookie variable whose name you have mentioned in "name" (mandatory),
expire is the time span for which you want the cookie to be saved in users's browser (mandatory),
path is the directory path if you want to set cookie for the particular directory on your site (optional), and
domain is the domain name of site on which you want to set cookie for some particular path directory (optional).

There are two more parameters in this setcookie function which are also optional namely secure and httponly, with this two variables,the syntax becomes-

setcookie(name, value, expire, path, domain, secure, httponly);

Both of these variables (secure and httponly) are boolean and accept only TRUE or FALSE in terms of values. If value of secure is set to TRUE then the cookie will only be sent to client system from the site server if the connection from the client to website is secure HTTPS.
If the value of httponly is set to TRUE then cookies will only be accessible by HTTP protocol and none of the scripting languages like javascript will be able to access the cookies.

Example To set Cookie:

Example 1:

setcookie("username","Deepaanshu",time() + (86400 * 7)); // 86400 seconds denotes 1 day
 

The above used method will create a cookie with cookies variable namely "username" having a value - "Deepaanshu" and "time() + (86400 * 7)" indicates that the cookie will automatically delete on the 7th day from now.

Example 2:

$username="Deepaanshu";
setcookie("username",$username,time() + (86400* 15),'/~design/','example.com',true,true);
 

This example will create a cookie with cookies variable namely "username" having a value - "Deepaanshu" for next 15 days from now and "/~design/","example.com" indicates that this cookie will applied on "design" directory on "example.com" domain. As this cookie is having a two true values at the last so, this cookie will only be created on user pc if connection from his side is HTTPS and this cookie will not accessible by javascript.

Example To Get Cookie variables: 

if(isset($_COOKIE['username']))
{
 $login_user_name=$_COOKIE['username'];
}
else
{
 $login_user_name="Guest";
}
echo 'Welcome Back '.$login_user_name;  // This will echo Welcome Back Deepaanshu if $_COOKIE['username'] is set with a value "Deepaanshu" 

Deleting Cookies :

To delete a cookie you don't have any unset function like sessions but rather you can make the cookie expire by giving it a time earlier then the current time and making its value blank.

setcookie("username", "", time() - 3600);  //this will make the cookie to expire as time given to it is a hour ago from current time. 


Hope you like this post……..Please Comment…………!!!!!!!!!

 

Wednesday, December 18, 2013

Different Types of AJAX Usage with Examples

Wednesday, December 18, 2013 - 0 Comments

Hiiiii, Being a web developer, you have used ajax many times for submitting form and then serializing the data of form to send the data on the same page or on a next page.
You may used this ajax with many different syntax like : you have used dataType:"json" before data sending or you may have used "parsed_data = jQuery.parseJSON(data)" after the don or success function after getting the response.
Some people use these different syntax without being aware of the meaning of these different syntax.
So, here in this I'll be showing two examples explaining the difference between these two syntax and usage.

AJAX USAGE

AJAX USAGE 1 :

 $.ajax({  
 type: "POST",
 url: "post1.php",
 data: // YOUR DATA TO SEND 
 }).done(function( data ) {

 parsed_data = jQuery.parseJSON(data);
 alert(parsed_data.response1);
 alert(parsed_data.response2);    
});

AJAX USAGE 2 :

 $.ajax({  
 type: "POST",
 url: "post1.php",
 dataType: "json",
 data: // YOUR DATA TO SEND
 }).done(function( data ) {
    
 alert(data.response1);
 alert(data.response2);    
});

In the Ajax usage 1 we haven't used dataType:"json" and rather we have used parsed_data = jQuery.parseJSON(data) in the response function of ajax when response is received through ajax . We have used this jQuery.parseJSON(data) to decode and parse the encoded JSON which is received in ajax response from the page on which you sent the data. The encoded  JSON response which you will getting in response for both the usage of ajax shown here will be of the form : 

{"response1":"Hello","response2":"World"}

After using this jQuery.parseJSON(data) as shown in Ajax Usage 1 , you can use the value of each of the variables in response JSON by :

data.response1 , data.reponse2, etc , both of these variables will give Hello , World  respectively .
In the Ajax Usage 1, Ajax is unaware that the data in response in Ajax so we manually have to decode and parse that response data to use the variables in it. This usage is used for both the condition when you are getting JSON as response  or you are getting a normal response other then JSON  To use the response data which is not in a JSON form then just remove the line with jQuery.parseJSON(data) and directly use the response data.


In Ajax Usage 2, we have used dataType:"json" in the Ajax settings before sending the data through Ajax in place of parsed_data = jQuery.parseJSON(data) in the response function of ajax. In this we are prior telling the Ajax that the data that will we received will be just in the JSON form and not in any other form. So, Ajax here automatically parse that JSON encoded data of the form as shown above and to use the variables in this data response you can use the same syntax as defined above like data.response1 , data.reponse2,etc. This usage is used where the response data which is received is just of the JSON form. If here you try to use the data directly not of the JSON form, you will get nothing in data. 


Hope you like this post……..Please Comment…………!!!!!!!!!


Monday, December 16, 2013

Using PHP Date() function to display Date and Time in Different Formats

Monday, December 16, 2013 - 0 Comments

Hiiii, We all know that managing Dates and Dates formats is a very important work when it comes to using dates in programming or when you have to use the dates fetched from the database in the format other then as it is saved in database.
In PHP, some people mostly beginners find it difficult to deal with date and time with different formats like 24 hour or 12 hour, some find it difficult to get current date/ time, you current timezone with GMT difference. 
Mostly people face trouble in the situation where a person has to change the format of the the data fetched from database or date got from the form fields.
So, here in this post I'll be telling you how to use PHP Date() with its different forms to gets every date time related data as possible like-  current date/ time, custom date with different formats, custom time with different formats and changing the format of date fetched from the database .      

PHP DATE FUNCTION

DEMO BEGINS :


<?php 
 // Connection to mysql
 $link = mysql_connect('localhost', 'root', 'root');
 if (!$link) {
 die('Not connected : ' . mysql_error());
 }

 // Selecting Database
 $db_selected = mysql_select_db('wordpress', $link);
 if (!$db_selected) {
 die ('Can\'t use wordress : ' . mysql_error());
 }

 $query="select wp_posts.post_date from wp_posts where wp_posts.ID=27";
 $line=mysql_query($query);
 $result=mysql_fetch_assoc($line);
 $post_date=$result['post_date'];
 echo $post_date."<br/>";        // prints in this format-  2013-10-31 07:59:13
 
 echo date('d M Y', strtotime($post_date))."<br/>";  // prints in this format- 31 Oct 2013 
 
 echo date('d/m/y', strtotime($post_date))."<br/>";  // prints in this format- 31/10/13
 
 echo date('D', strtotime($post_date))."<br/>";   // prints in this format- Thu
 
 
 // Taking Custom Dates
 $date="2013-01-07";
 echo date('d M Y', strtotime($date))."<br/>";   // prints in this format- 31 Oct 2013 with leading zeros
 
 echo date('j M Y', strtotime($date))."<br/>";   // prints in this format- 31 Oct 2013 without leading zeros
 
 
 // Time notations
 echo date('H:i:s', strtotime($post_date))."<br/>";  // prints in this format- 07:59:13
 
 echo date('H:i:s a', strtotime($post_date))."<br/>"; // prints in this format- 07:59:13 am
 
 echo date('H:i:s A', strtotime($post_date))."<br/>"; // prints in this format- 07:59:13 AM
 
 
 // Taking Custom TIme
 $time="15:30:41";
 echo date('h:i:s A', strtotime($time))."<br/>";   // prints in this format- 03:30:41 PM in 12h format
 
 echo date('H:i:s A', strtotime($time))."<br/>";   // prints in this format- 03:30:41 PM in 24h format without trailing zeros
 
 echo date('g:i:s A', strtotime($time))."<br/>";   // prints in this format- 03:30:41 PM in 12h format
 
 echo date('G:i:s A', strtotime($time))."<br/>";   // prints in this format- 03:30:41 PM in 24h format without trailing zeros
 
 echo date('O')."<br/>";         // prints the Difference to Greenwich time (GMT) in hours
 
 
 // Current Date and Time
 echo "Current Date :".date('d M Y')."<br/>";
 echo "Current Time :".date('h:i:s A');
?>

Hope you like this post……..Please Comment…………!!!!!!!!!

Thursday, December 5, 2013

Easy PHP User Login System (Database User Validation)

Thursday, December 5, 2013 - 0 Comments

Hiiiiii, people who are new-new php developers came across a situation when they have to develop a user login system. It seems to be a  very hard to develop login system by validating user details from database for the new developers but actually this task is very. You can send the username and password values to the next page or same page by just html form POST method or using AJAX. But this tutorial is  taking into cosideration that a developer is not having or completely unaware of knowledge of how to use AJAX for data sending , So, we will be just using core php to implement a login system.

I this tutorial, user is validated with the values exist i database, session variables like user id & username are set so that you can use that variables on anyother pages, form variables are sent to next page.

Demo :

PHP Login System

Code Begins :

File Structure : 
Main Directory --
--> check.php
--> index.php
--> home.php


check.php :

<?php
$link = mysql_connect('localhost', 'root', '');
if (!$link) {
    die('Not connected : ' . mysql_error());
}

$db_selected = mysql_select_db('test', $link);
if (!$db_selected) {
    die ('Can\'t use test table : ' . mysql_error());
}

$username=$_POST['username'];
$password=$_POST['password'];

$query="select * from user where username='".$username."'";
$result=mysql_query($query);
$records=mysql_fetch_array($result);

if($records)
{
 if($password==$records['password'])
 {
  session_start();
  $_SESSION['username']=$records['username'];
  $_SESSION['userid']=$records['id'];
  header('Location: home.php');
 }
 else
 {
  $msg="Password Incorrect";
  header('Location: index.php?msg='.$msg);
 }
}
else
{
 $msg="Username Incorrect";
 header('Location: index.php?msg='.$msg);
}
?>

index.php :

<!DOCTYPE HTML>
<html>
<head>
<title>Login System</title>
</head>
<body>

<h1>Login Form</h1>
<?php

if(isset($_GET['msg']))
{
 $msg=$_GET['msg'];
 echo '<p><font color="red">';
 echo $msg;
 echo '</font></p>';
}
?>
<form action="check.php" method=POST>
  <label for="username">Username</label>
  <input type="text" name="username" id="username" placeholder="username"><br>
  <label for="password">Password</label>
  <input type="password" name="password" id="password"  placeholder="password"><br><br>
  <input type="submit" value="Submit">
</form>
</body>
</html>



home.php :

<?php
session_start();
$username=$_SESSION['username'];
$userid=$_SESSION['userid'];

echo "You Are Logged IN -<b>".$username."</b> and your ID is -<b>".$userid."</b>";
?>
To run this tutorial , you need a database and a table containing users records. In this tutorial I am using a database namely - "test" with a table name - "user". This "user" table is having three columns as follows : id, username and password .


Hope you like this post……..Please Comment…………!!!!!!!!!

Saturday, November 23, 2013

Easy jQuery Dropdown Menu with attractive CSS

Saturday, November 23, 2013 - 0 Comments

Hiiii, nowadays many dropdown menus are available in market which you can implement on your website but sometimes they are not easy to implement and sometimes managing CSS for that dropdown are so difficult. One major thing more that you will find very less websites on internet without a dropdown menu. Dropdown allows you to manage the links on you website in a very attractive way and in a very organized way. So here in this post , I will be telling you how to implement an  attractive Dropdown in a very easy way with a feature of giving links to all the menu items. 

DROPDOWN MENU DEMO VIEW :


DROPDOWN MENU CODE BEGINS :

<html> <head> <title>Simple Dropdown</title> <script src="http://code.jquery.com/jquery.js"></script> <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css"> <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-theme.min.css"> <script src="//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script> </head> <body> <div style="width:50%; height:30%; border:2px solid #DDDDDD; margin-left:20px; margin-top:20px;"> <h1>&nbsp;Simple Dropdown Tutorial</h1> <div class="bs-example" style="margin-left:10px;"> <ul class="nav nav-pills"> <li class="active"><a href="#">Home</a></li> <li class="dropdown"> <a href="#" data-toggle="dropdown" role="button" id="drop4">Dropdown <b class="caret"></b></a> <ul aria-labelledby="drop4" role="menu" class="dropdown-menu" id="menu1"> <li role="presentation"><a href="https://twitter.com/Mycodesstock" tabindex="-1" role="menuitem">Action</a></li> <li role="presentation"><a href="https://twitter.com/Mycodesstock" tabindex="-1" role="menuitem">Another action</a></li> <li role="presentation"><a href="https://twitter.com/Mycodesstock" tabindex="-1" role="menuitem">Something else here</a></li> <li class="divider" role="presentation"></li> <li role="presentation"><a href="https://twitter.com/Mycodesstock" tabindex="-1" role="menuitem">Separated link</a></li> </ul> </li> <li class="dropdown"> <a href="#" data-toggle="dropdown" role="button" id="drop5">Dropdown 2 <b class="caret"></b></a> <ul aria-labelledby="drop5" role="menu" class="dropdown-menu" id="menu2"> <li role="presentation"><a href="https://twitter.com/Mycodesstock" tabindex="-1" role="menuitem">Action</a></li> <li class="divider" role="presentation"></li> <li role="presentation"><a href="https://twitter.com/Mycodesstock" tabindex="-1" role="menuitem">Separated link</a></li> </ul> </li> <li class="dropdown"> <a href="#" data-toggle="dropdown" role="button" id="drop6">Dropdown 3 <b class="caret"></b></a> <ul aria-labelledby="drop6" role="menu" class="dropdown-menu" id="menu3"> <li role="presentation"><a href="https://twitter.com/Mycodesstock" tabindex="-1" role="menuitem">Menu Item 1</a></li> <li role="presentation"><a href="https://twitter.com/Mycodesstock" tabindex="-1" role="menuitem">Menu Item 2</a></li> <li role="presentation"><a href="https://twitter.com/Mycodesstock" tabindex="-1" role="menuitem">Menu Item 3</a></li> <li class="divider" role="presentation"></li> <li role="presentation"><a href="https://twitter.com/Mycodesstock" tabindex="-1" role="menuitem">Menu Item 4</a></li> </ul> </li> </ul> <!-- /tabs --> </div> </div> </body> </html>

Hope you like this post……..Please Comment…………!!!!!!!!!

© 2013 MyCodeStock. All rights reserved.
Designed by SpicyTricks