Saturday, April 17, 2010

Send Ajax Requests from JavaScript easily with Prototype framework

Did you have a need of setting up an JSP Java variable in a JSP file inside a JavaScript code. Generally, this is not possible as JavaScript works on client-side and JSP Java compilation happens server-side. i.e. When a user request a JSP file, first, the Java codes in it is compiled and generates pure HTML (and JavaScript) code. So, if you want to set a Java variable or any other thing involving Java in the client-side, you have to send a request to the server saying what you have to do.

As, you know when submitting a form with POST or GET, it sends a POST or GET request with the fields in that form. But, it loads another page which takes time and may not be the case you need.


With AJAX you can send a request to server very easily.Here, I'm telling you to send a AJAX request with the use of prototype framework. Prototype offers a Object Oriented with extensive Ajax support which aims to ease development of dynamic web applications. The framework offers various features and enhancements for JavaScript. Here, we are looking sending a AJAX request. You can learn more about this at http://www.prototypejs.org/learn/introduction-to-ajax
  • First download the prototype.js file from http://prototypejs.org/download
  • Then copy it to a suitable location and add this code in your HTML: (Make sure to set the correct path in src)
 <script type="text/javascript" src="/path/to/prototype.js"></script>  
 Then you can send a AJAX request by simply creating a new Ajax object and calling it's request method.
 new Ajax.Request('/some_url', { method:'post' }); 
      Here is an example code:

      new Ajax.Request('pathToJSPFile.jsp',
            {

                 method:'post',
                 parameters:{para1:"para1Text", para2:"para2Text"},
                 onSuccess: function(transport) {
                       var response = transport.responseText;  
                       alert("success "+response);
                  },
                  onFailure: function(transport) {
                       alert("fail");   
                  }
        });
  Just put above code in a method and call it when necessary. I think the code is self explainable.

    1 comment: