Monday, 30 November 2015

AngularJS Interview Questions and Answers for Experienced

AngularJS Interview Questions and Answers for Experienced



Question: What is AngularJS?
It is javasScript framework which is written in javascript. It is Best for Single Page Applications. It extend the html with new attributes which makes it more useful for UI Developer.


Question: In which language, AngularJS is written?
javaScript


Question: When First AngularJS was released?
2009

Question: When latest AngularJS was released?
November 24, 2017


Question: What is latest version of AngularJS?
1.6.7


Question: Who created AngularJS?
Misko Hevery started to work on AngularJS in 2009. He was employee of Google.
Question: Is it opensource?
Yes, It is free to use.



Question: Explain what are the key features of Angular.js?
  1. Scope
  2. Controller
  3. Model
  4. View
  5. Services
  6. Data Binding
  7. Directives
  8. Filters
  9. Testable



Question: From where we can download the AngularJS File?
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>



Question: What is controller in AngularJS?
Controller is constructor function in Angular Controller.
When a Controller is attached to the DOM with use the ng-controller, Angular will instantiate a new Controller object using constructor function.



Question: Explain what are directives?
Directives are used to add new attributes of HTML.



Question: What are the different types of Directive?
Different types of directives are
  1. Element directives
  2. Attribute directives
  3. CSS class directives
  4. Comment directives



Question: Explain what is injector?
An injector is a service locator, used to retrieve object instances.



Question: Explain what are factory method in angularJs?
Factory method are used to create the directive. It is invoked only once, when compiler matches the directive for the first time.



Question: Does Angular use the jQuery library?
Ans. Yes, Angular can use jQuery if you have included the jQuery library.
IF Not, Angular falls back to its own implementation of the subset of jQuery that we call jQLite.



Question: What is ng-app, ng-init and ng-model?
ng-app - To initialize the Angular Application.
ng-init - To initialize the Angular Application data.
ng-model - To bind the html tags (input, select, textarea) to Angular Application Data.



Question: What is Data Binding in Angular JS?
It is synchronization of data between the model(Angular Application variable) and view components (display with {{}}).



Question: Give an Example of Data-Binding in AngularJS?
<div ng-app="" ng-init="quantity=10;cost=5">
<b>Total Cost: {{ quantity * cost }}</b>
</div>


Question: What is Looping in AngularJs and Give an Example?
It is used to display the data in loop same as foreach in PHP
Example:
<div data-ng-app="" data-ng-init="names=['Web','Technology','Experts','Notes']">
<b>Loop Example:</b>
  <br />
<ul>
<li data-ng-repeat="x in names">
      {{ x }}
    </li>
</ul>
</div>

Question: How to Write Expression in AngularJS?
<div ng-app="">
<b>Expression: {{ 15 + 55 }}</b>
</div>



Question: How to initiate variable in AngularJS?
<div ng-app="" ng-init="quantity=10;cost=5">
<b>Total Cost: {{ quantity * cost }}</b>
</div>


OR

<div ng-app="" ng-init="quantity=1;cost=5">
<b>Total Cost: <span ng-bind="quantity * cost"></span></b>
</div>



Question: Example of AngularJS Strings?
<div ng-app="" ng-init="Str1='Web';Str2='Technology'">
Full String is : <b>{{ Str1 + " " + Str2 }}</b>
</div>




Question: Example of AngularJS Object?
<div ng-app="" ng-init="myobj={Str1:'Web',Str2:'Technology'}">
String Display: <b>{{ myobj.Str2 }}</b></div>



Question: What is Angular Controllers & give an Example?
Controller is constructor function in Angular Controller.
When a Controller is attached to the DOM with use the ng-controller, Angular will instantiate a new Controller object using constructor function.
Example:
<div ng-app="" ng-controller="StrControllerExample">
String 1: <input ng-model="str1" type="text" /><br />
String 2: <input ng-model="str2" type="text" /><br />
Full String <b> {{fullString()}}</b>
</div>
<script>
function StrControllerExample($scope) {
    $scope.str1 = "Web",
    $scope.str2 = "Technology",
    $scope.fullString = function() {
        return $scope.str1+ " " + $scope.str2;
    }
}
</script>




Question: What is Dependency Injection?
Dependency Injection (DI) is a software design pattern that deals with how components get deal of their dependencies.


MongoDB Database Commands with Examples

mongoDB Database Commands with Examples

