16 Nov 2014

How to display Fullcalendar event details in a popup using CakePHP


Full calendar integration is quite easy in CakePHP but major difficulty arises when you want your events to come from database in the JSON format and you need to display event details in a popup on an event click. Don’t worry! I will explain here, how it could be done easily. Follow the steps with me and if you do properly, it's like making maggi noodles :P

Step1: Create a table APPOINTMENTS in your database. Here is the query for your ease.

CREATE TABLE IF NOT EXISTS `appointments` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `title` varchar(200) NOT NULL,
  `book_datetime` datetime DEFAULT NULL,
  `start_datetime` datetime DEFAULT NULL,
  `end_datetime` datetime DEFAULT NULL,
  `notes` text,
  `hash` text,
  `is_unavailable` tinyint(4) DEFAULT '0',
  `id_users_provider` bigint(20) unsigned DEFAULT NULL,
  `id_users_customer` bigint(20) unsigned DEFAULT NULL,
  `id_services` bigint(20) unsigned DEFAULT NULL,
  `id_google_calendar` text,
  PRIMARY KEY (`id`),
  KEY `id_users_customer` (`id_users_customer`),
  KEY `id_services` (`id_services`),
  KEY `id_users_provider` (`id_users_provider`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
 

Step2: Code in Controller

Create an “Appointments” controller (in my case AppointmentsController) in the controller folder. In the “index” function of it create a variable “eventData” as an array which will store the event related data needed to display in the popup.

$eventData = array();
$i = 0;

I have declared a variable “i” used to store multiple events data in eventData array.
Now fetch all appointments from the “Appointments” table using this query.

$allAppointments = $this->Appointment->find('all');

Extract event related data from this “allAppointments” variable. Actually it’s an array. So you have to do some easy manipulation like this:

foreach ($allAppointments as $value) {
                $eventData[$i++] = $value['Appointment'];
}

Now final step in controller’s file, set the values to some variables to pass to view.

$this->set('allAppointments', $allAppointments);
$this->set('eventData', $eventData);

Note: No need for model here.
If you simply want data from “Appointments” table, there is no need for any model. If you need some more data related to an appointment like - user name from users table, etc. then you need to call the model. Will talk about that part in some other tutorial.

Step3: Creating a view.

Now create a “Appointments” folder in the View folder. It’s the CakePHP syntax – you have to create a folder in the view similar to the Controller name and in this folder you will place your view files with .ctp extension (again CakePHP syntax).
In “Appointments” folder create a .ctp file with the name of the method which need to be called. Here we have created “index” method in the “Appointments” controller, so we will create and index.ctp file and place our html,php, js & css related things in it.

Step4: JSON Encode array to string.

Now the array containing details of events is in “eventData”. We will encode it to JSON format string using “json_encode” PHP function.

<?php
    $encodedData = json_encode($eventData);
?>
Now this string variable, we will set to the HTML page in any div with display none. This step is done to fetch this string in Javascript code of full calendar.
<div id="JSONdata" style="display:none;"><?php echo $encodedData; ?></div>

Step5: Placing DIVs in the code.

Now create an event content div which will contain all the event data like this:

<div id="eventContent">
     <div id="eventInfo"></div>
</div>
And place the calendar containing div also.
<div id='calendar'></div>

Step6: Calling fullcalendar script and setting attributes

This is the final step. First of all you need to include the css and javascript files in your code in the head section or top of your view file – index.ctp.
CSS
  • fullcalendar.css
Javascript
  • moment.min.js
  • jquery.min.js
  • fullcalendar.min.js
  • jquery-ui.js
Include the above files in order included, so that no javascript issues occur. Now call the full calendar script as described below.

<script>
                $(document).ready(function() {
                var jData = $("#JSONdata").html();
                $('#calendar').fullCalendar({
                                header: {
                                                left: 'prev,next today',
                                                center: 'title',
                                                right: 'month,agendaWeek,agendaDay'
                                },
                                events: jQuery.parseJSON(jData),
                                eventRender: function(event, element){
                                element.attr('href', 'javascript:void(0);'); // disable the event href
                                element.click(function(){
                                // set the values & open the modal
                                var html = "<div><div class='heading'>Appointment Details</div><br/><span class='firstCol'>Title</span>&nbsp;<span class='secondCol'>"+event.title+"</span><br/><span class='firstCol'>Start Date</span>&nbsp;<span class='secondCol'>"+event.start_datetime+"</span><br/><span class='firstCol'>End Date</span>&nbsp;<span class='secondCol'>"+event.end_datetime+"</span><br/><span class='firstCol'>Booked Date</span>&nbsp;<span class='secondCol'>"+event.book_datetime+"</span><br/><span class='firstCol'>Notes</span>&nbsp;<span class='secondCol'>"+event.notes+"</span><br/><span class='firstCol'>Description</span>&nbsp;<span class='secondCol'>"+event.notes+"</span><br/></div>";

                                $("#eventInfo").html(html);
                                $("#eventContent").dialog({
                                                                modal : true
                                                });
                                });
                                },                                            
                                defaultDate: '2014-09-12',
                                editable: true,
                                eventColor: 'green',
                                //eventBackgroundColor: 'blue',
                                eventLimit: true // allow "more" link when too many events
                                });                          
                });
</script>
To parse json encoded string data in the fullcalendar, use parseJSON() function. Pass the values to the “events” attribute as shown below.

events: jQuery.parseJSON(jData),

This will display all the events fetched from appointments table into the calendar. See image below:


eventRender: This attribute will be used to display popup and event details when clicked on any event. Paste the code as mentioned in previous step. It will work like this, if you click on any event:

Hope it works for you, if not - mention in comments your issues.
Happy Coding :)

