Friday, 15 April 2016

How to apply css in iframe with javaScript?

How to apply css in iframe with javaScript?

See Following Working Example:
Suppose you have Following Iframe
<iframe border="0" cellspacing="0" frameborder="0" id="myIframeWebsite" name="myIframeWebsite" src="http://example.com/mydir/file.html"></iframe>

Now you just need to add a script code which will add the css file in iframe.
For Example:
<iframe border="0" cellspacing="0" frameborder="0" id="myIframeWebsite" name="myIframeWebsite" src="http://example.com/mydir/file.html"></iframe>
<script type="text/javascript">
var iframeCssLink = document.createElement("link") 
iframeCssLink.href = "/css/myiframecss.css"; 
iframeCssLink.rel = "stylesheet"; 
iframeCssLink.type = "text/css"; 
frames['frame1'].document.body.appendChild(iframeCssLink);
</script>

What will do above code
Whenever iframe load in browser, "/css/myiframecss.css" file will will be added in the head of iframe.
You just need to add all the css inside "/css/myiframecss.css"


Note: Iframe and website must have same Domain, Port and protocol.



Wednesday, 13 April 2016

How to create wordpress Shortcode?

How to create wordpress Shortcode?

Question: What is Shortcode in Wordpress?
A shortcode is code that lets you do nifty things with very little effort.


Question: What is use Shortcode in Wordpress?
Shortcodes can be embed in post Or page which can do lot of things like Image Gallery, Video listing etc.


Question: Give a simple Shortcode example?
[gallery]

It would add photo gallery of images attached to that post or page.


Question: What is Shortcode API in Wordpress?
Shortcode API is set of functions for creating shortcodes in Page and Post.


The Shortcode API also support attributes like below:
[gallery id="123" size="large"]



Question: What is name of function which is used to register a shortcode handler?
add_shortcode

It has two parameter.
first is shortcode name and second callback function. For Example:
add_shortcode( 'shortcode', 'shortcode_handler' );



Question: How many parameter can be passed in callback function?
  1. $atts - an associative array of attributes.
  2. $content - the enclosed content
  3. $tag - the shortcode tag, useful for shared callback functions



Question: How to create shortcode in wordpress? Give working example? Create Shortcode
function testdata_function() {
  return 'This is testing data. This is testing data. This is testing data. This is testing data. This is testing data. This is testing data.';
}
add_shortcode('testdata', 'testdata_function');

Use Shortcode
[testdata]



Question: How to create shortcode with attributes in wordpress? Give working example?
Create Shortcode
function testdata_function($atts) {
    extract(shortcode_atts(array(
      'header' =&gt; 'This is default heading',
      'footer' =&gt; 'This is default footer',
   ), $atts));

  return '<b>'.$header.'</b>
This is testing data. This is testing data. This is testing data. This is testing data.
<b>'.$footer.'</b>';
}
add_shortcode('testdata', 'testdata_function');

Use Shortcode
[testdata header="Custom Heading" footer="Custom footer"]



Question: How to create shortcode with in wordpress? Give working example?
Create Shortcode
function testdata_function($attr, $content) {
  return $content.' This is testing data. This is testing data. This is testing data. This is testing data. This is testing data. This is testing data.';
}
add_shortcode('testdata', 'testdata_function');


Use Shortcode
[testdata]This is content[/testdata]



Question: What to do if Ampersand (i.e &) converted to &#038;?
Use html_entity_decode function (PHP inbuilt function).


Question: How to use meta tags in shortcode?
If you want to add meta tags in head tag. then use below function.
add_action('wp_head', 'add_meta_tags');
function add_meta_tags() {
        echo '';
    }



Monday, 11 April 2016

YII interview questions and answers for fresher

yii interview questions and answers for fresher

Question: What is Yii?
Yii is a PHP framework which is based on MVC (Model View Controller).


Question: Is it opensource?
Yes, It is opensource. Download and use as per your project requirement. Question: What is full form of Yii
Yes it is.


Question: In which language, It is written?
PHP.


Question: What is current stable version of Yii?
Version: 2.0.7 dated February 14, 2016.