Question: Expalin the Basic terminology for MongoDB?
RDBMS MongoDB
Database Database
Table Collection
Tuple/Row Document
column Field
Table Join Embedded Documents
Primary Key Primary Key (Default key _id provided by mongodb itself)
Mysqld/Oracle mongod
mysql/sqlplus mongo

Note: # used for commenting.

Question: Create a New database?
use mydb #switched to db mydb



Question: Check which database you are currently using?
use



Question: Display the List of databases?
show dbs #All database will display which have atleast 1 document.



Question: Delete the current database?
db.dropDatabase() #Delete the current used database.



Question: How to create collection for a database?
db.createCollection("mycollection") #create a collection for current selected database.



Question: Display the List of collections in database?
show collections #All collection will display for current database.



Question: How to drop the collection?
db.mycollection.drop() #mycollection collection will be deleted.



Question: How to delete all the records from mongodb ?
db.collection.remove();



Question: How to delete all the records with condition?
db.collection.remove({uid=111});

Will delete all the record where uid=1111


Question: How to insert data(Know as document) into collection?
db.mycollection.insert({
   _id: ObjectId(7df78ad89765),
   title: 'MongoDB Overview',    
   by: 'Web technology',   
   tags: ['mongodb', 'database', 'NoSQL'],   
})
#Single document is added in collection "mycollection" .



Question: How to add multiple document into collection in single command?
db.mycollection.insert({
   {   
   title: 'MongoDB Overview',    
   by: 'Web technology',   
   tags: ['mongodb', 'database', 'NoSQL'],   
   },
 
   {
   title: 'MongoDB Overview2',    
   by: 'Web technology experts notes',   
   tags: ['mongodb', 'database', 'NoSQL' ,'Multiple Record'],   
       
   }
])



Question: What is command for search a document? Give Example?
find() is used to search. For Example

db.mycollection.find()#Search the one document in un structured way .



Question: How to search a document in pretty way (structured way) ? Give Example?
pretty() is used to search in pretty way. For Example

db.mycollection.find({"by":"Web technology"}).pretty()#Search the one document in structured way .



Question: How to search a document with "and condition"?
db.mycollection.find({"by":"Web technology",{"title": "MongoDB Overview"}}).pretty()#Search the one document in structured way .



Question: How to list first 10 document?
db.mycollection.find({"by":"Web technology",{"title": "MongoDB Overview"}}).limit(10).pretty()#Search the 10 document in structured way .



Question: How to get 2nd document?
db.mycollection.find({"by":"Web technology",{"title": "MongoDB Overview"}}).limit(1).skip(1).pretty()#Search the 10 document in structured way .



Question: How to list document with title ascending order?
db.mycollection.find({"by":"Web technology",{"title": "MongoDB Overview"}}).sort({"title":1}).pretty()#Search the in title ascending order.



Question: How to search document in title descending order?
db.mycollection.find({"by":"Web technology",{"title": "MongoDB Overview"}}).sort({"title":-1}).pretty()#Search the in title descending order. 



Question: How to Add indexing?
db.mycollection.ensureIndex({"title":1,"description":-1})#title in ascending order and description in descending order.To create index in descending order you need to use -1. 



Question: How to search a document with "OR condition"?
db.mycollection.find({"by":"Web technology",$or[{"title": "MongoDB Overview"}]}).pretty()#Search the one document in structured way .



Question: How to update a document?
db.mycollection.update({'title':'MongoDB Overview'},{$set:{'title':'MongoDB text'}})#update "MongoDB Overview" with "MongoDB text " .



Question: How to delete a document?
db.mycollection.remove({'title':'MongoDB Overview'})#Delete the record where document is 'MongoDB Overview' .




Find all records
db.mycollection.find();
Display all the records in this collection.



Find all records and display in pretty way
db.mycollection.find().pretty();
Display all the records in this collection but presentable way.



Find all records with single condition (Age: 29)
db.mycollection.find({age:29});
Display all the records where age=29.



Find all records with multiple AND condition (Age: 29, Number:17)
db.mycollection.find({age:29, number:17});
Display all the records where age=29 and number=17



Find all records with multiple OR condition (Age: 29 OR Number:17)
db.mycollection.find({$or:[{age:29},{number:17}]});
Display all the records where age=29 OR number=17 (each of one).



Find all records with multiple OR condition (Age>28 OR Number:17)
db.mycollection.find({$or:[{age:{$gt:28}},{number:17}]});
Display all the records where age>29 and number=17



Find all records and display and one display column (name)
db.mycollection.find({},{name:1}).pretty();
Display all the name in this collections.



Find all records and display and two display column (name and number)
db.mycollection.find({},{name:1,number:1}).pretty();
Display all the name and number in this collections.



Limit the number of record
db.mycollection.find().limit(3).pretty();
Display only 3 records.



Display all the records except 1,2,3
db.mycollection.find().skip(3).pretty();
Skip first 3 records.


Saturday, 28 November 2015

PayPal Express Checkout Working Flow - In Simple Steps with Clean Example


PayPal Express Checkout Working Flow
PayPal Express Checkout is a powerful API-based solution that can be integrated into any merchant website. With PayPal Express Checkout API, customer leave the website and complete the transaction in http://paypal.com, where customer can pay with paypal.com account OR with credit card / Debit card. When start processing, Paypal gives a TOKEN key which is used to charge money from customer OR get the Payment Details OR Customer Shipping/Billing details. Developer should save this token key for future use.


Express Checkout have Simple Seven Steps. Start from initializing the token and end with success page after payment.


Customer makes their payment and completes their order on your website. This enables tighter integration with your website and order management processes. It can be more efficient for PayPal users and may facilitate sales.



Following are 7 Steps of express Checkout
Step 1: Get Token API In this case we need to send an API call to Paypal Server with item detail, receiver email etc.
Request Parameter Example
Array
(
    [USER] => PAYPAL_API_EMAIL
    [PWD] => PAYPAL_API_PASSWORD
    [SIGNATURE] => PAYPAL_API_SIGNATURE
    [VERSION] => 95
    [ip] => 127.0.0.1
    [METHOD] => SetExpressCheckout
    [returnUrl] => http://example.com/order/success //customer will return this URL, if paid
    [cancelUrl] => http://example.com/order/failed //customer will return this URL, if not paid
    [L_PAYMENTREQUEST_0_NAME0] => Om Belt - Black
    [L_PAYMENTREQUEST_0_DESC0] => Obscure Belts
    [L_PAYMENTREQUEST_0_AMT0] => 82.92
    [L_PAYMENTREQUEST_0_QTY0] => 1
    [PAYMENTREQUEST_0_CURRENCYCODE] => USD
    [PAYMENTREQUEST_0_SHIPPINGAMT] => 5.15
    [PAYMENTREQUEST_0_AMT] => 88.07
    [PAYMENTREQUEST_0_ITEMAMT] => 82.92
    [PAYMENTREQUEST_0_PAYMENTACTION] => Order
    [PAYMENTREQUEST_0_SELLERPAYPALACCOUNTID] => receiver_email_address;//payment will receive by this paypal email
    [PAYMENTREQUEST_0_PAYMENTREQUESTID] => ORDER_UNIQUE_ID
)

Step 2: Get Token From API Response After calling above API, we will get below response
Array
(
    [TOKEN] => EC-06N33746DC1035058
    [TIMESTAMP] => 2014-08-11T11:40:52Z
    [CORRELATIONID] => dcda5dabca4a7
    [ACK] => Success
    [VERSION] => 95
    [BUILD] => 12301660
)
Now, Store the TOKEN will be used in future


Step 3: Send Customer to Paypal After getting success, we will send customer to following URL with appending token key
https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&useraction=commit&token=EC-06N33746DC1035058
Here User will see Cart detail and can pay after login.

Step 4: Order Confirmation Page After login successfully, Customer will move to Order Confirmation page with "Pay Now" Button
(Here user will see the cart detail and can pay)

Step 5: Get Order Detail When Customer paid successfully, customer will return to returnUrl (see step1), In return URL, TOKEN and PayerID will be appended automatically.
From TOKEN, we will get to know for what order user return.
From PayerID, We will get to know user is ready to pay us and also we used this Id to charge him.

Call following API, to get the Order Detail From Paypal
Array
(
    [USER] => PAYPAL_API_EMAIL
    [PWD] => PAYPAL_API_PASSWORD
    [SIGNATURE] => PAYPAL_API_SIGNATURE
    [VERSION] => 95
    [url] => https://api-3t.sandbox.paypal.com/nvp
    [METHOD] => GetExpressCheckoutDetails
    [TOKEN] => EC-06N33746DC1035058
)