12 Sept 2014

10 Always Asked JavaScript Interview Questions and Answers

Q1: How can we submit a form without a submit button? Or how can we submit a form using JavaScript?

Ans: A form can not only be submitted from html code but also from JavaScript code. You need to know the form name at least.Submit() function is used to submit the form instead of submit button.
E.g.
<form id="myForm" action="form_submitted.php">
<a href="javascript: submitMyForm()">Search</a>
</form>
<script>
function submitMyForm() {
document.getElementById("myForm").submit();
/* you can also use below DOM technique, but for that form tag should contain name of the form like this:
<form name=”myForm1”> */
document.forms["myForm1"].submit(); // or
document.myForm1.submit();
}
</script>


Q2: How to check that a variable is a number?

Ans: There is predefined function to check if a variable is a number or not.
isNaN: returns true if the argument is not a number. NAN itself means Not aNumber.
E.g.    isNaN(“hello”) // returns true.
isNaN(145) // returns false.

Q3: How we can create arrays in JavaScript?

Ans: There are two ways of creating arrays in JavaScript. Using,
1. Array literal
2. New keyword
Array literal Syntax:
var cars = [“BMW”, “AUDI”, “MERCEDES”, “HYUNDAI”];
New Keyword syntax:
var cars = new Array(“BMW”, “AUDI”, “MERCEDES”, “HYUNDAI”);
Both of them work exactly the same way, but it’s better to use first one as it is simple, speedy & easily readable.

Additional Information:

Accessing the values from an array, var carName = cars[0];
Modifying the first element, cars[0] = “VOLKSWAGEN”;
Note: Type of Array is object, so arrays are objects in JavaScript.

Q4: What is the data type of variables in JavaScript?

Ans: In JavaScript there are 7 types of data types – 3 primary, 2 composite and 2 special.
Primary(Primitive) – String, Number and Boolean.
Composite(Reference) – Object and Array.
Special – Null and Undefined.
Javascript has dynamic data types, means same variable can be used as different types.
E.g.    
var a;                   // a is undefined
var a = 55;          // a is a Number
var a = “Hello”;  // a is a String

Q5: Are JavaScript Scripts faster than server side scripts?

Ans: Yes, JavaScript is faster than any server side script because it’s written for client side browsers or machines, so it doesn't need web server’s support for execution.

Q6: How JavaScript code can be inserted into a webpage?

Ans: JavaScript can be inserted anywhere in the page – either <body> or in the <head> section, but it should be enclosed within <script></script> tags.
<script>
// some code here…
</script>
You might see in some old codes, ‘type=”text/javascript”’ in the script tag. It is no longer required as JavaScript is the default scripting languages these days in all major browsers.
<script type=”text/javascript”>
// some code here…
</script>
Note: Please remember external scripts shouldn't contain <SCRIPT> tags.

