Saturday, 24 September 2016

How to add or remove query string in URL without page refresh


You can add/remove query string from URL without reloading page in javascript. Generally URL changes by page reloading. When URL changes page gets refresh and new content appears on page.
e.g. Go
Here when we click 'Go' it goes to new URL with query string.

HTML5 gave you facility to change URL using pushState function to change URL and append data using ajax.
e.g. history.pushState({state:1, rand: Math.random()}, '', "?page="+1);
history.pushState function is used to add history state. It takes three parameters: a state object, a title (which is currently ignored), and (optionally) a URL.

You can test code by clicking following buttons
      


Use following code function to modify query string without page reload
//Add jquery
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.js"></script>
<script>
//Define variable
var objQueryString={};

//Get querystring value
function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
    results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

//Add or modify querystring
function changeUrl(key,value) {
 //Get query string value
 var searchUrl=location.search;
 if(searchUrl.indexOf("?")== "-1") {
  var urlValue='?'+key+'='+value;
  history.pushState({state:1, rand: Math.random()}, '', urlValue);
 }
 else {
  //Check for key in query string, if not present
  if(searchUrl.indexOf(key)== "-1") {
   var urlValue=searchUrl+'&'+key+'='+value;
  }
  else { //If key present in query string
   oldValue = getParameterByName(key);
   if(searchUrl.indexOf("?"+key+"=")!= "-1") {
    urlValue = searchUrl.replace('?'+key+'='+oldValue,'?'+key+'='+value);
   }
   else {
    urlValue = searchUrl.replace('&'+key+'='+oldValue,'&'+key+'='+value); 
   }
  }
  history.pushState({state:1, rand: Math.random()}, '', urlValue);
  //history.pushState function is used to add history state.
  //It takes three parameters: a state object, a title (which is currently ignored), and (optionally) a URL.
 }
 objQueryString.key=value;
 sendAjaxReq(objQueryString);
}

//Used to display data in webpage from ajax
function sendAjaxReq(objQueryString) {
 $.post('test.php', objQueryString, function(data) {
  //alert(data);
 })
}


//Function used to remove querystring
function removeQString(key) {
 var urlValue=document.location.href;
 
 //Get query string value
 var searchUrl=location.search;
 
 if(key!="") {
  oldValue = getParameterByName(key);
  removeVal=key+"="+oldValue;
  if(searchUrl.indexOf('?'+removeVal+'&')!= "-1") {
   urlValue=urlValue.replace('?'+removeVal+'&','?');
  }
  else if(searchUrl.indexOf('&'+removeVal+'&')!= "-1") {
   urlValue=urlValue.replace('&'+removeVal+'&','&');
  }
  else if(searchUrl.indexOf('?'+removeVal)!= "-1") {
   urlValue=urlValue.replace('?'+removeVal,'');
  }
  else if(searchUrl.indexOf('&'+removeVal)!= "-1") {
   urlValue=urlValue.replace('&'+removeVal,'');
  }
 }
 else {
  var searchUrl=location.search;
  urlValue=urlValue.replace(searchUrl,'');
 }
 history.pushState({state:1, rand: Math.random()}, '', urlValue);
}

</script>

<div>
 <input type="button" value="Add id" onClick="changeUrl('id','2')" />
 <input type="button" value="Add category" onClick="changeUrl('category','mobile')" />
 <input type="button" value="Add item" onClick="changeUrl('item','samsung')" />

 <input type="button" value="Remove id" onClick="removeQString('id','2')" />
 <input type="button" value="Remove category" onClick="removeQString('category')" />
 <input type="button" value="Remove item" onClick="removeQString('item')" />
 <input type="button" value="Remove query string" onClick="removeQString('')" />
</div>
Find more details on http://www.fbchandra.com/developers/add-remove-query-string-url-without-reloading-page/ 

Saturday, 17 September 2016

Explain MVC (Model View controller) software architecture

 

Model-view-controller (MVC) is a software architectural pattern for implementing user interfaces and business logic. It divides a software into three layers which manages the request coming from users and separates the internal representation of information.

Components:
The components of MVC are given below
  1. Model, captures the behavior of the application in terms of its problem domain, independent of the user interface. The model directly manages the data, logic and rules of the application. It is mainly used for database interaction.
  2. View can be any output representation of information, such as a chart or a diagram. Multiple views of the same information are possible, such as a bar chart for management and a tabular view for accountants. What we see on screen, comes from view. HTML or display is part of view.
  3. Controller, accepts input and converts it to commands for the model or view. When you hit any URL, firstly calls goes to controller. Here we decide, we have to show plain HTML or need to display data from database to HTML. If we have to display from plain HTML, we simply call view from controller otherwise, we calls model for database interaction, fetch relevant data from database and pass it to view.