After calling above API, response will be return

Step 6: Charge Money From Customer We need to a new paypal method to charge the customer i.e DoExpressCheckoutPayment
Request Params Example
Array
(
    [USER] => PAYPAL_API_EMAIL
    [PWD] => PAYPAL_API_PASSWORD
    [SIGNATURE] => PAYPAL_API_SIGNATURE
    [VERSION] => 95
    [url] => https://api-3t.sandbox.paypal.com/nvp
    [METHOD] => DoExpressCheckoutPayment
    [TOKEN] => EC-06N33746DC1035058
    [PAYERID] => HS5JSKPGX4T2G
    [L_PAYMENTREQUEST_0_NAME0] => Om Belt - Black
    [L_PAYMENTREQUEST_0_DESC0] => Obscure Belts
    [L_PAYMENTREQUEST_0_AMT0] => 82.92
    [L_PAYMENTREQUEST_0_QTY0] => 1
    [PAYMENTREQUEST_0_CURRENCYCODE] => USD
    [PAYMENTREQUEST_0_SHIPPINGAMT] => 5.15
    [PAYMENTREQUEST_0_AMT] => 88.07
    [PAYMENTREQUEST_0_ITEMAMT] => 82.92
    [PAYMENTREQUEST_0_SELLERPAYPALACCOUNTID] => receiver_email_address//payment will receive by this paypal email
   
)

When we call DoExpressCheckoutPayment, We will charge the payment from customer Account and an email will be sent to customer and receiver.

Step 7: Check Resonse
Array
(
    [TOKEN] => EC-06N33746DC1035058
    [SUCCESSPAGEREDIRECTREQUESTED] => false
    [TIMESTAMP] => 2014-08-11T12:41:32Z
    [CORRELATIONID] => e5d0b3a5e674a
    [ACK] => Success
    [VERSION] => 95
    [BUILD] => 12301660
    [INSURANCEOPTIONSELECTED] => false
    [SHIPPINGOPTIONISDEFAULT] => false
    [PAYMENTINFO_0_TRANSACTIONID] => 6HD429843V086060C
    [PAYMENTINFO_0_TRANSACTIONTYPE] => cart
    [PAYMENTINFO_0_PAYMENTTYPE] => instant
    [PAYMENTINFO_0_ORDERTIME] => 2014-08-11T12:41:32Z
    [PAYMENTINFO_0_AMT] => 88.07
    [PAYMENTINFO_0_FEEAMT] => 2.85
    [PAYMENTINFO_0_TAXAMT] => 0.00
    [PAYMENTINFO_0_CURRENCYCODE] => USD
    [PAYMENTINFO_0_PAYMENTSTATUS] => Completed
    [PAYMENTINFO_0_PENDINGREASON] => None
    [PAYMENTINFO_0_REASONCODE] => None
    [PAYMENTINFO_0_PROTECTIONELIGIBILITY] => Eligible
    [PAYMENTINFO_0_PROTECTIONELIGIBILITYTYPE] => ItemNotReceivedEligible,UnauthorizedPaymentEligible
    [PAYMENTINFO_0_SELLERPAYPALACCOUNTID] => receiver_email_address
    [PAYMENTINFO_0_SECUREMERCHANTACCOUNTID] => UFBX24KTUHJKU
    [PAYMENTINFO_0_ERRORCODE] => 0
    [PAYMENTINFO_0_ACK] => Success
)


Customer can pay with Credit card without Paypal Account

  1. Login to Paypal
  2. Go to Profile subtab
  3. Click on Website Payment Preferences under the Selling Preferences column
  4. Check the yes box under PayPal Account Optional


Comparison between MySQL and MongoDB

Comparison between MySQL and MongoDB

Features MySQL MongoDB
Logo


Type of Database? Relational Database Document-oriented database
Initial release 23 May 1995 13 October 2015
Current Stable Version 5.7.18 / 10 April 2017 3.4.5 / 14 June 2017
Written in C/C++ C/C++, JavaScript
Open Source Yes Yes
License GPL (version 2) or proprietary GNU AGPL v3.0 (drivers: Apache license)
Offical Website http://www.mysql.com https://www.mongodb.org
How stored Data In Structed, data is stored in tables. Unstructed, data is stored in Collection in JSON Format.
Terminology Table
Row
Column
Joins
Collection
Document
Field
Embedded documents, linking
Normalization used to minimize data redundancy Normalization is obsolete for MongoDB
Get data from two different tables Joins are used References are used
Transactions vs Atomic Updates MySQL Support No supported
How to get data SQL Query is used you need to used functions with parameter
Security MySQL uses privilege-based security model. MongoDB security features include authentication, authorization and auditing
Select Query
SELECT * FROM users
 WHERE name LIKE "%Web%";
