Sunday, 30 June 2013

jQuery Function with Examples

jQuery Function with Examples


jQuery Functions with example which used mostly in web development

To use following functions you have to include jQuery file from jquery.com

.add() : Add elements to the set of matched elements. Example Add div to all p elements
$("p").add("div")


.addBack() : Add the previous set of elements on the stack to the current set, optionally filtered by a selector. Example Add class "background" to all the "div" having class "after"
$("div.after").find("p").addBack().addClass("background");


.after(): Insert content, specified by the parameter, after each element in the set of matched elements. Example Add the content "Test Message" just after "div" having "after" class
$('div.after').after('Test Message');


.ajaxComplete(): Register a handler to be called when Ajax requests complete. Example ajaxComplete will be called automatically just after finishing the ajax
$(document).ajaxComplete(function(event,request, settings) {
alert( "Request Complete." );
});
$( ".trigger" ).click(function() {
$( ".result" ).load( "ajax/test.html" );
});


.ajaxError(): Register a handler to be called when Ajax requests complete with an error. Example ajaxError will be called automatically just after finishing the ajax with error
$(document).ajaxError(function(event, jqxhr, settings, exception) {
alert( "Request Complete with Error." );
});
$( ".trigger" ).click(function() {
$( ".result" ).load( "ajax/test.html" );
});


.ajaxSend(): Attach a function to be executed before an Ajax request is sent. This is an Ajax Event. Whenever an Ajax request is about to be sent, jQuery triggers the ajaxSend event. Any and all handlers that have been registered with the .ajaxSend() method are executed at this time. Example ajaxSend will be called automatically when ajax is about to be sent.
$(document).ajaxSend(function(event, jqxhr, settings) {
alert( "Ajax Request just send" );
});
$( ".trigger" ).click(function() {
$( ".result" ).load( "ajax/test.html" );
});


.ajaxStart(): Register a handler to be called when the first Ajax request begins. This is an Ajax Event. Whenever an Ajax request is about to be sent, jQuery checks whether there are any other outstanding Ajax requests. If none are in progress, jQuery triggers the ajaxStart event. Any and all handlers that have been registered with the .ajaxStart() method are executed at this time. Example ajaxStart will be called automatically when ajax request start
$(document).ajaxStart(function() {
alert( "Ajax Request just send" );
});
$( ".trigger" ).click(function() {
$( ".result" ).load( "ajax/test.html" );
});


.ajaxStop(): Description: Register a handler to be called when all Ajax requests have completed. Example Whenever an Ajax request completes, jQuery checks whether there are any other outstanding Ajax requests. If none remain, jQuery triggers the ajaxStop event. Any and all handlers that have been registered with the .ajaxStop() method are executed at this time. The ajaxStop event is also triggered if the last outstanding Ajax request is cancelled by returning false within the beforeSend callback function.
$( ".log" ).ajaxStop(function() {
$(this).text( "Triggered ajaxStop handler." );
});


.ajaxSuccess(): Attach a function to be executed whenever an Ajax request completes successfully. Example Whenever an Ajax request completes successfully, jQuery triggers the ajaxSuccess event. Any and all handlers that have been registered with the .ajaxSuccess() method are executed at this time.
$(document).ajaxSuccess(function() {
$( ".log" ).text( "Triggered ajaxSuccess handler." );
});