Q7: How to access external JavaScript files?

Ans: To access the external JavaScript file/files you need to add a reference of it in your code. The reference is provided by src attribute.
Syntax:
<script type="text/javascript" src="myscript.js"></script>
Here myscript.js is the external js file to be included.

Q8: What is the sum of this?

a. “1”+2+3
b. 2+5+”5”
c. 3+”7”+1
Ans: There is a simple rule in JavaScript – if you add a number and string, the result will be a string.
So,
“1”+2+3 = 123
2+5+”5” = 75
3+”7”+1 = 371
Remember operations are performed left to right. So if first one is a string, it considers everything after it as a string, so “1”+2+3 equals to 123 rather than 15.

Q9: How to resolve the JavaScript code rendering issue in old browsers? Or How to hide JavaScript code from old browsers that don’t support JavaScript?

Ans: This question is not much relevant these days as almost all browsers these days are quite advanced and support JavaScript. Still you should know about it. One can comment whole JavaScript code inside the SCRIPT tags.
Syntax:
<script type="text/javascript" language="JavaScript">
<!--
Put your JavaScript code here.
//-->
</script>
Old browsers will interpret JS code as an HTML comment.

Another way is using NOSCRIPT tag. It can be used both in HTML4 & 5 but not supported in XHTML.
The <noscript> tag defines an alternate content for users that have disabled scripts in their browser or have a browser that doesn't support script.
Syntax:
<script>
document.write("Hello")
</script>
<noscript>Sorry, your browser does not support JavaScript!</noscript>
In HTML 4, NOSCRIPT tag can be used only inside <body> element but in HTML 5 it can be used both inside <head> and <body>.

Q10: How to create new objects in JavaScript and assign object properties?

Ans: It’s very easy to create new objects in JavaScript.NEW keyword is used to create objects.
Syntax: varObj = new object(); or varObj = {}

You can also create your own objects and add properties to it.
E.g. var car = {name:”Audi”, model:”A6”, color:”black”, cc:”2500”}

Object properties can be assigned like this.
                Obj[“age”] = 22or car.model = “R8”;



31 Aug 2014

10 Always Asked PHP Interview Questions and Answers

Q1: What is the difference between PHP 4 and PHP 5?

Ans: One should know the following changes to understand what has changed from PHP 4 to PHP 5.
  • PHP 4 is more of a procedural Language (but it had support for OOP) whereas PHP 5 is an object oriented language (it has more enhanced features of OOP like access specifiers, inheritance etc.). 
  • PHP5 removed register_globals, magic quotes, and safe mode. 
  • PHP 5 introduced many new things like –interfaces, functions, error level (E_STRICT), default extensions (like PDO, SimpleXML, etc.), MySQL extension named MySQLi (Improved MySQL), built in SOAP extension for interoperability with web services. 
  • PHP 5 gave 3 levels of accesses – Public,Private and Protected – which were not in PHP 4 earlier. 
  • PHP 4 was powered by Zend Engine 1.0, while PHP 5 is powered by Zend Engine 2. 
  • Major difference is PHP 5 got a new Object Model.In PHP 4 objects were handled as primitive types (everything was passed by value, including objects) while in PHP 5 objects are referenced by handle, and not by value (objects are passed by reference) 

Q2: What is the difference between $var and $$var? When is $$var used?

Ans: $var is a simple variable. Variables are declared in PHP using the $. So any variable can be declared as $x, $y, etc.
$$var instead is a reference variable. Consider the following example.
$var = “mango”;
$$var = 10;
echo $mango;// output: 10
  $$var is used when you need flexible variable naming.

Q3: What is the difference between require, require_once, include and include_once?

Ans: 
Difference between require and include:
Include: Used to include a file in a PHP code, but upon failure it generates a warning (E_WARNING) and the script will continue, the code will run.
Syntax: include 'filename'; or include(“filename”);

Require: Also used to include a file in a PHP code, but upon failure it generates an error (E_COMPILE_ERROR) and the script will halt.
Syntax: require 'filename'; or require(“filename”);
Remember r & r, error = require.

Difference between require_once and require:

require_once is identical to require the only difference being that if require_once is used, PHP will check if the file has already been included, and if so, it will not include it again.
Syntax: require_once ‘filename’; or require_once(“filename”);
include_once ‘filename’; or include _once(“filename”);
Note: Better to use include ‘filename’ instead of bracket () version;

Q4: What is the difference between GET and POST method?

Ans: These are the two most commonly used HTTP request methods.
GET: It requests data from the source.
POST: it submits data to be processed to a specific source.
Parameters
GET
POST
Caching
GET requests can be cached.
POST request never cached.
Data
Limited data can be sent like 2 kb.
Unlimited
Security
Data shown in url, non-secure
Totally secured
Browser History
GET requests remains in browser history
POST requests don’t.
Safe for password/sensitive data sending?
No
Yes
Can be bookmarked?
Yes
No

Q5: What are various ways of sending data from browser to web server and vice versa?

Ans: Data could be send in many ways.

From browser to web server:

  1. Query string (www.example.com?abc=xyz)
  2. POST method ($_POST)
  3. Sessions ($_SESSION)

From Server to Browser:

  1. GET method ($_GET)
  2. Cookies (A cookie, also known as an HTTP cookie, web cookie, or browser cookie, is a small piece of data sent from a website and stored in a user's web browser while the user is browsing that website. Every time the user loads the website, the browser sends the cookie back to the server to notify the website of the user's previous activity)

Q6: What are commonly used HTTP status codes?

Ans: The commonly used HTTP status codes which you will encounter in your daily life are the following:
  • 200 – ok
  • 301 – Moved Permanently
  • 302 – Found
  • 303 – See other
  • 403 – Forbidden
  • 404 – Not found
  • 500 – Internal Server error
  • 502 – Bad Gateway
  • 503 – Service unavailable
There are actually 5 classes of response:
  • 1xx Informational (Request received, continuing process)
  • 2xx Success (Client action was received, understood, accepted & processed successfully)
  • 3xx Redirection (further action needs to be taken to complete the request)
  • 4xx Client error
  • 5xx Server error

Q7: What are various common HTTP header fields?

Ans: HTTP header fields provide information about the request, response or about the object sent in the message body. The common HTTP header fields are:

Client Request headers:

  • Cookie (The Cookie request-header field value contains a name/value pair of information stored for that URL. E.g. Cookie: name=value)
  • Authorization (it contains the authentication credentials for HTTP authentication. E.g. Authorization : credentials)

Server Response headers:

  • Location (used in redirection, or when a new resource has been created)
  • Refresh (used in redirection, or when a new resource has been created.)
E.g. syntax: header("refresh:5;url=wherever.php");
This syntax redirects to the desired page after 5 seconds.
E.g. syntax: header("refresh:0;url=wherever.php");
This syntax redirects to the desired page immediately.

Q8: What is .htaccess and why it is used?

Ans: 
  • .htaccess is directory-level configuration file.
  • The original purpose of .htaccess was to allow per-directory access control. For example requiring a password to access the content.
Common usages:
  • Authorization & authentication.
  • Rewriting URLs.
  • Block users by IP address or domain.
  • Allow a server to control caching by web browsers and proxies.
  • Customized error responses.
  • Enable server-side includes.

Q9: Describe about the different types of error in PHP?

Ans: There are 3 types of errors which are very common in PHP.
  1. Notices: These are run-time notices. These occur if the script found something that might be an error. These errors are not displayed to the user. E.g. Accessing a variable that has not yet been defined.
  2. Warnings: These are serious errors but non-fatal. These errors are by default displayed to the user but they don’t result in script termination. E.g. Attempting to include() a file which does not exist will generate a warning.
  3. Errors: These are fatal and critical errors. They result in script termination and are by default displayed to the user. E.g. Instantiating an object of a non-existent class, or calling a non-existent function.

Q10: What is SESSION and how it is set and unset?

Ans: 
  • Session is a simple way to store data for individual users against a unique session ID.
  • It persist state information between pages.
  • $_SESSION is the global variable which gets set when session is started.
  • Manually sessions can be started using session_start() function.
Registering a variable:
<?php
session_start();
$_SESSION[‘key’] = value;

?>
Un-registering a variable:
<?php
session_start();
unset($_SESSION[‘key’]);

?>
Completely destroy/reset all session data:
<?php
session_destroy();
?>