db.books.find({"name": { 
"$regex":  "Web" }});
Insertion Query
INSERT INTO users (user_id, age, status) 
VALUES ("100", 20, "Active")
db.users.insert({  user_id: "100",
  
age: 20,  status: "Active"})
Update Query
UPDATE users SET status = "Active" 
WHERE age > 25
db.users.update( {
age: { $gt: 25 } }, { $set: { 
status: "Active" } }, { multi: true }
)
Insert data Speed Normall Much Faster as compare to MySQL
Best Database for Very-2 Heavy Site Not MongoDB is better
DBA Required Yes, For better performance Not required
Rich Data Model No Yes
Dyamic Schema No Yes
Typed Data Yes Yes
Data Locality No Yes
Field Updates Yes Yes
Easy for Programmers No Yes
Complex Transactions Yes No
Auditing Yes Yes
Auto-Sharding No Yes

Thursday, 26 November 2015

How to bookmarks a web page with JavaScript


How to bookmarks a web page with JavaScript


Follow Simple 3 Steps.
  1. Add Following code where you want to show the Bookmark Button.
    <a href="https://www.blogger.com/blogger.g?blogID=5911253879674558037#" id="bookmarkmarkme" rel="sidebar" title="Click to Bookmark this Page">Bookmark Me</a>
  2. Include jQuery File
    <script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
  3. Add Following JavaScript code at end of page.
                            $(document).ready(function() {
                              $("#bookmarkmarkme").click(function() {
                                /* Mozilla Firefox Bookmark */
                                if ('sidebar' in window && 'addPanel' in window.sidebar) { 
                                    window.sidebar.addPanel(location.href,document.title,"");
                                } else if( /*@cc_on!@*/false) { // IE Favorite
                                    window.external.AddFavorite(location.href,document.title); 
                                } else { // webkit - safari/chrome
                                    alert('Press ' + (navigator.userAgent.toLowerCase().indexOf('mac') != - 1 ? 'Command/Cmd' : 'CTRL') + ' + D to bookmark this page.');
                                }
                            });
                          });
                                        



Friday, 20 November 2015

Top 10 Ajax interview Questions and Answers

Top 10 Ajax interview Questions and Answers