Question: What is offical website of Yii Framework?
http://www.yiiframework.com


Question: From where i an download Yii Framework?
http://www.yiiframework.com/download


Question: How to start Yii?
http://www.yiiframework.com/tour


Question: What are main feature of Yii framework?
  1. MVC design pattern
  2. Web Service available for Apps like android
  3. Internationalization and localization translation for multilingual.
  4. Caching for speed up the application
  5. Error handling and logging for tracking
  6. cross-site scripting (XSS), cross-site request forgery (CSRF) protection
  7. PHPUnit and Selenium for testing.
  8. Automatic code generation help us to fast development.



Question: How to set default controller on Yii?
array(
    'name'=>'Yii Framework',
    'defaultController'=>'site',
);



Question: How to get current controller id?
echo Yii::app()->controller->id;



Question: How to get current action id?
echo Yii::app()->action->id;



Question: What is the first function that gets loaded from a controller? ?
index



Question: How can we use ajax in Yii?
use ajax helper


Question: What are two type of models in YII
  1. Form models
  2. active records


Question: What are active records model?
Active Record is a design pattern used to abstract database access in an object-oriented way.
active records model is based on this design pattern.


Question: How to define a form model?
class MyLoginForm extends CFormModel
{
    public $username;
    public $password;
    public $rememberMe=false;
}



Question: How to set validation in Form Model?
class MyLoginForm extends CFormModel
{
    public $username;
    public $password;
    public $rememberMe=false; 
    private $_identity;
 
    public function rules()
    {
        return array(
            array('username, password', 'required'),
            array('rememberMe', 'boolean'),
            array('password', 'authenticate'),
        );
    }
 
    public function authenticate($attribute,$params)
    {
        $this->_identity=new UserIdentity($this->username,$this->password);
        if(!$this->_identity->authenticate())
            $this->addError('password','username or password Incorrect .');
    }
}



Question: What are the core application components available on Yii?
  1. db- database connection.
  2. assetManager - manage the publishing of private asset files
  3. authManager - manage role-based access control
  4. cache- manage caching functionality
  5. clientScript- manage javascript and CSS
  6. coreMessages- provides translated core messages
  7. errorHandler- manage errors handling.
  8. themeManager- Manage themes
  9. urlManager- URL parsing and creation functionality
  10. statePersister- mechanism for persisting global state
  11. session- Session management
  12. securityManager- Security Managment



Friday, 8 April 2016

Apache Interview Questions And Answers for experienced

Apache Interview Questions And Answers for experienced

Question: How to set UTF-8 for data store and fetch?
  1. Specify the utf8mb4 character set on all tables and text columns in database.
  2. While getting data from database, set the utf8 character set, like below
    $dbh = new PDO('mysql:charset=utf8mb4');
  3. Add META tag in HTML, For Example:



Question: What is difference between HTTP_HOST and SERVER_NAME?
The SERVER_NAME is defined in server config.
The HTTP_HOST is obtained from the HTTP request header.
To view SERVER_NAME and HTTP_HOST in server, use below code.
echo 'Server Name: '.$_SERVER['SERVER_NAME']; echo "\n";
echo 'HTTP HOST: '.$_SERVER['HTTP_HOST'];



Question: Difference between the Apache HTTP Server and Apache Tomcat?
Apache is HTTP server application which parse the PHP and return HTML.
Apache Tomcat is servlet container which is used to deploy your Java Servlets and JSPs.


Question: How to enable mod_rewrite for Apache 2.2?
To use rewrite mode, use following
a2enmod rewrite

then please re-start the web server.
service apache2 restart



Question: Give few tips for debugging .htaccess rules?
  1. Use a Fake-user agent.
  2. Do not use 301 until you are done testing.
  3. Remember that 301s are aggressively cached in your browser.
  4. Use a HTTP Capture tool.
  5. Use below for htacess testing: http://htaccess.madewithlove.be/ http://htaccess.mwl.be/



Question: How to give 777 permission to a folder and all contents?
chmod -R 777 .



