CSC/ECE 517 Fall 2009/wiki2 2 rv: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
No edit summary
No edit summary
 
(28 intermediate revisions by one other user not shown)
Line 1: Line 1:
=AJAX implementation in MVC environments of  in Ruby , Java , PHP , ASP.NET=
=AJAX implementation in Ruby , Java , PHP and ASP.NET MVC Framework=
==MVC Environment==
MVC


==AJAX==
==1.Ajax==
AJAX is an efficient way for a web application to handle user interactions with a web page  -- a way that reduces the need to do a page refresh or full page reload for every user interaction. This enables rich behavior (similar to that of a desktop application or plug-in-based web application) using a browser. AJAX interactions are handled asynchronously in the background. As this happens, a user can continue working with the page. AJAX Interactions are initiated by the JavaScript in the web page. When the AJAX interaction is complete, JavaScript updates the HTML source of the page. The changes are made immediately without requiring a page refresh. AJAX interactions can be used to do things such as validate form entries (while the user is entering them) using server-side logic, retrieve detailed data from the server, dynamically update data on a page, and submit partial forms from the page.
AJAX is an efficient way for a web application to handle user interactions with a web page  -- a way that reduces the need to do a page refresh or full page reload for every user interaction. This enables rich behavior (similar to that of a desktop application or plugin-based web application) using a browser. AJAX interactions are handled asynchronously in the background. As this happens, a user can continue working with the page. AJAX Interactions are initiated by the JavaScript in the web page. When the AJAX interaction is complete, JavaScript updates the HTML source of the page. The changes are made immediately without requiring a page refresh. AJAX interactions can be used to do things such as validate form entries (while the user is entering them) using server-side logic, retrieve detailed data from the server, dynamically update data on a page, and submit partial forms from the page.


What is particularly attractive about this is that AJAX applications do not require a separate plug-in, and are platform and browser-neutral. That said, AJAX is not supported as well in older browsers. Care needs to be taken in writing client-side script that accounts for the differences between browsers.
What is particularly attractive about this is that AJAX applications do not require a separate plug-in, and are platform and browser-neutral. That said, AJAX is not supported as well in older browsers. Care needs to be taken in writing client-side script that accounts for the differences between browsers.
   
   
==AJAX Implemetaions ==  
==2.Model–View–Controller (MVC) ==
AJAX
Model–View–Controller (MVC) is an architectural pattern used in software engineering. The pattern isolates business logic from input and presentation, permitting independent development, testing and maintenance of each.
===AJAX in Ruby===