Question 1: Give basic example of JSONP with Ajax?
Full Form of JSONP is JSON with padding.
JSONP is a simply way to overcome the XMLHttpRequest same domain policy. (As we know, we can't send Ajax request to a different domain.)
But with use of JSONP we can do the same.

$.getJSON("http://example.com/file.json?callback=?", function(result){
   console.log(result); //Here response will comes   
});



Question 2: How to add header in Ajax call?
Way 1: Add Header in Ajax call
$.ajax({
    url: '/aja/ajax-call',
    headers: {
        'Authorization':'Basic xxxxxxxxxxxxx',
        'X_CSRF_TOKEN':'xxxxxxxxxxxxxxxxxxxx',
        'Content-Type':'application/json'
    },
    method: 'POST',
    dataType: 'json',
    data: 'name=test&age=20&gender=m',
    success: function(data){
      console.log(data);
    }
  });

Way 2: Add Header Before send the Ajax call
$.ajax({
    url: '/aja/ajax-call',
    beforeSend: function (request){
       request.setRequestHeader("Authority", authorizationToken);
    },
    method: 'POST',
    dataType: 'json',
    data: 'name=test&age=20&gender=m',
    success: function(data){
      console.log(data);
    }
  });




Question 3: URL Encode a string before sending in Ajax call?
$.ajax({
    url: '/aja/ajax-call', 
    method: 'POST',
    dataType: 'json',
   data: 'name=test&age=20&gender=m&url='+encodeURIComponent('http://web-technology-experts-notes.in'),
    success: function(data){
      console.log(data);
    }
  });



Question: Do AJAX requests retain PHP Session info?
Yes,


Question 4: What should i do when i didn't get result in Ajax Call? use error:, I ajax code. For Example:
$.ajax({
    url: '/aja/ajax-call', 
    dataType: 'json',
   data: 'name=test&age=20&gender=m',
    success: function(data){
      console.log(data);
    },
    error: function ( jqXHR, textStatus, errorThrown ) {
        console.log(jqXHR+'-'+textStatus+'-'+errorThrown);
      },
  });



Question 5: How to send ajax request synchronously? set async as false, for Example
$.ajax({
    url: '/aja/ajax-call', 
    dataType: 'json',
   data: 'name=test&age=20&gender=m',
    success: function(data){
      console.log(data);
    },
    async:false ,
  });



Question 6: Can we send post data with JSONP?
No, we can get only results with JSONP


Question 7: How to get the jQuery $.ajax error response text?
Add following node, in $.ajax,
error: function(xhr, status, error) {
  var err = xhr.responseText;
}



Question 8: How to pass entire form in Ajax call?
First serialize the form data and pass in ajax call. For Example.
$.ajax({
    url: '/aja/ajax-call', 
    dataType: 'json',
   data: $('form#formId').serialize(), /* Must be serialized **/
    success: function(data){
      console.log(data);
    },
    error: function ( jqXHR, textStatus, errorThrown ) {
        console.log(jqXHR+'-'+textStatus+'-'+errorThrown);
      },
  });



Question 9: What are different readyStates in XHLHttpRequest?
State     Description
0- The request is not initialized
1- The request has been set up
2- The request has been sent
3- The request is in process
4- The request is complete


Question 10: How we can upload the image with Ajax?
use uploadify plugin.
http://www.uploadify.com/demos


Thursday, 19 November 2015

Top 10 jQuery interview Questions and Answers

Top 10 jQuery interview Questions and Answers


Question: How to replace the text of div using class?
Suppose HTML
<div class="myDivClass">
Update this text</div>
jQuery code 
$('.myDivClass').text('Updated'); 



Question: How to replace the text of div using "div id"?
Suppose HTML
<div id="myDivId">
Update this text</div>
jQuery code 
$('#myDivId').text('Updated'); 



Question: How to replace the html of div using class?
Suppose HTML
<div class="myDivClass">
Update this html</div>
jQuery code 
$('.myDivClass').html('Updated'); 



Question: How to replace the text of div using "div id"?
Suppose HTML
<div id="myDivId">
Update this text</div>
jQuery code 
$('#myDivId').html('Updated'); 



Question: How to Check if checkbox is checked?
Suppose HTML is
<input name="lang[]" type="checkbox" value="English" />
<input name="lang[]" type="checkbox" value="Hindi" />
<input name="lang[]" type="checkbox" value="Urdu" />

JQuery code
var totalCheckboxSelected = $('input[name="lang[]"]:checked').length;
if(totalCheckboxSelected){
    console.log(totalCheckboxSelected+' check box checked');
}else{
    console.log('NO checkbox is selected');
}



Question: How can you check for a #hash in a URL?
if(window.location.hash) {
    var hashValue = window.location.hash.substring(1);
    console.log(hashValue);
} else {
  console.log('Hash not found');
} 



Question: How get to know which mouse button is pressed?
$('#divId').mousedown(function(event) {
    switch (event.which) {
        case 1:
            console.log('Left button pressed.');
            break;
        case 2:
            console.log('Middle button pressed.');
            break;
        case 3:
            console.log('Right button pressed.');
            break;
        default:
            console.log('Exception Case!');
    }
});



Question: How to add update the color of div with jQuery?
$('div#divId').css("background-color", "red");



Question: How to remove class from div?
$("div#divId").removeClass('className'); 



Question: How do I get the value of a textbox using jQuery?
Html

<input id="websiteId" name="website" type="text" value="Web Technology Experts Notes" /> jQuery:
$("#websiteId").val();



Question: How to submit form with post method with Ajax?
HTML Form
<form action="/ajax/form-url" id="ajaxform" method="POST" name="ajaxform">
First Name: <input name="fname" type="text" value="" /> <br />
Last Name: <input name="lname" type="text" value="" /> <br />
<input name="submit" type="submit" value="Submit the Form" /> </form>

jQuery Code
$( document ).ready(function() {
    $("#ajaxformSubmit").submit(function(e)
    {
        var postData = $(this).serializeArray();
        var formURL = '/ajax/form-url'
        $.ajax(
        {
            url : formURL,
            type: "POST",
            data : postData,
            success:function(data, textStatus) 
            {            console.log(data);
            }
        });
        e.preventDefault(); //STOP default action
    });
});



Question: How to escape the text?
var someHtmlString = "";
var escaped = $("
").text(someHtmlString).html(); console.log(escaped); //<script>aalert('hi!');</script>



Sunday, 15 November 2015

Top 10 PHP Interview Questions and Answers


Top 10 PHP Interview Questions and Answers


Question 1: How to redirect a page to another?
You can use header function to recirect.
header('location: http://www.web-technology-experts-notes.in"); //Redirect to home page of another website

header('location: http://www.web-technology-experts-notes.in/2015/11/php-questions-and-answers-for-experienced.html"); //Redirect to another page and another website

header('location: php-questions-and-answers-for-experienced.html"); //Redirect to another page of same website

header('location: php-questions-and-answers-for-experienced.html?topic=php");  //Redirect to another page of same website with parameter

header('Location: http://www.web-technology-experts-notes.in/2015/11/php-questions-and-answers-for-experienced.html', true, 301); //Permanent Redirect

Following are different use of header functions.
  1. Redirect from one page to another page. Also can redirect to another website.
  2. Help to download the file like (csv download, pdf download etc).
  3. Browser Authentication to the web page.
  4. Set the header of any page at the top of page.



Question 2: Is it secure to store a password in a session?
No,
If you still need then please stored in encrypted form with different name (not password).


Question 3: How to set/get PHP array in cookie?
//Set an array in cookie
$arrayData=json_encode(array(1,2,3,4,5,6));
setcookie('no_array', $arrayData);

//Get an array from cookie
$cookie = $_COOKIE['no_array'];
$arrayData = json_decode($cookie);
print_r($arrayData);



Question 4: What is the difference between bindParam and bindValue?
$string='this is ';
if (strlen($string) != strlen(utf8_decode($string)))
{
    echo 'is unicode';
}else{
  echo 'It is Not unicode.';
}



Question 5: How to add 30 mins to a date?
$date = date("Y-m-d H:i:s");
date("Y/m/d h:i:s", strtotime("+30 minutes", $date));



Question 6: How to get Path From URL?
$url = "http://www.web-technology-experts-notes.in/2013/09/amazon-s3-introduction.html";
$path = parse_url($url);
print_r($path);
/**Array
(
    [scheme] => http
    [host] => www.web-technology-experts-notes.in
    [path] => /2013/09/amazon-s3-introduction.html
)*/



Question 7: How to get array elements which present in two different array?
$array1 = array("a" => "green", "red", "blue");
$array2 = array("b" => "green", "yellow", "red");
$result = array_intersect($array1, $array2);
print_r($result);
/**Array ( [a] => green [0] => red )*/



Question 8: How to replace array elements with another another?
$input = array("red", "green", "blue", "yellow");
array_splice($input, -1, 1, array("black", "maroon"));
print_r($input);

/*Array ( [0] => red [1] => green [2] => blue [3] => black [4] => maroon )*/



Question 9: Count number of elements in an array?
$foodArray = array('fruits' => array('orange', 'banana', 'apple'),
              'veggie' => array('carrot', 'collard', 'pea'));

echo count($foodArray); // output 2
// recursive count
echo count($foodArray, COUNT_RECURSIVE); // output 8



Question 10: How to exchanges all keys with their associated values in an array?
$input = array("oranges", "apples","mango", "pears");
$flippedArray = array_flip($input);

print_r($flippedArray);
/*Array ( [oranges] => 0 [apples] => 1 [mango] => 2 [pears] => 3 )*/



Saturday, 14 November 2015

PHP Questions and Answers for experienced

PHP Questions and Answers for experienced



Question: Difference between array_map, array_walk and array_filter?
array_map: This function applies the callback to the elements of the given arrays.
$arrayData= array_map('strtolower', array('One','Two','three'));
print_r($arrayData); //array ( [0] => one [1] => two [2] => three )

array_walk: This function apply a user supplied function to every member of an array
function my_function(&$item, $key){
  $item=$item.($key+1);
}
$arrayData=array('One','Two','three');
array_walk($arrayData, 'my_function');
print_r($arrayData); //Array ( [0] => One1 [1] => Two2 [2] => three3 )

array_filter: This function filters elements of an array using a callback function.
function odd_number($item){
  if($item%2==0){
    return false;
    }else{
    return true;
    }
}
$arrayData=array(1,2,3,4,5,6);
$arrayData=array_filter($arrayData, 'odd_number');
print_r($arrayData); //Array ( [0] => 1 [2] => 3 [4] => 5 )



Question: How to convert date to timestamp in PHP??
echo strtotime('2015-09-15'); //1442275200



Question: Give an easy way to encrypt/decrypt the password?
define('SALT', 'X4DSF464ADS6SC5C5D55D5'); 
function encrypt_string($text) 
{ 
    return trim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, SALT, $text, MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND)))); 
} 

function decrypt_string($text) 
{ 
    return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, SALT, base64_decode($text), MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND))); 
} 