Question: Why WAMP showing 403 Forbidden message on Windows 7?
Wrong Virtual Host configuration
http://www.web-technology-experts-notes.in/2013/04/set-up-virtual-host.html


Question: How to change port number for apache in WAMP?
  1. Open httpd.conf file, in wamp server. Location in My Computer: E:\wamp\bin\apache\apache2.2.22\conf\httpd.conf
  2. Search "Listen 80" and replace the port number.
    Listen 80 
    to
    Listen 8080
  3. Re-Start your wamp Server



Question: What is thread safe or non thread safe in PHP?
A Thread Safe version should be used if you install PHP as an Apache module [Using WampServer/Xampp Server]. The Non Thread Safe version should be used if you install PHP as a CGI binary.


Question: Which PHP mode? Apache vs CGI vs FastCGI?
There are multiple ways to execute PHP scripts on a web server.
Following are three different way to execute the PHP.
  1. Apache:Using mod_php to execute PHP scripts on a web server. It is the most popular.
  2. CGI: Executing PHP scripts with a CGI application on a Web Server. It is the legacy way of running applications.
  3. FastCGI: FastCGI was in between the PHP Apache Module and the CGI application. It allows scripts to be executed by an interpreter outside of the web server.




Thursday, 7 April 2016

Paypal IPN Validation in PHP

Paypal IPN Validation in PHP

Question: How to IPN? How to set IPN in Paypal?
http://www.web-technology-experts-notes.in/2016/03/instant-payment-notification-paypal.html


Question: Why we need to validate the IPN?
To make sure, all data sent in our server is from Paypal.


Question: What are benefits of validating the IPN?
  1. Protect our transaction from SPAM OR robots OR from hackers.
  2. Protect from dmmmy entires in our database.
  3. If protection is ON, We will always sure for transaction record in database.



Question: What does paypal do with valiation?
It will validate all the data, sent to paypal.


Question: What is name of parameter which is send to paypal for validation?
cmd.
For Example:
cmd=_notify-validate



Question: What does paypal return if validation failed?
INVALID


Question: How does paypal return, if validation passed?
VERIFIED


Question: How to validate IPN Response in Sandbox Mode?
$ipnData=$_POST;
$ipnData['cmd']='_notify-validate';
$verify= file_get_contents('https://www.sandbox.paypal.com/cgi-bin/webscr', false, stream_context_create(array(
            'http' => array(
                'header'  => "Content-type: application/x-www-form-urlencoded\r\nUser-Agent: MyAPP 1.0\r\n",
                'method'  => 'POST',
                'content' => http_build_query($ipnData)
            )
        )));  
if($verify=='VERIFIED'){
/** Your data is valid and it is return from paypal */

}



Question: How to validate Paypal IPN Response in LIVE Mode ?
$ipnData=$_POST;
$ipnData['cmd']='_notify-validate';
$verify= file_get_contents('https://www.paypal.com/cgi-bin/webscr', false, stream_context_create(array(
            'http' => array(
                'header'  => "Content-type: application/x-www-form-urlencoded\r\nUser-Agent: MyAPP 1.0\r\n",
                'method'  => 'POST',
                'content' => http_build_query($ipnData)
            )
        )));  
if($verify=='VERIFIED'){
/** Your data is valid and it is return from paypal */

}


Question: How to validate IPN Validate with curl?
$ipnData=$_POST;
$ipnData['cmd']='_notify-validate';

$validateURL='https://www.paypal.com/cgi-bin/webscr';//for paypal
//$validateURL='https://www.sandbox.paypal.com/cgi-bin/webscr'; //for sandbox paypal
   
$ch = curl_init($validateURL);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($ipnData));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close'));
if ( !($verify = curl_exec($ch)) ) {          
 curl_close($ch);
 die('Some Error');
}
curl_close($ch); 
var_dump($verify );//IF VERIFIED, then validate




Wednesday, 6 April 2016

Javascript Questions And Answers for Fresher and Experienced

Javascript Questions And Answers for Fresher and Experienced

Question: How to pass multiple parameter in setTimeout function?
function myFunctionName(var1,var2){
    console.log('called after 2 sec of page load '+var1+' '+var2);
}
setTimeout(myFunctionName,2000,'value1','value2');