Models the domain-specific representation of the data on which the application operates. Domain logic adds meaning to raw data (for example, calculating whether today is the user's birthday, or the totals, taxes, and shipping charges for shopping cart items). When a model changes its state, it notifies its associated views so they can refresh.Many applications use a persistent storage mechanism (such as a database) to store data. MVC does not specifically mention the data access layer because it is understood to be underneath or encapsulated by the model. Models are not data access objects although in very simple apps, with little domain logic, there is no real distinction to be made. Also, the ActiveRecord is an accepted design pattern which merges domain logic and data access code - a model which knows how to persist itself.ViewRenders the model into a form suitable for interaction, typically a user interface element. Multiple views can exist for a single model for different purposes.ControllerReceives input and initiates a response by making calls on model objects.
[[Image:MVC_diag.jpg]]
* A model is an object representing data or even activity, e.g. a database table or even some plant-floor production-machine process.
* A view is some form of visualization of the state of the model.
* A controller offers facilities to change the state of the model.
                                                     
An MVC application may be a collection of model/view/controller triplets, each responsible for a different UI element.
MVC is often seen in web applications where the view is the HTML or XHTML generated by the app. The controller receives GET or POST input and decides what to do with it, handing over to domain objects (ie the model) which contain the business rules and know how to carry out specific tasks such as processing a new subscription.
==Implentaion of Ajax in MVC framework ==
===Ajax used in Ruby Framework===
Basically used in View and controller
Basically used in View and controller
How to Use Ajax in Our Web Application
How to Use Ajax in Our Web Application
Line 26: Line 38:
Once the browser has rendered and displayed the initial web page, different user actions cause it to display a new web page (like any traditional web app) or trigger an Ajax operation:
Once the browser has rendered and displayed the initial web page, different user actions cause it to display a new web page (like any traditional web app) or trigger an Ajax operation:


*A trigger action occurs. This could be the user clicking on a button or link, the user making changes to the data on a form or in a field, or just a periodic trigger (based on a timer).
* A trigger action occurs. This could be the user clicking on a button or link, the user making changes to the data on a form or in a field, or just a periodic trigger (based on a timer).
*Data associated with the trigger (a field or an entire form) is sent asynchronously to an action handler on the server via XMLHttpRequest.
* Data associated with the trigger (a field or an entire form) is sent asynchronously to an action handler on the server via XMLHttpRequest.
*The server-side action handler takes some action (that's why it is an action handler) based on the data, and returns an HTML fragment as its response.
* The server-side action handler takes some action (that's why it is an action handler) based on the data, and returns an HTML fragment as its response.
*The client-side JavaScript (created automatically by Rails) receives the HTML fragment and uses it to update a specified part of the current page's HTML, often the content of a <div> tag.  
* The client-side JavaScript (created automatically by Rails) receives the HTML fragment and uses it to update a specified part of the current page's HTML, often the content of a <div> tag.  


   
   
Steps to implement Ajax in Ruby:
Steps to implement Ajax in Ruby:
   
   
*Using a link_to_remote tag in the HTML
a. Using a link_to_remote tag in the HTML
       <%= link_to_remote( "Register",
       <%= link_to_remote( "Register",
                         :update => "new_user",
                         :update => "new_user",
                         :url =>{ :action => "allusers" }) %>
                         :url =>{ :action => "allusers" }) %>
    This tag tells that the name of the link is "Register", it will render the new response inside div named as "new_user" and it will call "allusers" action from controller.
This tag tells that the name of the link is "Register", it will render the new response inside div named as "new_user" and it will call "allusers" action from controller.
   
   
*After this allusers action  will render in a partial template like this:
b. After this allusers action  will render in a partial template like this:
         render :parti => "allusers"
         render :parti => "allusers"
*This call will go to a "_allusers" file where response will be populated and result will come inside div tag "new_user".
c. This call will go to a "_allusers" file where response will be populated and result will come inside div tag "new_user".
    
    
   
   


===AJAX in Java===
===Ajax used in Java Framework===
   
   
In the Java Frame work the MVC performs the follwoing functions:
The view registers as a listener on the model. Any changes to the underlying data of the model immediately result in a broadcast change notification, which the view receives. This is an example of the push model described earlier. Note that the model is not aware of the view or the controller -- it simply broadcasts change notifications to all interested listeners.
The controller is bound to the view. This typically means that any user actions that are performed on the view will invoke a registered listener method in the controller class.
The controller is given a reference to the underlying model.
Once a user interacts with the view, the following actions occur:
The view recognizes that a GUI action -- for example, pushing a button or dragging a scroll bar -- has occurred, using a listener method that is registered to be called when such an action occurs.
The view calls the appropriate method on the controller.
The controller accesses the model, possibly updating it in a way appropriate to the user's action.
If the model has been altered, it notifies interested listeners, such as the view, of the change. In some architectures, the controller may also be responsible for updating the view. This is common in Java technology-based enterprise applications.
Implementing autocomplete in a search field is something that can be performed using AJAX. To do it, we need to provide code on the client and on the server.
There are three Java Ajax Framework based on MVC architecture.
*'''[http://ajaxanywhere.sourceforge.net/ AjaxAnywhere] turns any set of existing JSP/JSF/Struts/Spring/etc.. components into AJAX-aware components without a complexe JavaScript coding.'''
The features of AjaxAnywhere are:
-Does not break existing server-side MVC architecture.
-Less JavaScript to develop and to maintain. Absence of commonly accepted naming convention, formatting rules, patterns makes JavaScript code messier then Java/JSP. It is extremely difficult to debug and unit-test it in multi-browser environment. Get rid of all those complexities by using AjaxAnywhere.
-Easy to integrate. AjaxAnywhere does not require changing the underlying application code.
-Graceful degradation. Switch whenever you need between AJAX and traditional (refresh-all-page) behaviour of your web application. Your application can also support both behaviors.
*'''[http://struts.apache.org/ Struts] is a MVC library that (since version 2) includes complex AJAX-tags'''
AJAX is a JavaScript can make a HTTP request and update portions of a page directly, without going through a conventional POST or GET and refreshing the entire page. Better yet, a page can contain several JavaScripts making simultaneous (asynchronous) requests.The key point is that when a script makes an "Ajax request" (XHR), the server doesn't know it came from a script, and handles it like any other request. One reason Ajax is so successful is that it works just fine with existing server technologies, including Struts.
It's not the Ajax request that is different, but the Ajax response. Instead of returning an entire page for the browser to display (or redisplay), an Ajax response will just return a portion of a page. The response can take the form of XML, or HTML, or plain text, another script, or whatever else the calling script may want.
Both Struts 1 and Struts 2 can return any type of response. We are not limited to forwarding to a server page. In Struts 1, you can just do something like:
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("Hello World!  This is an AJAX response from a Struts Action.");
out.flush();
return null;
In Struts 2, we can do the same thing with a Stream result.
package actions;
import java.io.InputStream;
import java.io.StringBufferInputStream;
import com.opensymphony.xwork2.ActionSupport;
public class TextResult extends ActionSupport  {
    private InputStream inputStream;
    public InputStream getInputStream() {
        return inputStream;
    }
    public String execute() throws Exception {
        inputStream = new StringBufferInputStream("Hello World! This is a text string response from a Struts 2 Action.");
        return SUCCESS;
    }
}
Struts 2 Configuring the TextResult Action
<action name="text-result" class="actions.TextResult">
    <result type="stream">
        <param name="contentType">text/html</param>
        <param name="inputName">inputStream</param>
    </result>
</action>
*'''[http://ifw2.sourceforge.net/ IFW2] An open source business-applications oriented Ajax framework with support for JPA/EJB3'''
Here the approach to Ajax is quite different from other solutions ,  the system is able to track, on the server side, changes to the page displayed on the browser and, through a small javascript runtime, to refresh only changed parts . It is completely transparent to the programmer which has to deal only with a new jsp tag library. This is the view side of our MVC model, but work has been done also on the controller and model side. The controller side is based around the concept of Flow which lets the programmer design the interaction with the user as finite state-machines. Each flow can be in turn nested in another flow and became a state of it (sub-flow), used in modal interaction with the user or as a component of another flow (the main difference with a sub-flow is that a component is active concurrently with other components and can interact with them in a way similar to portlets).


Implementing auto complete in a search field is something that can be performed using AJAX. To do it, we need to provide code on the client and on the server.
===Ajax used in PHP Framework===
Ajax in PHP has the following flow
*1. you have an HTML page, styled with CSS
*2. you click on something
*3. JS sends request to the server (to a PHP script)
*4. JS updates the original HTML page


On the Client
The MVC Pattern :
When implemeting Ajax in PHP the MVC patter develops as follows
*Model:It contains the PHP script and the logic , it interacts with the database .
*View:It contains the CSS style sheets , HTML ,DOM and the JavaScript that updates the HTML.
*Controller: It has the PHP script on the server side and the JavaScript on the Client side.


First, the user specifies the URL of a page that is loaded by the browser. For this example let's assume the page is an HTML page that is generated by a JSF component, servlet, or JSP page. The page contains a form text field that has an attribute onkeyup with the name of a JavaScript function doCompletion(). This function is called each time a key is pressed in the form text field.
MVC implementation requires a well working Object model from the programming language, and because PHP4 was missing those capabilities no strong libraries emerged.  
<input type="text" size="20" autocomplete="off" id="complete-field" name="id" onkeyup="doCompletion();">


Let's assume that a user types in an "M" character in the form text field. In response, the doCompletion() function is called which, in turn, initializes an XMLHttpRequest object:
There are various frameworks that use PHP-AJAX in them , one of them that uses the MVC Pattern is The Akelos PHP Framework
  function initRequest() {
It is a web application development platform based on the MVC (Model View Controller) design pattern.
      if (window.XMLHttpRequest) {
          return new XMLHttpRequest();
      } else if (window.ActiveXObject) {
          isIE = true;
          return new ActiveXObject("Microsoft.XMLHTTP");
      }
  }


  function doCompletion() {
[http://www.adevel.com/amodules3/ AModules3] is a flexible framework for developing applications using Object Oriented Programming. It's like "Rails" for PHP. It utilizes new features only found in PHP5 and shapes your application into a very efficient code. The following features are also included:
      if (completeField.value == "") {
          clearTable();
      } else {
          var url = "autocomplete?action=complete&id=" +
                  escape(completeField.value);
          var req = initRequest();
          req.onreadystatechange = function() {
              if (req.readyState == 4) {
                  if (req.status == 200) {
                      parseMessages(req.responseXML);
                  } else if (req.status == 204){
                      clearTable();
                  }
              }
          };
          req.open("GET", url, true);
          req.send(null);
      }
  }


The XMLHttpRequest object is not currently part of standard JavaScript (efforts are underway to standardize it), but is a de facto standard and is the heart of AJAX. This object is responsible for interacting over HTTP with a server-side component (in this case, a servlet).
* Template and Skin support through SMlite
* Flexible and modular API system (also implements ModelViewController model)
* Multiple APIs - you can develop command line applications with amodules3
* PHP5+ (using exceptions and other new features)
* Seamless AJAX support


Three parameters are specified when you create an XMLHttpRequest object: a URL, the HTTP method (GET or POST), and whether or not the interaction is asynchronous. In the XMLHttpRequest example, the parameters are:
===Ajax used in ASP.Net Framework===


* The URL autocomplete, and the text from the complete-field (an M character):
The ASP.NET MVC Framework simply provides its own set of JavaScript files and utilities to make AJAX calls occur in much the same way they occur in WebForms applications. In this article I’ll go through the various aspects of the AJAX API you can leverage in ASP.NET MVC applications. Compared to WebForms, ASP.NET MVC provides a smarter layer of code on top of the same ASP.NET runtime.  
                var url = "autocomplete?action=complete&id=" +
                        escape(completeField.value);
* GET, signifying the HTTP interactions uses the GET method, and true, signifying that the interaction is asynchronous:
                req.open("GET", url, true);


A callback function needs to be set when you use asynchronous calls. This callback function is called asynchronously at specific points during HTTP interaction when the readyState property on the XMLHttpRequest changes. In the example the callback function is processRequest(). It's set as the XMLHttpRequest.onreadystatechange property to a function. Notice the call to the parseMessages function when the readState is "4". The XMLHttpRequest.readyState of "4" signifies the successful completion of the HTTP interaction.
The ASP.NET MVC Framework abstracts some of the steps in the procedure just described. For example, the URL is not necessarily bound to a server file. The URL is simply the representation of the requested resource. This means that a module intercepts the request, parses the URL, and forwards the request to a controller component. The role that the page class plays in WebForms is split between controller and view in ASP.NET MVC.The role that the page class plays in WebForms is split between controller and view in ASP.NET MVC. ASP.NET MVC works on top of the same runtime environment and same set of global rules as Webforms. AJAX is used in ASP.NET MVC similar to Webforms.


The HTTP interaction begins when XMLHttpRequest.send() is called. If the interaction is asynchronous, the browser continues to process events in the page.
AJAX is about making an out-of-band request to the web server via XMLHttpRequest. A piece of JavaScript code prepares the call, runs it asynchronously, then processes the response in a callback function. The callback function is responsible for updating the user interface with downloaded data using the DOM services. To make developers’ lives a bit easier, Microsoft provided in ASP.NET AJAX such facilities as the partial rendering API and JavaScript proxy for Web services. The package that contains the ASP.NET MVC install also includes the jQuery library, so you can use this library (or any other similar libraries) to prepare your direct AJAX calls directed at URLs of choice. This is the most natural way of having AJAX in ASP.NET MVC applications. However, Microsoft provides facilities to make AJAX happen in a way that is similar to partial rendering in WebForms.  


On the Server
The methods to use AJAX in ASP.NET is through
*[http://www.nikhilk.net/Ajax-MVC.aspx Direct Scripting]
*[http://www.nikhilk.net/Ajax-MVC.aspx ActionLink AJAX Helper]
*[http://www.nikhilk.net/Ajax-MVC.aspx Partial Rendering in ASP.NET MVC ]


The XMLHttpRequest makes an HTTP GET request to the URL autocomplete, which is mapped to a servlet called AutoComplete. The doGet() method of the AutoComplete servlet is called. Here is what the doGet() method looks like:
==References==
  public void doGet(HttpServletRequest request,
          HttpServletResponse response)
        throws IOException, ServletException {
      ...
      String targetId = request.getParameter("id");
      if (targetId != null) targetId = targetId.trim().toLowerCase();
      Iterator it = employees.keySet().iterator();
      while (it.hasNext()) {
          EmployeeBean e = (EmployeeBean)employees.get(
                  (String)it.next());
          if ((targetId != null) &&
              (e.getFirstName().toLowerCase ().startsWith(targetId) ||
              e.getLastName().toLowerCase().startsWith(targetId))
              && !targetId.equals("")) {
              sb.append("<employee>");
              sb.append("<id>" + e.getId() + "</id>");
              sb.append("<firstName>" + e.getFirstName() +
                      "</firstName>");
              sb.append("<lastName>" + e.getLastName() +
                      "</lastName>");
              sb.append("</employee>");
              namesAdded = true;
          }
      }
      if (namesAdded) {
          response.setContentType("text/xml");
          response.setHeader("Cache-Control", "no-cache");
          response.getWriter().write("<employees>" +
                  sb.toString() + "</employees>");
      } else {
          response.setStatus(HttpServletResponse.SC_NO_CONTENT);
      }
    }


As you can see in this servlet, there is nothing really new you need to learn to write server-side code for AJAX processing. The response content type needs to be set to text/xml for cases where you want to exchange XML documents. With AJAX, you can also exchange plain text or even snippets of JavaScript which may be evaluated or executed by the callback function on the client. Note too that some browsers might cache the results, and so it might be necessary to set the Cache-Control HTTP header to no-cache. In this example, the servlet generates an XML document that contains all employees with a first or last name beginning with the character M. Here is an example of an XML document that is returned to the XMLHttpRequest object that made the call:
[http://en.wikipedia.org/wiki/Model–view–controller MVC structure]


<employees> <employee> <id>3</id> <firstName>George</firstName> <lastName>Murphy</lastName> </employee> <employee> <id>2</id> 
[http://www.netbeans.org/kb/60/ruby/ajax.html AJAX in Ruby]
<firstName>Greg</firstName> <lastName>Murphy</lastName> </employee> <employee> <id>11</id><firstName>Cindy</firstName>
<lastName>Murphy</lastName> </employee> <employee> <id>4</id> <firstName>George</firstName> <lastName>Murray</lastName> 
</employee>  <employee> <id>1</id> <firstName>Greg</firstName> <lastName>Murray</lastName> </employee> </employees>


Returning to the Client
[http://www.ajaxf1.com/tutorial/ajax-php.html AJAX in PHP]


When the XMLHttpRequest object that made the initial call receives the response, it calls the parseMessages() function (see the initialization of the XMLHttpRequest earlier in this example for more details). Here is what the parseMessages() function looks like:
[http://www.jaxtut.com/ AJAX in JAVA]
  function parseMessages(responseXML) {
      clearTable();
          var employees = responseXML.getElementsByTagName(
                  "employees")[0];
      if (employees.childNodes.length > 0) {
          completeTable.setAttribute("bordercolor", "black");
          completeTable.setAttribute("border", "1");
      } else {
          clearTable();
      }
   
      for (loop = 0; loop < employees.childNodes.length; loop++) {
          var employee = employees.childNodes[loop];
          var firstName = employee.getElementsByTagName(
                  "firstName")[0];
          var lastName = employee.getElementsByTagName(
                  "lastName")[0];
          var employeeId = employee.getElementsByTagName(
                  "id")[0];
          appendEmployee(
                  firstName.childNodes[0].nodeValue,
                  lastName.childNodes[0].nodeValue,
                  employeeId.childNodes[0].nodeValue);
      }
  }


The parseMessages() function receives as a parameter an object representation of the XML document returned by the AutoComplete servlet. The function programmatically traverses the XML document, and then uses the results to update the contents of the HTML page. This is done by injecting into a element whose id is "menu-popup" the HTML source for the names in the XML document:
[http://ajax.net-tutorials.com AJAX in ASP.NET]
As the user enters more characters, the list shortens. The user can then click on one of the names.


[http://ajaxpatterns.org/Java_Ajax_Frameworks Java Ajax Frameworks ]


== Conclusion ==
[http://ajaxpatterns.org/PHP_Ajax_Frameworks PHP AJAX Frameworks]

Latest revision as of 01:16, 11 October 2009

AJAX implementation in Ruby , Java , PHP and ASP.NET MVC Framework

1.Ajax

AJAX is an efficient way for a web application to handle user interactions with a web page -- a way that reduces the need to do a page refresh or full page reload for every user interaction. This enables rich behavior (similar to that of a desktop application or plugin-based web application) using a browser. AJAX interactions are handled asynchronously in the background. As this happens, a user can continue working with the page. AJAX Interactions are initiated by the JavaScript in the web page. When the AJAX interaction is complete, JavaScript updates the HTML source of the page. The changes are made immediately without requiring a page refresh. AJAX interactions can be used to do things such as validate form entries (while the user is entering them) using server-side logic, retrieve detailed data from the server, dynamically update data on a page, and submit partial forms from the page.

What is particularly attractive about this is that AJAX applications do not require a separate plug-in, and are platform and browser-neutral. That said, AJAX is not supported as well in older browsers. Care needs to be taken in writing client-side script that accounts for the differences between browsers.

2.Model–View–Controller (MVC)

Model–View–Controller (MVC) is an architectural pattern used in software engineering. The pattern isolates business logic from input and presentation, permitting independent development, testing and maintenance of each.

Models the domain-specific representation of the data on which the application operates. Domain logic adds meaning to raw data (for example, calculating whether today is the user's birthday, or the totals, taxes, and shipping charges for shopping cart items). When a model changes its state, it notifies its associated views so they can refresh.Many applications use a persistent storage mechanism (such as a database) to store data. MVC does not specifically mention the data access layer because it is understood to be underneath or encapsulated by the model. Models are not data access objects although in very simple apps, with little domain logic, there is no real distinction to be made. Also, the ActiveRecord is an accepted design pattern which merges domain logic and data access code - a model which knows how to persist itself.ViewRenders the model into a form suitable for interaction, typically a user interface element. Multiple views can exist for a single model for different purposes.ControllerReceives input and initiates a response by making calls on model objects.

  • A model is an object representing data or even activity, e.g. a database table or even some plant-floor production-machine process.
  • A view is some form of visualization of the state of the model.
  • A controller offers facilities to change the state of the model.

An MVC application may be a collection of model/view/controller triplets, each responsible for a different UI element.

MVC is often seen in web applications where the view is the HTML or XHTML generated by the app. The controller receives GET or POST input and decides what to do with it, handing over to domain objects (ie the model) which contain the business rules and know how to carry out specific tasks such as processing a new subscription.

Implentaion of Ajax in MVC framework

Ajax used in Ruby Framework

Basically used in View and controller How to Use Ajax in Our Web Application

The hard way to use Ajax in your web app is to write your own custom JavaScript that directly uses the XMLHttpRequest object's API. By doing this, we have to deal with the idiosyncrasies of each browser.

An easier way is to use one of several JavaScript libraries that provide higher-level Ajax services and hide the differences between browsers. Libraries such as DWR, Prototype, Sajax, and Ajax.NET are all good choices.

The easiest way of all is to use the built-in Ajax facilities of Ruby on Rails. In fact, Rails makes Ajax so easy that for typical cases it's no harder to use Ajax than it is not to! How Rails Implements Ajax

Rails has a simple, consistent model for how it implements Ajax operations.

Once the browser has rendered and displayed the initial web page, different user actions cause it to display a new web page (like any traditional web app) or trigger an Ajax operation:

  • A trigger action occurs. This could be the user clicking on a button or link, the user making changes to the data on a form or in a field, or just a periodic trigger (based on a timer).
  • Data associated with the trigger (a field or an entire form) is sent asynchronously to an action handler on the server via XMLHttpRequest.
  • The server-side action handler takes some action (that's why it is an action handler) based on the data, and returns an HTML fragment as its response.
  • The client-side JavaScript (created automatically by Rails) receives the HTML fragment and uses it to update a specified part of the current page's HTML, often the content of a
    tag.


Steps to implement Ajax in Ruby:

a. Using a link_to_remote tag in the HTML

     <%= link_to_remote( "Register",
                        :update => "new_user",
                        :url =>{ :action => "allusers" }) %>

This tag tells that the name of the link is "Register", it will render the new response inside div named as "new_user" and it will call "allusers" action from controller.

b. After this allusers action will render in a partial template like this:

       render :parti => "allusers"

c. This call will go to a "_allusers" file where response will be populated and result will come inside div tag "new_user".


Ajax used in Java Framework

In the Java Frame work the MVC performs the follwoing functions:

The view registers as a listener on the model. Any changes to the underlying data of the model immediately result in a broadcast change notification, which the view receives. This is an example of the push model described earlier. Note that the model is not aware of the view or the controller -- it simply broadcasts change notifications to all interested listeners. The controller is bound to the view. This typically means that any user actions that are performed on the view will invoke a registered listener method in the controller class. The controller is given a reference to the underlying model.

Once a user interacts with the view, the following actions occur: The view recognizes that a GUI action -- for example, pushing a button or dragging a scroll bar -- has occurred, using a listener method that is registered to be called when such an action occurs. The view calls the appropriate method on the controller. The controller accesses the model, possibly updating it in a way appropriate to the user's action. If the model has been altered, it notifies interested listeners, such as the view, of the change. In some architectures, the controller may also be responsible for updating the view. This is common in Java technology-based enterprise applications. Implementing autocomplete in a search field is something that can be performed using AJAX. To do it, we need to provide code on the client and on the server.

There are three Java Ajax Framework based on MVC architecture.

  • AjaxAnywhere turns any set of existing JSP/JSF/Struts/Spring/etc.. components into AJAX-aware components without a complexe JavaScript coding.

The features of AjaxAnywhere are: -Does not break existing server-side MVC architecture. -Less JavaScript to develop and to maintain. Absence of commonly accepted naming convention, formatting rules, patterns makes JavaScript code messier then Java/JSP. It is extremely difficult to debug and unit-test it in multi-browser environment. Get rid of all those complexities by using AjaxAnywhere. -Easy to integrate. AjaxAnywhere does not require changing the underlying application code. -Graceful degradation. Switch whenever you need between AJAX and traditional (refresh-all-page) behaviour of your web application. Your application can also support both behaviors.

  • Struts is a MVC library that (since version 2) includes complex AJAX-tags

AJAX is a JavaScript can make a HTTP request and update portions of a page directly, without going through a conventional POST or GET and refreshing the entire page. Better yet, a page can contain several JavaScripts making simultaneous (asynchronous) requests.The key point is that when a script makes an "Ajax request" (XHR), the server doesn't know it came from a script, and handles it like any other request. One reason Ajax is so successful is that it works just fine with existing server technologies, including Struts.

It's not the Ajax request that is different, but the Ajax response. Instead of returning an entire page for the browser to display (or redisplay), an Ajax response will just return a portion of a page. The response can take the form of XML, or HTML, or plain text, another script, or whatever else the calling script may want.

Both Struts 1 and Struts 2 can return any type of response. We are not limited to forwarding to a server page. In Struts 1, you can just do something like:

response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("Hello World!  This is an AJAX response from a Struts Action.");
out.flush();
return null;

In Struts 2, we can do the same thing with a Stream result.

package actions;
import java.io.InputStream;
import java.io.StringBufferInputStream;
import com.opensymphony.xwork2.ActionSupport;
public class TextResult extends ActionSupport  {
    private InputStream inputStream;
    public InputStream getInputStream() {
        return inputStream;
    }
    public String execute() throws Exception {
        inputStream = new StringBufferInputStream("Hello World! This is a text string response from a Struts 2 Action.");
        return SUCCESS;
    }
}

Struts 2 Configuring the TextResult Action

<action name="text-result" class="actions.TextResult">
    <result type="stream">
        <param name="contentType">text/html</param>
        <param name="inputName">inputStream</param>
    </result>
</action>
  • IFW2 An open source business-applications oriented Ajax framework with support for JPA/EJB3

Here the approach to Ajax is quite different from other solutions , the system is able to track, on the server side, changes to the page displayed on the browser and, through a small javascript runtime, to refresh only changed parts . It is completely transparent to the programmer which has to deal only with a new jsp tag library. This is the view side of our MVC model, but work has been done also on the controller and model side. The controller side is based around the concept of Flow which lets the programmer design the interaction with the user as finite state-machines. Each flow can be in turn nested in another flow and became a state of it (sub-flow), used in modal interaction with the user or as a component of another flow (the main difference with a sub-flow is that a component is active concurrently with other components and can interact with them in a way similar to portlets).

Ajax used in PHP Framework

Ajax in PHP has the following flow

  • 1. you have an HTML page, styled with CSS
  • 2. you click on something
  • 3. JS sends request to the server (to a PHP script)
  • 4. JS updates the original HTML page

The MVC Pattern : When implemeting Ajax in PHP the MVC patter develops as follows

  • Model:It contains the PHP script and the logic , it interacts with the database .
  • View:It contains the CSS style sheets , HTML ,DOM and the JavaScript that updates the HTML.
  • Controller: It has the PHP script on the server side and the JavaScript on the Client side.

MVC implementation requires a well working Object model from the programming language, and because PHP4 was missing those capabilities no strong libraries emerged.

There are various frameworks that use PHP-AJAX in them , one of them that uses the MVC Pattern is The Akelos PHP Framework It is a web application development platform based on the MVC (Model View Controller) design pattern.

AModules3 is a flexible framework for developing applications using Object Oriented Programming. It's like "Rails" for PHP. It utilizes new features only found in PHP5 and shapes your application into a very efficient code. The following features are also included:

  • Template and Skin support through SMlite
  • Flexible and modular API system (also implements ModelViewController model)
  • Multiple APIs - you can develop command line applications with amodules3
  • PHP5+ (using exceptions and other new features)
  • Seamless AJAX support

Ajax used in ASP.Net Framework

The ASP.NET MVC Framework simply provides its own set of JavaScript files and utilities to make AJAX calls occur in much the same way they occur in WebForms applications. In this article I’ll go through the various aspects of the AJAX API you can leverage in ASP.NET MVC applications. Compared to WebForms, ASP.NET MVC provides a smarter layer of code on top of the same ASP.NET runtime.

The ASP.NET MVC Framework abstracts some of the steps in the procedure just described. For example, the URL is not necessarily bound to a server file. The URL is simply the representation of the requested resource. This means that a module intercepts the request, parses the URL, and forwards the request to a controller component. The role that the page class plays in WebForms is split between controller and view in ASP.NET MVC.The role that the page class plays in WebForms is split between controller and view in ASP.NET MVC. ASP.NET MVC works on top of the same runtime environment and same set of global rules as Webforms. AJAX is used in ASP.NET MVC similar to Webforms.

AJAX is about making an out-of-band request to the web server via XMLHttpRequest. A piece of JavaScript code prepares the call, runs it asynchronously, then processes the response in a callback function. The callback function is responsible for updating the user interface with downloaded data using the DOM services. To make developers’ lives a bit easier, Microsoft provided in ASP.NET AJAX such facilities as the partial rendering API and JavaScript proxy for Web services. The package that contains the ASP.NET MVC install also includes the jQuery library, so you can use this library (or any other similar libraries) to prepare your direct AJAX calls directed at URLs of choice. This is the most natural way of having AJAX in ASP.NET MVC applications. However, Microsoft provides facilities to make AJAX happen in a way that is similar to partial rendering in WebForms.

The methods to use AJAX in ASP.NET is through

References

MVC structure

AJAX in Ruby

AJAX in PHP

AJAX in JAVA

AJAX in ASP.NET

Java Ajax Frameworks

PHP AJAX Frameworks