echo $msg = encrypt_string("your message"); //q2s33vKz5sNPPQFzZygm4nqtjuPljaI+9q1mtcwRZ3U=
echo decrypt_string($msg);//your message


Question: How to get the last character of a string in PHP?
echo substr("web tehnology", -1); // y



Question: How to store array in constants??
$arrayData=array(1,2,3,4,5,6);
define ("FRUITS", serialize($arrayData));
print_r(unserialize (FRUITS));



Question: What is the difference between bindParam and bindValue?
bindParam the variable is bound as a reference and will only be evaluated at the time that PDOStatement::execute() is called. PDOStatement::bindValue() is not work in this way.


Question: What is use of PHP_EOL?
PHP_EOL is used to find the newline character in a cross-platform-compatible way so it handles DOS/Mac/Unix issues.


Question: How to get accurate Ip Address of client Machine?
function ip_address(){
    foreach (array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $key){
        if (array_key_exists($key, $_SERVER) === true){
            foreach (explode(',', $_SERVER[$key]) as $ip){
                $ip = trim($ip); // just to be safe

                if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false){
                    return $ip;
                }
            }
        }
    }
}
echo ip_address();//101.60.216.68 



Question: How to get extension of file??
$path ='/web-tech/myimage.png';
print_r(pathinfo($path, PATHINFO_EXTENSION));