Question: How to enumerate the properties of js objects?
var myObject = {name1: 'Value1',name2: 'Value2'};
//console.log(myObject); //It will print all the values

for (var name in myObject) {
  //console.log(name+'=>'+myObject[name]);
  }



Question: How to measure the execution time of javascript script?
var startTime = new Date().getTime();
/*
Write here you script
*/
for(i=1;i<=500000; i++){
}
var endTime = new Date().getTime();

var time = endTime - startTime;
console.log('Execution time in Milli Seconds: ' + time);
console.log('Execution time in Seconds: ' + time/1000);



Question: How to listen (Do some changes) the window.location.hash change?
$(window).on('hashchange', function() {  
  callNewFunction(window.location.href)  
});
function callNewFunction(url){
    console.log('Hash URL is called');
}

After appling above code, whenever you add/update the hash value, callNewFunction will called automatically.

hashchange event is HTML5 feature and supported by all modern browsers and support is added in following browser.
  1. Internet Explorer 8
  2. Firefox 3.6
  3. Chrome 5
  4. Safari 5
  5. Opera 10.6



Question: How to add class in an element?
HTML Part
<div id="myDivId">
</div>

javaScript Part
var d = document.getElementById("myDivId");
d.className += " newClass";



Question: How to get the list of classes for an element?
d = document.getElementById("myDivId");
console.log(d.className);



Question: Can we compare two javaScript objects?
Yes, We can compare two javascript objects. See Following examples.
var myObject1 = {name1: 'Value1',name2: 'Value2'};
var myObject2 = {name1: 'Value111',name2: 'Value222'};
if(JSON.stringify(myObject1) === JSON.stringify(myObject2)){
 console.log("Both object are same");
}else{
console.log("Both object are different");
} 



Question: What is difference between Array(3) and Array('3') in javascript?
new Array(3), means declare the 3 elements and each have value "undefined". new Array('3'), means declare the 1 element and have value 3.
console.log(new Array(3)); // [undefined, undefined, undefined]
console.log(new Array('3')); // ["3"]



Question: How to get browser URL for all browser?
console.log(window.location.href);



Question: How to remove an element(string OR object ) from javascript Array/Object?
var myObject = {name1: 'Value1',name2: 'Value2'};
delete myObject['name1']
console.log(myObject);



Question: What does jQuery.fn mean?
jQuery.fn is just an prototype for defining the new functions.
fn is an alias to the prototype property.
For Example,
$.fn.newFunctionName = function(val){
console.log('something '+val); //something Test Value
};
$.fn.newFunctionName('Test Value');



Question: How to remove an empty elements from an Array?
var simpleArray = [1,3,,3,null,,0,,undefined,4,,6,,];
var cleanArray = simpleArray.filter(function(n){ return n != undefined }); 
console.log(cleanArray);



Question: How to add 5 days in JavaScript?
var result = new Date();
result.setDate(result.getDate() + 5);
console.log(result);



Tuesday, 5 April 2016

Javascript Interview Questions And Answers for 4 year experienced

Javascript Interview Questions And Answers for 4 year experienced

Question: How to remove an item from javaScript Array?
var myArray = new Array('a', 'b', 'c', 'd');
var index = myArray.indexOf('b');
myArray.splice(myArray, 1);
console.log(myArray);



Question: How to call a function after 2 section?
function myFunctionName(){
    //console.log('called after 2 sec of page load');
}
setTimeout(myFunctionName,2000);



Question: How to start/stop setInterval function?
function myFunctionName(){
    //console.log('called after 2 sec of page load');
}
var refreshIntervalObject =setInterval(myFunctionName, 3000);
clearInterval(refreshIntervalObject);



Question: What is basic difference between $(document).ready() and window.onload?
$(document).ready(): This event occurs after the HTML document has been loaded.
window.onload This event when all content (e.g. html, js, images) also has been loaded.


Question: Is JavaScript a pass-by-reference OR pass-by-value?
passed by reference


