Monday, December 25, 2017

How to display PDF in html web page

Usually, we need to display PDF file in HTML web page, today we will learn how do we embed the PDF file in a web page. There are many ways to do this. It's important to understand the best approach that suits your needs. Following are super easy methods for adding the PDF to your Website. 1. <embed />
<embed src="https://sumanbogati.github.io/tiny.pdf" width="600px" height="500px" />
Pros:- No JavaScript required, HTML standard, and Easy to use. Cons:- It does not have a fallback when your browser is not able to display PDF. DEMO 2. <object> </object>
<object data="https://sumanbogati.github.io/tiny.pdf" type="application/pdf" width="600" height="500">
  test.pdf
</object>
Pros:- No JavaScript required, HTML standard, and Easy to use. If a browser does not display the PDF then it let the user download the PDF by fallback. DEMO

3. <iframe> </iframe>
<iframe src="https://sumanbogati.github.io/tiny.pdf" style="width:600px; height:500px;"></iframe>
Pros:-
No JavaScript required, HTML standard, and Easy to use. You can reach the maximum users using a iframe.
DEMO

To cover the maximum browsers
, you can use the following code
<object data="https://sumanbogati.github.io/tiny.pdf" type="application/pdf" width="600" height="500">
    <embed src="https://sumanbogati.github.io/tiny.pdf" width="600px" height="500px" />
        

This browser does not support PDFs. Please download the PDF to view it: Download PDF.

</embed></object>
To reach the android browser

Any of the above method, does not display PDF in android browser, for that you need to upload the PDF to google drive and share that document with everyone, now you get the link and use this URL with embed tag, eg:-
<embed src="https://drive.google.com/file/d/1ZKgZhUuBr_-nLnbpExhQmqKCx_1QqxT2/preview" width="800px" height="1000px" />
We will reach to all the Desktop and android browsers
by following code,
<object data="https://drive.google.com/file/d/1ZKgZhUuBr_-nLnbpExhQmqKCx_1QqxT2/preview"  width="600" height="500">
    <embed src="https://drive.google.com/file/d/1ZKgZhUuBr_-nLnbpExhQmqKCx_1QqxT2/preview" width="600px" height="500px" />
        

This browser does not support PDFs. Please download the PDF to view it: View the PDF.

</embed></object>

Advance way to display PDF in html web page,

If you want to display PDF in browsers of all devices(Desktop and android mobiles) and want more control over displaying PDF in html web page, then the pdf.js will be useful. Following are the reasons which might attract you to use pdf.js,

  • Control over PDF toolbar in browser, there can be the interface, by which, end user can zoom and navigate the PDF pages.
  • Some annotation over the displayed PDF.
  • Supports on all desktop and mobile browsers.
  • It’s secure, users are not able to download the PDF.
  • You can validate on html web page that PDF is rendered or not.
  • pdf.js is JavaScript library which is maintained by Mozilla, it's so reliable and community supported, that, even Opera browser uses this framework on their own browser.

DEMO

Conclusion

If you need to display simply a PDF and does not want more control over the PDF in browser then the mix use of object and embed tag will be fine, otherwise, pdf.js can be the great tool.

Friday, November 10, 2017

Best books to learn JavaScript

I would suggest using following JavaScript books for different learners.

If you are a beginner in JavaScript, the book A Smarter Way to Learn JavaScript will be perfect for you. The author of the book teaches the JavaScript in a unique way.

Most interestingly, this book helps you to learn JavaScript doing practical exercises, which is powerful and helpful for a beginner.

If you are looking for intermediate or advanced JavaScript learning, the book Eloquent JavaScript will be excellent. After reading each few chapters, you will get the project that needs to be done for actual learning.

This book has also chapters about latest technologies like Node.js, Canvas, and Web-socket related to JavaScript.

Other than that, the resources from Mozilla Developer Network can be useful, for example, if you would like to know about querySelector() method, you would just type querySelector mdn on google, most probably the top link from a result will be the resource you need.

Takeaway

After so many years of experience in programming, I could say with surety that practical knowledge would not come only by reading the book and online resources, for that you need to use what you have learned, it would not gain until your brain fight to solve the problem by coding in your favorite editor.

Sunday, November 5, 2017

Difference between undefined and null in JavaScript


Every JavaScript programmer uses the undefined and null in their programming career, but do we really know the difference between them.

Today I put some light on differences between undefined and null and which one we should use when we programming?


Definition

Variable undefined means it has been declared but did not assign real value yet(eg: string, number, boolean and object). This also means the value does not exist before the scope, for example,

var color; 
console.log(color);

With above code, we are trying to access the declared variable which has no value, so as a result, color is undefined.


Variable null (var country = null) means it has no values, if you go deeper this means it has 'no object values'. After initializing the variable with null, it expects from the program that 'country' will hold the object at later.


Javascript throws the variable/property is undefined,


When you try to access the variable which is declared but did not associate any value,

var name;
console.log(name); // name is undefined


If you explicitly assign the undefined value

var name = undefined;


When you try to access the object’s property which is not defined yet,

var mycar = {color:'red'}
if(mycar.name==undefined){
    console.log(mycar.name) // mycar.name is undefined 
}


When the function does not return anything, sum contains undefined in the following case,

var sum = function (){console.log(2+2)};


When a function is defined with parameters but it invokes without the arguments,

function subtract(val1, valu2){ console.log(val1 + val2)}


after invoking subtract(3), val2 is undefined in above function.


The variable seems to null,


When you explicitly assign a null value to variable or property of the object,


var mycar = null; and var office.employee=null;


When browser tries to access the element which is not available in DOM,

var firstElem = document.getElementById('header');


the element with the id 'header' is not available in the browser, so firstElem is null.


When I use undefined?

If we need to check undefined against variable explicitly, for example, one scenario could be
where a variable is not undefined but it might be the null, following statement could be used

if(name !== undefined ){
    // this is being executed even when name = null;
}


When I use null?

If we want to check the variable is undefined, 'no object values', or element is null, then we use null, for example, we issue the query to check the DOM existence.

var header = document.querySelector('#header');

From above code,  we can validate if the header has something by checking header is null or not.


Conclusion

With null and undefined, it seems we are checking the same thing (no values) with two different approaches, so which one we should pick?. I want to go with null because it can be used to check for both null and undefined of the variable, whereas other is used to check undefined only.

Below condition is true if the variable(
name) is not undefined and is not null.

if(name != null){
  // this is executed when variable name has anything but undefined and null
}

Saturday, January 7, 2017

Ajax using by plain JavaScript

Why we need Ajax ?

Ajax is needed to make the HTTP request to the server without page refresh, What does this mean? Have you know about when you type something on google which provides suggestions related to your query from google database without loading the page. To See the demo just type some letter on below input box.
Ajax can be used to update any part of the web page without a browser refresh. For example, a website has a block named “Most Visited News”, which shows 5 most visited news items, and it has “More” link at bottom of the block, after clicking this link, there would show all visited news items without a page load. It gives the smooth user experience HTTP request is used for send/receive data to/from a server. A page refresh gives the extra load to the server than a single HTTP request, because after reloading the page, the client sends the total numbers of HTTP requests as many as JavaScript, Images, and CSS files are used on this page.


Normal process for HTTP request

If you want to display new data in your site from database by clicking a link or submitting a form, without using Ajax the architecture would be something like



With the traditional way, for fetching data from a server, the HTTP request from a browser to server happens with page load only. As I said above, the site has a block “Most Visited News”, and a link “More” under this block. It does not use Ajax and after clicking on the link, the new data would display with the page loading.


Ajax process for HTTP request

Below figure shows the client does HTTP request to a server without page load by using Ajax.


With Ajax for performing above more-item task, if you click on “More” link, the browser displays the information without page load and the user even does not know what’s going on the background. A user will have a great user experience with this.

What is Ajax?

Ajax is the sum of Asynchronous JavaScript and XML. To understand this you should have knowledge of JavaScript, HTML and basic about CSS. It sends the data by using XMLHttpRequest object and get the response back from a server.

Let’s understand the code that how do we send/receive data to/from a server. I have created the example module named Ajax.

Initialize the XMLHttpRequest

 
var Ajax = {
 /**
  This Function initiates the XMLHttpRequeset Object,
  the object-path for commmunication between Client and Server.
 **/
 init: function () {
  if (window.XMLHttpRequest) {
   //IE7+, Firefox, Chrome, Opera, Safari
   this.http = new XMLHttpRequest();
  } else {
   // // IE 6 and older
   this.http = new ActiveXObject("Microsoft.XMLHTTP");
  }
             
  this.onReadStateChange();
  
  // It triggers if some error occured with http request
  this.http.onerror = function (err) {
   console.log("Error " + err);
  };
  
  // It triggers if http request is interrupted
  this.http.onabort = function (evt) {
   console.log("Error abort " + evt);
  }
 },


In above function init,  you are just initiating the XMLHttpRequest object through new XMLHttpRequest() for latest browser and new ActiveXObject("Microsoft.XMLHTTP"); is for IE6 and older. The client uses this object to send the HTTP request to server.

Send data/request to server

/**
 This function is used to send the http
 request to server, The paramter "path" expects for server path
 and "data" for sending to server.
**/
send: function (method, data, path, cb) {
 console.log('send');
 /** callback function is initiate and
  will be invoked after got response from server **/
 this.cb = cb; 
 if(method == 'GET'){
  // To send data in GET method, we prepend '?' to the data
  path =  path+'?'+data; 
  data = null;
  this.http.open(method,  path, true);
 } else {
  this.http.open(method,  path, true);
  
  /** It sends the data by using POST method as key pair value like,
  with name=suman&age=30, server gets value as name = suman; and age = 30; **/
  this.http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
 }
 // Sending request to server
 this.http.send(data); 
}


The function send is used to initialize HTTP request and send it to server. It accepts the path of a server, a method either it’s GET or POST, and the data as key pair value, like name=suman.

It has also expected callback function which will be invoked after fetching the data from a server.
To initialize HTTP request and for sending request to server, this.http.open(method,  path, true) and  this.http.send(data) are used.

Get response from server 

/**
 This Function triggers to show the HTTP request status, 
 it gets the data from server if request is succeed
**/
onReadStateChange: function () {
 console.log('init');
 var that = this;
 this.http.onreadystatechange = function (evt) {
  console.log('ready state ' + that.http.readyState + ' status code ' + that.http.status);
  // It means the fetch operation has been completed
  if (that.http.readyState == 4) {
   if (typeof that.cb != 'undefined') {
    // 200, means http request is successful.
    // with readyState 4 means, data is downloaded successfully
    if (that.http.status == 200) {
     that.cb({'data' : that.http.responseText});
    } else {
     that.cb({'error' : evt});                            
    }
   }
  }
 }
},
};


This method onReadStateChange  receives the data from server, gets the error if something wrong happens in client or a server, and shows the status of HTTP request. 

In this method, readyState 4 and HTTP status 200 show that the data is downloaded successfully and there would trigger the callback function which was received during sending the HTTP request in send method.

Use the Ajax module,

var data = 'rdata=hello&name=suman'; 

// The path of server to which the HTTTP request is sent.
var path = 'server.php'; 

/** The callback function will trigger, 
 after fetching the data from server **/
function afterResponse(response){ 
 var result = response.hasOwnProperty('error') ? "Something bad happens." : response.data;
 document.querySelector("#result h3").innerHTML = result;
}

Ajax.init();
Ajax.send('POST', data, path, afterResponse);


By above code, we initializing the module with providing method, data, path, and callback function afterResponse. Inside this callback function you can perform the action based on a response given by server.

About readyStage and HTTP Status code

There is two type of information we should know about like, readyState shows the state of HTTP request client and HTTP status shows that request has been completed successfully or not.
You can get more about readyState and status code.

Below table shows different information about request status by the different combination.

readyState
HTTP status
description
1
0
The request has been opened but not sent yet.
2
200
The request to sever has been sent and it’s successful.
3
200
The data is being downloaded from server.
4
200
The data is downloaded on client successfully from server.

You can get the source code by Ajax using plain JavaScript.