Question: How to Check if PHP session has already started?
if(session_id() == '') {
    echo "session not started";
}else{
 echo "session started";
}



Question: NOW() equivalent function in PHP?
echo date("Y-m-d H:i:s"); //2015-11-14 9:52:32



Question: How to get all php functions?
print_r(get_defined_functions());



Friday, 13 November 2015

PHP Difficult Interview Questions and Answers

PHP Difficult Interview Questions and Answers


Question: How to check a variable is NULL OR empty string?
var_dump($variableName);

Also for compare you can use === to compare data type.


Question: How can I execute an anonymous function?
call_user_func(function() { echo 'anonymous function called.'; });



Question: How can I measure the speed of code written in PHP?
$startTime= microtime(true);
/** Write here you code to check **/
/** Write here you code to check **/
$endTime= microtime(true);
echo 'Time Taken to executre the code:'.$endTime-$startTime;



Question: Which PHP Extension help to debug the code?
Xdebug


Question: How to get Yesterday date?
date("F j, Y", strtotime( '-1 days' ) ); //November 11, 2015



Question: How to set HTTP header to UTF-8 using?
Add following at the top of page.
header('Content-Type: text/html; charset=utf-8');



Question: How to get first 20 characters from string?
echo substr('Web Technology Experts Notes',0,20);



Question: How to get last date of month of given date?
$date = "2015-11-23";
echo date("Y-m-t", strtotime($date));



Question: How do I check with PHP if file exists?
$filename = "/folder/filename.php";
if (file_exists($filename)) {    
    echo "The file $filename exists.";    
} else {
    echo "The file $filename does not exists.";
}



Question: How to remove non-alphanumeric characters ?
echo preg_replace("/[^A-Za-z0-9 ]/", '', 'web technology experts notes @2015 '); //web technology experts notes 2015



Question: How do I replace all line breaks (\n\r) in a string with
tags?

echo str_replace(array('\r','\n','\r\n'),'
','Hello \n Web technology');



Question: How do I format a number to a dollar amount in PHP? Give Example?
Use money_format
echo money_format('$%i', 6.6); // echos '$3.40' //echos $6.60



Question: How to prevent Browser cache for php site?
Add following code at the top of web page.
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");



Question: How do i get the current script file name?
echo __FILE__; //htdocs/project/index.php



Question: How to add key/value in existing array?
$arrayname['keyname'] = 'new value';