Question: How to send cross domain Ajax Request?
You can send ajax request with "JSONP" only in Cross Domain.
$.ajax({
    url: '/ajax',
    dataType: 'jsonp',
    success:function(data, textStatus, request){
      console.log(request.getResponseHeader('some_header'));
    
    }
});   



Question: What is CDATA? When it is required?
CDATA stand for "Character Data" and it means that the data in between tags.
CDATA is required when you need an document to parse as XML.


Question: How to compare two Dates in javaScript?
var date1 = new Date();
var date2 = new Date(d1);
if(d1.getTime() === d2.getTime()){
    /* Both Time are are Same **/
}else{
    /* Time are are Different**/
}



Question: How to merge two array?
var array1 = ["One","Two"];
var array2 = ["Three", "Four"];
var mergeArray = array1.concat(array2);
console.log(mergeArray);



Question: How to use Regular Expression in JavaScript?
var searchString= '12 34';
var result=searchString.match( /\d+/g ) 
console.log(result ); //["12", "34"]
console.log(result.length+' Elements matched'); //2 Elements matched



Question: How to trigger ENTER key was pressed?
var code = e.keyCode || e.which; if(code == 13) { /** Enter key is pressed **/ }


Question: How to select element by Name?
var arrChkBox = document.getElementsByName("elementName");
Question: How to Convert character to ASCII code in JavaScript?
var characterString='$';
characterString.charCodeAt(0);//36



Question: What do you mean by "javascript:void(0)"?
javascript:void(0) means "DO Nothing";
for example:
<a href="javascript:void(0)">No effect on clicking</a>



Question: Can we detect, if javaScript is enabled?
Yes, we can do with html tag.
<noscript>
    javascript is not enabled, Please enable javascript in your browser.
</noscript>



Question: How to add element in the begining OR at the end of array?
var myArray = new Array('a', 'b', 'c', 'd');
myArray.push('end');
myArray.unshift('start');
console.log(myArray);




Monday, 4 April 2016

Javascript Interview Questions And Answers for 3 year experienced

Javascript Interview Questions And Answers for 3 year experienced

Question: How to open a URL in a new tab using javaScript?
JavaScript
function OpenInNewTab() {  
  var url='http://www.onlinevideoswatch.com/';
  var win = window.open(url, '_blank');
  win.focus();
}

Html
<div onclick="OpenInNewTab();">
Click to Open in Tab</div>



Question: How to Convert JavaScript String to be all lower case?
var strVal="How are yOu";
strVal.toLowerCase(); //how are you



Question: How to detect a mobile device in javaScript?
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
 /** You are using Mobile Devices**/
}



Question: How do you check if a variable is an array in JavaScript?
var myArray=new Array('one','two','three','four');
console.log(myArray);
var myval='two';

if (myArray.indexOf(myval)) {
  console.log('value is Array!');
} else {
  console.log('Not an array');
}



Question: How to generate random number between two numbers (1-100)?
var minimum=1
var maximum=100
var randomnumber 

randomnumber = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
console.log(randomnumber);



Question: How to declare constant in javaScript?
const MY_CONSTANT_NAME = "value that will never change";

Here you can't change the value of "MY_CONSTANT_NAME"
It Will work in all browsers except IE 8, 9 and 10.


Question: How can I format numbers as money format?
var monthlyExpanse=98765.432
monthlyExpanse.toFixed(4);//98765.4320 
monthlyExpanse.toFixed(3);//98765.432 
monthlyExpanse.toFixed(2);//98765.43
monthlyExpanse.toFixed(1);//98765.4



Question: How can display JSON data in readble form?
var str = JSON.stringify(obj, null, 2); // space level  2



Question: How to Get selected value from dropdown list ?
HTML
<select id="countryId">  
  <option value="11">England</option>
<option selected="selected" value="22">India</option>
  <option value="33">Japan</option>
</select>

JavaScript
var e = document.getElementById("countryId");
var countryId = e.options[e.selectedIndex].value;
//console.log(countryId); //22



Question: How to convert a number to hexadecimal,octal ?
var myNumber= 500;
//console.log(myNumber.toString(16));//1f4
//console.log(myNumber.toString(8));//764