.andSelf():Add the previous set of elements on the stack to the current set. Example This function has been deprecated and is now an alias for .addBack(), which should be used with jQuery 1.8 and later. As described in the discussion for .end(), jQuery objects maintain an internal stack that keeps track of changes to the matched set of elements. When one of the DOM traversal methods is called, the new set of elements is pushed onto the stack. If the previous set of elements is desired as well, .andSelf() can help. animate(): Perform a custom animation of a set of CSS properties. The .animate() method allows us to create animation effects on any numeric CSS property. The only required parameter is a plain object of CSS properties. This object is similar to the one that can be sent to the .css() method, except that the range of properties is more restrictive. Example
$('a.clickMe').click(function() {
$('#effect').animate({
width: 'toggle',
height: 'toggle'
}, {
duration: 5000,
specialEasing: {
width: 'linear',
height: 'easeOutBounce'
},
complete: function() {
$(this).after('
Animation complete.');
} }); });


.contents(): Get the children of each element in the set of matched elements, including text and comment nodes. Given a jQuery object that represents a set of DOM elements, the .contents() method allows us to search throughthe immediate children of these elements in the DOM tree and construct a new jQuery object from the matching elements. The .contents() and .children() methods are similar, except that the former includes text nodes as well as HTML elements in the resulting jQuery object.


Form Submit By Ajax - Simple Example
    function submitme(){
        var data= $('#form').serialize();
        var url ="/ajax/submiturl";

        $.ajax({
            type: "POST",
            url: url,
            data: data,
            success: function(data){
                alert(data);
            },
            dataType: 'json'
        });

    }


Friday, 21 June 2013

Stored Procedure - Advantage of Stored Procedure - Disadvantage of Stored Procedure

Advantage of  Stored Procedure

  • Stored procedures can be used to maintain data integrity and enforce database policy without relying on an external program to do so.
  • the DBA can add behavior that the application doesn't care about. For example, storing a modify date on each row.
  • You do not need to deploy to make a change.
  • Much faster than dynamic queries
  • Easier to expand a system
  • A small functionalists can be added in SP (Store Procedure)



Dis-Advantage of  Stored Procedure
  • Debugging is hard.
  • Source control can be a pain.
  • If you have a lot of functionality in store procedure it will making swapping between different database systems harder - It also creates more work if you want to support different database systems.
  • Developing stored procedures can be a fairly specialized task, especially as they get more complex.
  • Refactoring is harder. Renaming or changing where the store proc is might produce a bad effect.

Wednesday, 12 June 2013

Difference Between Cakephp and Zend Framework

S.No Cakephp Zend Framewok
1
It is just framework. It is Both framework and library.
2
In View Form helper, there is form elements, validation available. In View Form helper, there is form elements, validation, filters(like strip_tags), order of elements, sub form, and decoraters are available.
3
we can render form elements one by one We can render form in one line, one by one element, element OR  decorator OR error separetly.
4
Form configuration can not done by through configuation file Zend_form can be do configuration through zend_cofig or xml
5
When cake start, It load all library that's why Its not good for small project. Its library is too big as compare to cakephp. If you are  not using any component then it will not load by default.
6
It uses front controller design and singleton design pattern. It use front controller pattern, factory patter, strategy pattern, singleton pattern.
7
It is good for fast development. It is best, if you application are using webservices
8
ACL, Auth like comonents are easily availbele for cakephp. It has its own ACL, Auth components and upto deeper level.
9
When cake start, It load all library that's why Its not good for small project. Its library is too big as compare to cakephp. If you are  not using any component then it will not load by default.
10
It have session component It have Zend Session and Zend Registery components.
11
Its class name does not map with file location Its mapping,
If any class name is Zend_forms_abc
file location is Zend/Forms/abc.php
12
Mostly used for fast development. Mostly used for web services

Saturday, 8 June 2013

Pending Interview Questions and Answers

Who is the Father of PHP?
Rasmus Lerdorf


Which programming language does PHP resemble to?
PHP resemble to pearl and C


How can we create a database using PHP and MySQL?
We can create MySQL database in php with the use of
mysql_create_db ("db_name");


Is variable name case sensitive?
Yes, In PHP variable name case sensitive. We cannot start a variable with number like $777name as a valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores.


How can we execute a php script using command line?
Just run the PHP CLI (Command Line Interface) program and provide the PHP script file name as the command line argument. For example, "php myScript.php", assuming "php" is the command to invoke the CLI program.


Differentiate between in_array() and array_search() in php?
in_array : Checks if a value exists in an array. array_search() : Searches an array for a given value and returns the corresponding key if successful.


How do you call a constructor for a parent class?
parent::constructor($value);


How to delete file in PHP ?
unlink($filename);


How to delete variable in PHP ?
unset($variable);


What is the urlencode and urldecode in php ?
Returns a string in which all non-alphanumeric characters except -_. have been replaced with a percent (%) sign followed by two hex digits and spaces encoded as plus (+) signs.


What is the use of the function htmlentities?
htmlentities Convert all applicable characters to HTML entities This function is identical to htmlspecialchars() in all ways, except with htmlentities(), all characters which have HTML character entity equivalents are translated into these entities.


Differentiate between strstr and stristr in php?
strstr() and stristr both are used to find the first occurence of the string only difference is stristr( ) is case insensitive.


How can we know the total number of elements of Array?
sizeof($array);
count($array);


How to secure your website?
  1. Validate Input.
  2. Use Auth & ACL.
  3. Protect my Session ID
  4. Preventing Cross Site Scripting (XSS) flaws
  5. SQL injection vulnerabilities
  6. Turning off error reporting and exposing to the site for hackers
  7. Protect secure data of website


What is PHP configuration file called?
php.ini.


What is a persistent cookie?
A persistent cookie is a cookie which is stored in a cookie permanently on the browser's computer. By default, cookies are created as temporary cookies which stored only in the browser's memory. When the browser is closed, temporary cookies will be erased automatically.


What are non-key columsn in database?
Answer: A non key attribute in sql server is a columns which can not be used to identify a record uniquely for example name or age columns in customer table


Friday, 7 June 2013

Systems Development Life Cycle (SDLC)


SDLC stands for Software Development Life Cycle. 

It is series of process that followed to be make a software successful. In software development, if you follow the process of SDLC, the chance of success of project increase.

Today In IT Industries most of the companies including MNC follow this process. It help to complete the project on timely and with higher success rate.



Benefits of the SDLC Process

The intent of a SDLC process it to help produce a product that is cost-efficient, effective and of high quality. Once an application is created, the SDLC maps the proper deployment and decommissioning of the software once it becomes a legacy. The SDLC methodology usually contains the following stages: Analysis (requirements and design), construction, testing, release, and maintenance (response).






Following are the main steps of SDLC

1. Preliminary Analysis: The objective of phase 1 is to conduct a preliminary analysis, propose alternative solutions, describe costs and benefits and submit a preliminary plan with recommendations.Conduct the preliminary analysis: in this step, you need to find out the organization's objectives and the nature and scope of the problem under study. Even if a problem refers only to a small segment of the organization itself then you need to find out what the objectives of the organization itself are. Then you need to see how the problem being studied fits in with them.Propose alternative solutions: In digging into the organization's objectives and specific problems, you may have already covered some solutions. Alternate proposals may come from interviewing employees, clients , suppliers, and/or consultants. You can also study what competitors are doing. With this data, you will have three choices: leave the system as is, improve it, or develop a new system.Describe the costs and benefits.

2. Systems analysis, requirements definition: Defines project goals into defined functions and operation of the intended application. Analyzes end-user information needs.

3. Systems design: Describes desired features and operations in detail, including screen layouts, business rules, process diagrams, pseudocode and other documentation.

4. Development: The real code is written here.
Integration and testing: Brings all the pieces together into a special testing environment, then checks for errors, bugs and interoperability.

5. Acceptance, installation, deployment: The final stage of initial development, where the software is put into production and runs actual business.

6. Maintenance: What happens during the rest of the software's life: changes, correction, additions, moves to a different computing platform and more. This is often the longest of the stages.

Cache in PHP - Speed Up your website

Follow the following steps to implement caching in Core PHP?
  • Create a folder with write permission where you store the output of page
  • At the start of file, check whether you have already stored the output of file or not
  • If you have already stored the output in cache, then get the contents from cache instead of executing the code
  • If Not, first prevent the php to send the output to the browser (ob_start php) and store the output in cache folder
  • Create the page in your application from where you can delete all the files, stored in cache folder (when website updates)



See Example
$fileName="xxxx.html";
$cacheFolder="/cache/";//must be writeable 

//check if file in cache
if(file_exists($cacheFolder.$fileName,'r'){
$output = file_get_contents($cacheFolder.$fileName);
}else{
ob_start(); //stop sending output to the browser
//do work
//do work
//do work
$output = ob_get_contents();
ob_end_flush();
$fp=fopen($cacheFolder.$fileName,'w');
fwrite($fp, $output);
fclose($fp);
}
echo $output;


Wednesday, 5 June 2013

Normalization Denormalization different form of normalization

Question: What is Normalization?
Answer: Normalization is a process in relational database where fields and tables are organized to reduce the redundancy and dependency by dividing the larger tables and linking them.

Question: Why We use Normalization?
Answer: We use Normalization to organized the data and reduce the redundancy and dependency.

Question: What happen, if we don't do Normalization?
Answer: Following are the pros, if we don't normalization.
  • Redundancy
  • Heavy database
  • Incorrect database
  • Queries take much time to execute.

Question: What is Denormalization?
Answer: This is the process by with DBA(database admin) attempt to optimize the performance of the database by adding in redundant OR grouped data. The advantages to this is that the data is stored in one table are faster, as opposed to multiple smaller tables where need to multiple joins.

Answer: There are 5 types of Normation i.e 1NF, 2NF, 3NF, 4NF and 5NF.
We can achieve upto 4NF (4NF is very rare)

Question: What are different form of normalization?
Answer: Following are the different form of normalization.
1NF
Rule1: Each table cell should contain single value. Like (if user have two phone no then both phone number can't be in one column must have two records for this)
Rule2: Each Record needs to be unique.

2NF
Rule1: Must follow 1NF
Rule2: Extract the filed that are non-key columns and place into separate table and releate both table with primary key concept.

3NF
Rule1: Must follow 2NF
Rule2: Has no transitive functional dependencies
example: table  fields are 
zip, cityname, statename
In addition, you may wish to instead have separate City and State tables, with the City_ID in the Zip table and the State_ID in the City table.

BCNF
Rule1: Must follow 3NF
Rule2: All table can have only one primary key.


Monday, 3 June 2013

Javascript Interview Questions and Answers


JavaScript is a general-purpose programming language designed to let programmers of all skill levels control the behavior of software objects. The language is used most widely today in Web browsers whose software objects tend to represent a variety of HTML elements in a document and the document itself. You can change the DOM element and call the Ajax. It is independent of operating and language.


Question: How many types of loop are there in javaScript?

Answer: JavaScript supports following different types of loops
for - loops through a block of code a number of times
for/in - loops through the properties of an object
while - loops through a block of code while a specified condition is true
do/while - also loops through a block of code while a specified condition is true
/** for loop example **/
cars=["BMW","Volvo","Merchi","Ford"];
var i=2,len=cars.length;
for (; i");
}
/** for loop example **/

/** For/In Loop **/
var person={fname:"John",lname:"Doe",age:25}; 

for (x in person)
  {
alert(person[x]);
  }
/** For/In Loop **/

/** while loop **/
while (i<5 data-blogger-escaped-br="" data-blogger-escaped-he="" data-blogger-escaped-i="" data-blogger-escaped-is="" data-blogger-escaped-number="" data-blogger-escaped-x="x">";
  i++;
  }
/** while loop **/ 


Question:What are global variables? How are they declared? How these are different from local variables?
Answer: Variable that are available throughout the page.
These are declared without use of var keyword.

Variable that are declared with use of keyword var are local variable and available within scope.
// Declare a local variable
var localVariable = "PHP Tutorial"
// Declare a global
globalVariable = "google"
 


Question:What is the difference between undefined and null?
Answer: The value of a variable with no value is undefined (i.e., it has not been initialized). Variables can be emptied by setting their value to null. You can use === operator to test this.


Question: What are the various datatypes in javascript?
Answer: Number - Store Number like 1,100, 33
String - Store string like "php","tutorial-" etc
Boolean - Store true OR false
Function - Store the function
Object - Store the object like person object
Null - Store the variable value null
Undefined - Not defined variable value are undefined.


Question: What is negative infinity?
Answer: It’s a number in JavaScript, derived by dividing negative number by zero. For example var a=-100/0;

Question: How to check the type of variable?
Answertypeof is used to check the variable type. For example alert(typeof abc);


Question: How do you convert numbers between different bases in JavaScript?
Answer: Use the parseInt() function.
alert( parseInt ("3F", 16));


Question: What is Javascript namespacing? How and where is it used?
Answer: Using global variables in Javascript is evil and a bad practice. That being said, namespacing is used to bundle up all your functionality using a unique name. In JavaScript, a namespace is really just an object that you’ve attached all further methods, properties and objects.


Question: How to load javascript files asynchronously?
Question: How to load javascript files fast?
 Answer: If you have latest browser which support HTML5 then you just need to add "async" tag with value true
If you have old browser, you need to create a js function that will add javascript async Following are the Javascript function example
function loadScriptAsync (scriptFilePath){
    var scriptHeadTag=document.getElementsByTagName('script')[0];
    var ss=document.createElement('script');
    ss.type='text/javascript';
    ss.async=true;
    ss.src= scriptFilePath
    scriptHeadTag.parentNode.insertBefore(ss,s);
}

loadScriptAsync('/js/jsfile.js'); 

Pass PHP Array into Ajax Call
//Setp 1: Include jQuery file in your page

$phpData = array('fname'=>'G', 'lname'=>'Geo','email'=>'g7789@gmaill.com'); //Setp 2: This is your PHP Array data

 [script]
/** Setp 3: This is Ajax Call will be called after page fully load **/
     function saveuserdetail(mydata) {                                    
                    $.ajax({
                        type: "POST",//Here you can use POST/GET Method
                        url: '/postpageurl/',
                        data: mydata,
                        success: function(msg){                            
                            console.log('Data'+msg);
                        },
                        dataType: 'json'
                    });                
            }
/** This is Ajax Call will be called after page fully load **/


/* Step 4: When Page Load, PHP Array will convert into javaScript Object */
/* Pass the javaScript Object into javaScript Function i.e saveuserdetail**/
$( document ).ready(function() {
    var data=new Object("echo json_encode($phpData) ")
    saveuserdetail(data);
});
[/script]

Question: Is JavaScript case sensitive?
Answer: Yes!
getElementById is different from getElementbyID.


Question: How will you get the Checkbox status whether it is checked or not?
Answer:
alert(document.getElementById('checkbox1').checked);


Question: How do you submit a form using JavaScript?
Answer:
document.forms[0].submit();


Question: What does isNaN function do?
Answer: isNaN : IsNotaNumber
returns true if the argument is not a number;

Question: What does "1"+9+4 evaluate to?
Answer: 194

How do you assign object properties?
obj["age"] = 22 or obj.age = 22.



What’s a way to append a value to an array?
arr[arr.length] = value;


How to read and write a file using javascript?
 I/O operations like reading or writing a file is not possible with client-side javascript.



How do you convert numbers between different bases in JavaScript?
Use the parseInt() function, that takes a string as the first parameter, and the base as a second parameter. So to convert hexadecimal FF to decimal, use parseInt ("FF", 16);



What is negative infinity? 
It’s a number in JavaScript, derived by dividing negative number by zero.



How to set a HTML document's background color?
 document.bgcolor property can be set to any appropriate color.



What boolean operators does JavaScript support?
&&, and !



How to get the contents of an input box using Javascript?
 Use the "value" property.var myValue = window.document.getElementById("textboxID").value;



How to determine the state of a checkbox using Javascript? 
var checkedP = window.document.getElementById("CheckBoxID").checked;



How to set the focus in an element using Javascript? 
<script> function setFocus() { if(focusElement != null) { document.forms[0].elements["myelementname"].focus(); } } </script>



How to access an external javascript file that is stored externally and not embedded? 
This can be achieved by using the following tag between head tags or between body tags.<script src="raj.js"></script>How to access an external javascript file that is stored externally and not embedded? where abc.js is the external javscript file to be accessed.



What is the difference between an alert box and a confirmation box? 
An alert box displays only one button which is the OK button whereas the Confirm box displays two buttons namely OK and cancel.



What is a prompt box? 
A prompt box allows the user to enter input by providing a text box.



Can javascript code be broken in different lines?
Breaking is possible within a string statement by using a backslash \ at the end but not within any other javascript statement.that is ,document.write("Hello \ world");is possible but not document.write \("hello world");



What looping structures are there in JavaScript?
for, while, do-while loops, but no foreach.



How do you create a new object in JavaScript?
var obj = new Object(); or var obj = {};



What is this keyword?
It refers to the current object.


What is the difference between SessionState and ViewState? 
ViewState is specific to a page in a session. Session state refers to user specific data that can be accessed across all pages in the web application.

What looping structures are there in JavaScript? 
for, while, do-while loops, but no foreach.



To put a "close window" link on a page ? 
<a href='javascript:window.close()'> Close </a>



How to comment javascript code? 
Use // for line comments and/**/ for block comments



Name the numeric constants representing max,min values 
Number.MAX_VALUENumber.MIN_VALUE



What does javascript null mean? The null value is a unique value representing no value or no object.It implies no object,or null string,no valid boolean value,no number and no array object.



How do you create a new object in JavaScript? 
var obj = new Object(); or var obj = {};



How do you assign object properties? 
obj["age"] = 23 or obj.age = 23.



What’s a way to append a value to an array? 
arr[arr.length] = value;


What does undefined value mean in javascript? 
Undefined value means the variable used in the code doesn't exist or is not assigned any value or the property doesn't exist.



What is the difference between undefined value and null value? 
(i)Undefined value cannot be explicitly stated that is there is no keyword called undefined whereas null value has keyword called null(ii)typeof undefined variable or property returns undefined whereas typeof null value returns object



What is variable typing in javascript? It is perfectly legal to assign a number to a variable and then assign a string to the same variable as followsexamplei = 10;i = "string";This is called variable typing



Does javascript have the concept level scope? No. JavaScript does not have block level scope, all the variables declared inside a function possess the same level of scope unlike c,c++,java.

What is === operator ? ==== is strict equality operator ,it returns true only when the two operands are having the same value without any type conversion.

How to disable an HTML object ?
document.getElementById("myObject").disabled = true;



How to create a popup warning box?
alert('Warning: Please enter an integer between 0 and 1000.');



How to create a confirmation box? 
confirm("Do you really want to launch the missile?");



How to create an input box? 
prompt("What is your temperature?");


What's Math Constants and Functions using JavaScript? 
The Math object contains useful constants such as Math.PI, Math.EMath.abs(value); //absolute valueMath.max(value1, value2); //find the largestMath.random() //generate a decimal number between 0 and 1Math.floor(Math.random()*101) //generate a decimal number between 0 and 100



What does the delete operator do? 
The delete operator is used to delete all the variables and objects used in the program ,but it does not delete variables declared with var keyword.



How to get value from a textbox?
alert(document.getElementById('txtbox1').value);



How to get value from dropdown (select) control?alert(document.getElementById('dropdown1').value);


What is console.log?
It is feature of Firebug used for debug the javascript OR jQuery code. It can print the string, number, array OR object. It is same as print_r() in php.

Example of console.log
console.log (22 );
console.log ('web technology experts notes' );
console.log (arrayVal);
console.log (objectVal);



Question: How to check checkbox is checked or not in jquery?
$('.checkBoxClass').is(':checked');


Question: How to check the checkbox as checked?
$(".checkBoxClass").attr('checked', true); // Deprecated
$(".checkBoxClass").prop('checked', true);


Best Related Posts are Following:
1. jQuery Mobile interview questions and answers
2. Ajax Interview questions and answers for experienced
3. Advanced MySQL Interview Questions and Answers for Experienced
4. SAML Interview Questions and Answers
5. HTML5 interview Questions and Answers for Fresher and Experienced
6. Backbone Js interview questions and answers
7. Bootstrap Interview Questions and Answers for Experienced
8. HTML interview questions and Answers
9. SEO Interview Questions and Answers
10. AngularJS Interview Questions and Answers for Experienced
11. Difference Between Hadoop and Big-Data
12. Memcached interview questions and answers
13. General Interview Questions and Answers
14. UNIX Commands Interview Questions and Answers
15. Apache Interview Questions and Answers
16. PHP Technical Interview Questions and Answers
17. Zend Framework Interview Questions and Answers for Experienced - Page 2
18. CSS Interview Questions and Answers
19. Mysql Interview Questions And Answers - Atomicity, Dedlock, Client Program, Mysql Mode, Mysql Sensitivity Of Identifiers And Mysql Errors
20. Zend Framework Interview Questions and Answers for Experienced
21. XML Interview Questions And Answers