Search code examples
ajaxdatabaseliferayliferay-6

Extract data from database using ajax in Liferay


I am using liferay framwork for developing an application. I have a dropdown box whose values are pulled from the database. What i want to do is whenever a user selects any Person from the drop down menu the information about that Person should be extracted from the database just for viewing. How should this be done? Should I use ajax or any other stuff? And how should this be done? I do not know how to start:

EDITED: This is how I have made a call from jsp. I am not sure if it is correct approach Call from jsp:

 <!-- Ajax script to pull Employee data from the database -->
<script>
function showEmployeeInfo(empName)
{
    var xmlhttp;    
    if (str=="")
    {
        document.getElementById("empDetails").innerHTML="";
         return;
     }
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
         xmlhttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
          xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            document.getElementById("empDetails").innerHTML=xmlhttp.responseText;
        }
    }

    xmlhttp.open("GET","getEmp.java?q="+empName,true);
    xmlhttp.send();
}

Please note that xmlhttp.open("GET","getEmp.java?q="+empName,true); is incorrect and I didnt know how to put it.


Solution

  • You should always use a javascript library to perform ajax, why? Because the library would take care of the boiler-plate code and also would be cross-browser compliant.

    So with Liferay 6.x you can use as it is the default Library or else you can use which is the most popular and easy to use. It is just that you would need to include jQuery in your portlet explicitly where as with Alloy UI you can just directly use it.

    There are other libraries but I prefer these as I am comfortable with these two :-)

    I would give an example by using Alloy UI (a crash course):

    1. Lets understand the simple steps and flow first:
      1. Render JSP
      2. Have a resourceURL created <portlet:resourceURL var="ajaxCallResourceURL" /> in the JSP
      3. Call javascript function by generating an event through any element like onChange, onClick etc
      4. Use Alloy io.request module to call the serveResource method through the reourceURL
      5. The serveResource method returns either HTML text or JSON list to fill in the drop-down
      6. In the success method of the io.request script do some javascript magic to fill in the drop-down
    2. Now let the code flow:

      JSP

      <%-- Create the Resource URL --%>
      <portlet:resourceURL var="fetchWordsResourceURL" />
      
      <aui:form method="post" name="fm" >
      
          <%-- Calling the javascript function fetchWords() which will make the ajax call --%>
          <aui:select name="sourceSelect" id="sourceSelect" label="alphabets" onChange='<%= renderResponse.getNamespace() + "fetchWords();"%>'>
              <aui:option label="--" value="--" />
              <aui:option label="A" value="a" />
              <aui:option label="B" value="b" />
              <aui:option label="C" value="c" />
          </aui:select>
      
          <%-- The ajax response would populate this drop-down --%>
          <aui:select name="targetSelect" id="targetSelect" label="Words with Alphabets">
          </aui:select>
      
      </aui:form>
      
      <aui:script>
      <%-- This is the javascript function which will be executed onChange of the value of sourceSelect --%>
      
          Liferay.provide(
              window,
              '<portlet:namespace />fetchWords',
              function() {
      
                  var A = AUI();
      
                  var fetchWordsURL = '<%= fetchWordsResourceURL.toString() %>';
      
                  // selecting the sourceSelect drop-down to get the current value
                  var sourceElement = A.one("#<portlet:namespace />sourceSelect");
      
                  // selecting the targetSelect drop-down to populate values
                  var targetElement = A.one("#<portlet:namespace />targetSelect");
      
                  alert("Fetch word for alphabet = " + sourceElement.val());
      
                  A.io.request (
                      // the resource URL to fetch words
                      fetchWordsURL, {
                      data: {
                          // request parameters to be sent to the Server
                          <portlet:namespace />alphabet: sourceElement.val()
                      },
                      dataType: 'json',
                      on: {
                              failure: function() {
                                  // if there was some error at the server
                                  alert("Ajax failed!");
                              },
                              success: function(event, id, obj) {
      
                                  // JSON Data recieved from Server
      
                                  var wordsArray = this.get('responseData');
      
                                  // crude javascript magic to populate the drop-down
      
                                  //clear the content of select
                                  targetElement.html("");
      
                                  for (var j=0; j < wordsArray.length; j++) {
                                      // alert("Alphabet ==> " + wordsArray[j]);
      
                                      targetElement.append("<option value='" + wordsArray[j] + "'>" + wordsArray[j] + "</option>");
                                  }
                              }
                          }
                      }
                  ); 
              },
              ['aui-io']
          );
      </aui:script>
      

      Portlet class: serveResource method

      @Override
      public void serveResource(ResourceRequest resourceRequest,
          ResourceResponse resourceResponse)
          throws IOException, PortletException {
      
          String alphabet = ParamUtil.getString(resourceRequest, "alphabet");
      
          _log.info("Alphabet recieved from ajax request ==> " + alphabet);
      
          // build the JsonArray to be sent back
          JSONArray jsonArray = JSONFactoryUtil.createJSONArray();
      
          if("a".equals(alphabet)) {
      
              jsonArray.put("Apple");
              jsonArray.put("Ape");
              jsonArray.put("Ant");
          }
          else if("b".equals(alphabet)) {
      
              jsonArray.put("Banana");
              jsonArray.put("Ball");
              jsonArray.put("Bat");
      
          }
          else if("c".equals(alphabet)) {
      
              jsonArray.put("Code");
              jsonArray.put("Cat");
              jsonArray.put("Camera");
          }
      
          _log.info("Json Array populated ==> " + jsonArray.toString());
      
          // set the content Type
          resourceResponse.setContentType("text/javascript");
      
          // using printWrite to write to the response
          PrintWriter writer = resourceResponse.getWriter();
      
          writer.write(jsonArray.toString());
      }
      

    Thats it you are ready to code some highly ajaxed applications :-).