Question: How to convert a hexadecimal,octal number to decimal?
var hexaDecimal='1f4';
var octal='764';
console.log(parseInt(hexaDecimal,16)); //500
console.log(parseInt(octal,8)); //500



Question: How to convert a String to Decimal?
var strVal='100';
number=parseInt(strVal);



Question: What is use of instanceof?
var simpleStr = "This is string"; 
var myString  = new String();
var newStr    = new String("constructor");
var myDate    = new Date();
var myObj     = {};

simpleStr instanceof String; // returns false, checks the prototype chain, finds undefined
myString  instanceof String; // returns true
newStr    instanceof String; // returns true
myString  instanceof Object; // returns true



Question: How to Scroll to the top of the page?
var xCoord=200;
var yCoord=500;
window.scrollTo(xCoord, yCoord);



Question: How to display javaScript Object?
console.log(obj);



Question: How to use namespaces in javaScript?
var myNamespaceName = {

    foo: function() {
        alert('foo');
    },

    foo2: function() {
        alert('foo2');
    }
};

myNamespaceName.foo();//alert foo
myNamespaceName.foo2();//alert foo2



Friday, 1 April 2016

Ajax Interview Questions and Answers for Fresher

Ajax Interview Questions and Answers for Fresher

Question: What are the advantages of AJAX?
  1. Quick Response.
  2. Quick Response without loading page.
  3. Save the Bandwidth
  4. Client Server Interaction what user letting know (User will not get disturb)



Question: What are the dis Advantages of AJAX?
  1. Dependency on JavaScript.
  2. An simple js error, Ajax will not called.
  3. Security issues Might comes, if not implemented securely.
  4. Difficult in Debugging for beginner
  5. Sometimes browser compatibility issues comes.



Question: What are top website, who uses Ajax?
  1. Youtube
  2. Google
  3. Bing
  4. Gmail
  5. Twitter
  6. Linkdin



Question: What are security issues in AJAX?
  1. Ajax is visible in browser console
  2. Request, Response, header and cookie are visiable in browser console.
  3. Every time called ajax is purely visiable in Ajax
  4. An Ajax request can be called by hackers OR unauthorized, It can damage the website if there are not properly security checks
  5. Attackers can try the ajax call with different request parameter.



Question: What are the technologies used by AJAX?
  1. Javascript
  2. XMLHttpRequest
  3. XML/JSON/HTML
  4. DOM
  5. You can also use third party libaraies like jQuery, mootools etc



Question: What are common AJAX Framework?
  1. jQuery
  2. MooTools
  3. Prototype
  4. YUI
  5. Dojo Toolkit
  6. Google Web Toolkit (GWT)



Question:What are Ajax applications?
The web applicable which use the more ajax calls are ajax application.


Question: What are different stage of XMLHttpRequest?
  1. 0: request not initialized
  2. 1: server connection established
  3. 2: request received
  4. 3: processing request
  5. 4: request finished and response is ready



Question: In Ajax call, which method is more secure GET/Post?
POST is more secure as compare to Get Method.


Question: Can anyone send ajax request with POST Method ?
Yes, can send using CURL.


Question: What is the difference between JavaScript and AJAX? JavaScript an object-oriented computer programming language used in web browsers.
Ajax is set of web development techniques using JavaScript to send/receive the data from server without loading page.


Question: What is Asynchronous in Ajax?
We can set the Asynchronous value as true OR false.
Async=true

Ajax request execute independently, Its response can come earlier than other request which is execute later .
Async=false
Ajax request does not execute independently, Its response can comes when earlier request finished.


Question: How to submit entire form data with Ajax?
//serialize ajax Data
var formData = $('form#formId').serialize();
$.ajax({ 
        url: '/my/site',
         data: formData,
         type: 'post',
         success: function(result) {
                      console.log(result);
          }
});



Question:Give a simple example of JSONP with Ajax?
$.getJSON("http://twitter.com/status/user_timeline/padraicb.json?count=10&callback=?", function(result){
   //Now result have response of ajax call
   console.log(result);
});