Interactions:
In addition to dividing the application into three kinds of components, the model-view-controller design defines the interactions between them.
  1. A model stores data that is retrieved according to commands from the controller and displayed in the view.
  2. A view generates new output to the user based on changes in the model.
  3. A controller can send commands to the model to update the model's state (e.g. editing a document). It can also send commands to its associated view to change the view's presentation of the model (e.g. by scrolling through a document).

Model: The model represents data and the rules that govern access to and updates of this data. In enterprise software, a model often serves as a software approximation of a real-world process.
View: The view renders the contents of a model. It specifies exactly how the model data should be presented. If the model data changes, the view must update its presentation as needed. This can be achieved by using a push model, in which the view registers itself with the model for change notifications, or a pull model, in which the view is responsible for calling the model when it needs to retrieve the most current data.
Controller: The controller translates the user's interactions with the view into actions that the model will perform. In a stand-alone GUI client, user interactions could be button clicks or menu selections, whereas in an enterprise web application, they appear as GET and POST HTTP requests. Depending on the context, a controller may also select a new view -- for example, a web page of results -- to present back to the user.

There are two types of Programming models:
  1. Model 1
  2. Model 2(MVC) Architecture
Model 1 Architecture :
Servlet and JSP are the main technology to develop the web application. Servlet was considered as the superior to CGI. But is has some advantages and disadvantages also.
The main advantage is Servlet creates thread instead of creating process to handle the request. The advantage of Creating thread over process is that it doesn't allocate the separate memory. So many subsequent request can be handlled parallely.
The main disadvantage is :
  1. Servlet mixs up the Presentation and Business Logic.
  2. Servlet needs recompilation after a single change in the code.

To overcome the above mentioned problem, JSP can be used. It provides better seperation of Presentation and Business Logic by using the Java Bean, custom tags and JSTL, not required to compile the source file every time after a single change in the source file.

In this diagram, Users are sending the request through web browser for the JSP pages. JSP access Java Bean and invokes the Business Logic. Java Bean connects to the database to operate with the data and it gives the response to the browser which will be shown to the user through the JSP Pages.
Advantage:
  1. Very easy to implement the web application using MVC 1 Architecture.
  2. Clear separation between business logic and presentation logic.
  3. All objects and classes are independent to each other. So change in one class doesn't need to alter in another class.
  4. Reusable : Multiple views using the same model.
  5. Clarity of Design : Easy to maintain the code and future improvements.
Disadvantage :
  1. Time Consuming : It will take more time to develop the custom tags in JSP.
  2. It is better for small application, not for the large application.
  3. Decentralizatio of Navigation Control : Every page has the logic to determine the next page navigation. If the name of the JSP page is changed then it will affect the other pages also.
  4. Complexity : It is increasing the complexity.

Model 2 Architecture :
Model 2 is based on MVC (Model-View-Controller) design pattern.
Model The model represents the state (data) and business logic of the application.
View The view module is responsible to display data i.e. it represents the presentation.
Controller The controller module acts as an interface between view and model. It intercepts all the requests i.e. receives input and commands to Model / View to change accordingly.

Features of MVC 2:
  1. The MVC2 architecture removes the page centric property of MVC1 architecture by separating Presentation, control logic and the application state.
  2. In MVC2 architecture there is only one controller which receives the entire request for the application and is responsible for taking appropriate action in response to each request.
Difference Between MVC 1 and MVC 2:
MVC 1MVC 2
MVC 1 associates the presentation and Business Logic.MVC 2 isolates the presentation logic from Business Logic.
One component is responsible for receiving the request and sending the response.There are separate components for receiving and sending the response i.e. Controller and View.
As Business Logic and Presentation Logic mixes up, so web designer and web developer can't work simultaneously.As both are separated so web designer and developer can work simultaneously.
Doesn't support reusability of components.Support reusability of components.
View : JSP
Controller : Servlet
Model: JavaBeans
View : JSP/HTML
Controller : ActionServlet
Model : ActionForm(Java Class)

Monday, 5 September 2016

Basics of PHP

 

 

 

 

 

 



PHP (PHP Hypertext Preprocessor) is an open source general HTML embedded purpose scripting language which is specially used for web development. PHP also has support for talking to other services using protocols such as LDAP, IMAP, SNMP, NNTP, POP3, HTTP, COM (on Windows) and countless others. You can also open raw network sockets and interact using any other protocol. PHP has support for the WDDX complex data exchange between virtually all Web programming languages.
PHP Scripts can be used mainly for three purposes :
  • Server-Side Scripting : Three things are required to make this work. The PHP parser (CGI or server module), a web server and a web browser. You need to run the web server, with a connected PHP installation. You can access the PHP program output with a web browser, viewing the PHP page through the server.
  • Command Line Scripting : PHP script can be run without any server or browser. You only need the PHP parser to use it this way. This type of usage is ideal for scripts regularly executed using cron (on Unix or Linux) or Task Scheduler (on Windows). These scripts can also be used for simple text processing tasks.
  • Writing desktop applications : PHP is probably not the very best language to create a desktop application with a graphical user interface, but if you know PHP very well, and would like to use some advanced PHP features in your client-side applications you can also use PHP-GTK to write such programs.
PHP Versions :
  1. PHP was created sometime in 1994 by Rasmus Lerdorf. Rasmus Lerdorf, who wrote the original Common Gateway Interface (CGI) component, together with Andi Gutmans and Zeev Suraski, who rewrote the parser that formed PHP 3. PHP takes most of its syntax from C, Java, and Perl. PHP was written in the C programming language by Rasmus Lerdorf in 1994 for use in monitoring his online resume and related personal information.
  2. The Second generation implementation started to evolve PHP from a suit of tools into a programming language. It included built in support for DBM, mSQL, Postgres95 database, cookies, user-defined function support and much more. Lerdorf combined PHP with his own Form Interpreter, releasing the combination publicly as PHP/FI (generally referred to as PHP 2.0) on June 8, 1995.
  3. One of the biggest strengths of PHP 3.0 are the user interface for the multiple databases, protocols and APIs, the ease of extending the language itself attracted dozens of developers who submitted a variety of modules. Other key features introduced in PHP 3.0 included object-oriented programming support and a far more powerful and consistent language syntax. In June, 1998, with many new developers from around the world joining the effort, PHP 3.0 was announced by the new PHP Development Team as the official successor to PHP/FI 2.0.
  4. By 1998, shortly after PHP 3.0 was officially released, Andi Gutmans and Zeev Suraski had begun working on a rewrite of PHP's core. The design goals were to improve performance of complex applications, and improve the modularity of PHP's code base. The new engine, dubbed 'Zend Engine' (comprised of their first names, Zeev and Andi), met these design goals successfully, and was first introduced in mid 1999. PHP 4.0, based on this engine, and coupled with a wide range of additional new features, was officially released in May 2000. PHP 4.0 included other key features such as support for many more web servers, HTTP sessions, output buffering, more secure ways of handling user input and several new language constructs.
  5. PHP 5 was released in July 2004 after long development and several pre-releases. It is mainly driven by its core, the Zend Engine 2.0 with a new object model and dozens of other new features. PHP's development team includes supporting projects, such as PEAR, PECL, and documentation, and an underlying network infrastructure of well over one-hundred individual web servers on six of the seven continents of the world.
Advantages of PHP:
  1. Open source: It is developed and maintained by a large group of PHP developers, this will helps in creating a support community, abundant extension library.
  2. Speed: It is relative fast since it uses much system resource.
  3. Easy to use: It uses C like syntax, so for those who are familiar with C, it's very easy for them to pick up and it is very easy to create website scripts.
  4. Stable: Since it is maintained by many developers, so when bugs are found, it can be quickly fixed.
  5. Powerful library support: You can easily find functional modules you need such as PDF, Graph etc.
  6. Built-in database connection modules: You can connect to database easily using PHP, since many websites are data/content driven, so we will use database frequently, this will largely reduce the development time of web apps.
  7. Can be run on many platforms, including Windows, Linux and Mac, it's easy for users to find hosting service providers.
Disadvantages of PHP :
  1. Security : Since it is open sourced, all people can see the source code as text in public folder if any thing mishappen in apache. PHP does not it self protect its file. If there are bugs in the source code, it can be used by people to explore the weakness of PHP
  2. Not suitable for large applications: Hard to maintain since it is not very modular. Now a days, lots of framework and CMS has arrived in market to sort this problem.
  3. Weak type: Implicit conversion may surprise unwary programmers and lead to unexpected bugs. For example, the strings "1000" and "1e3" compare equal because they are implicitly cast to floating point numbers.

View more on http://www.fbchandra.com/developers/