CSC/ECE 517 Fall 2009/wiki2 2 AJAXandMVC

From Expertiza_Wiki
Revision as of 00:58, 10 October 2009 by Araj (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Introduction

What is MVC ?

Model–View–Controller (MVC) (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. 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.MVC helps to reduce the complexity in architectural design and to increase flexibility and reuse of code.Read more about MVC from wikipedia

Where does AJAX fit into in MVC ?

1. JAVA

2. PHP

PHP supports JSON encoding by default, this allows you to pass complex data types back and forth between PHP and Javascript fairly easily.Consider this simple example.[1]

To demonstrate the AJAX PHP connection we will create a very simple form with 2 input fields. In the first field you can type any text and we will send this text to our PHP script which will convert it to uppercase and sends it back to us.

CLIENT SIDE CODE

<script>
// Get the HTTP Object
function getHTTPObject(){
   if (window.ActiveXObject) 
       return new ActiveXObject("Microsoft.XMLHTTP");
   else if (window.XMLHttpRequest)//catches the response from the server 
       return new XMLHttpRequest();//this object is for AJAX PHP communication 
   else {
      alert("Your browser does not support AJAX.");
      return null;
   }
}

// Change the value of the outputText field
function setOutput(){
    if(httpObject.readyState == 4){
        document.getElementById('outputText').value = httpObject.responseText;
    }

}

// Implement business logic    
function doWork(){    
    httpObject = getHTTPObject();
    if (httpObject != null) {
        httpObject.open("GET", "upperCase.php?inputText="
                        +document.getElementById('inputText').value, true);
        httpObject.send(null); 
        httpObject.onreadystatechange = setOutput;
    }
}
</script>

  <form name="testForm">
     Input text: <input type="text"  onkeyup="doWork();" name="inputText" id="inputText" /> 
     Output text: <input type="text" name="outputText" id="outputText" />
  </form>

SERVER SIDE CODE

Server side functionality is very simple compared to the client side. In the PHP code we just need to check the $_GET super-global array. Afterwards convert it to uppercase and echo the result.

<?php
    if (isset($_GET['inputText'])) 
       echo strtoupper($_GET['inputText']);
?>


3. RAILS

Rails provide support for AJAX in the form of helper methods. There is no need to add Javascript code in the view templates. Instead, the helper methods create the Javascript code in the html page derived from the view templates. One of the ways this could be understood is through an example [2] of link_to_remote() method which can be used to get the latest time from a server and display it on a web page.Here is a sample view template.


SERVER SIDE CODE

<html>
  <head>
    <title>Ajax Demo</title>
    <%= javascript_include_tag "prototype" %>
  </head>
  <body>
    <h1>What time is it?</h1>
    <div id="time_div">
      I don't have the time, but
      <%= link_to_remote( "click here",
                         :update => "time_div",
                         :url =>{ :action => :say_when }) %>
      and I will look it up.
    </div>
  </body>
</html>

What this view does this is that it gives a link to display the current time. The current time would be fetched in the background without refreshing the browser. Now, there are two main helper methods to do this job. One of them is javascript_include_tag() that includes the Prototype JavaScript library. This is included with Rails package and is a basic requirement to make use of AJAX functionality. The other is link_to_remote() call that talks to the remote server when a request for current time is made. Here is a brief explanation of the parameters used in this method:

  1. click_here : this is the text for displaying the link
  2. time_div  : it is the id of the HTML DOM element that would have the current time content
  3. url  : refers to the server side action and it is say_when in this case

The role of the index action is to render the index.html file which displays the ‘before’ view. The controller is named demo and is coded as,

SERVER SIDE CODE

class DemoController < ApplicationController
  def index
  end

  def say_when
    render_text "<p>The time is <b>" + DateTime.now.to_s + "</b></p>"
  end
end

When “click here” is clicked on we would see the ‘after’ view which is shown above. What happens over here is that when a user clicks on “click me” an XMLHttpRequest is created by the browser and sent to the server where in the server invokes the say_when action and renders the HTML response fragment containing the current time. When the client side Javascript receives the response it replaces the contents of the div with an id of time_div.Besides the above example, there are other AJAX helper methods like the form method, i.e., form_remote_tag(). Here, is a prototype for it.

<%= form_remote_tag :url => { :action => 'create' },
  		     :update => ‘ajax_result’ %> 	
	<%= render :partial => ‘form’ %> 
	<%= submit_tag "Create" %>
<%= end_form_tag %>

<div id="ajax_result"></div>

Ajax in Ruby has immense potential in its application and can add to the efficiency as well as to the looks of a web template. In order to get a more in depth foot in Ajax on Rails , there is a very popular book “Ajax on Rails” by Scott Raymond and published by O’Reilly.