Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling servlet output in AJAX

My problem: I am sending a request to a servlet from an AJAX function in a JSP.

The servlet processes the data and returns a ArrayList.

My question is how to handle the ArrayList inside AJAX, and display it as a table in same JSP.

The code is

function ajaxFunction ( ) {

 // var url= codeid.options[codeid.selectedIndex].text;
 url="mstParts?caseNo=9&cdid=QCYST0020E1";
 //  alert(cid);
   var httpRequest;
    if (window.XMLHttpRequest) {
        httpRequest = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
    }
  if (httpRequest == null){ alert('null');}

alert(url);
    httpRequest.open("GET", url, true );

   httpRequest.onreadystatechange = function() { alertContents(httpRequest); };
  //httpRequest.setRequestHeader('Content-Type', 'text/plain');
    httpRequest.send(null);

  alert('t1');
}

function alertContents(httpRequest) {
    if (httpRequest.readyState == 4) {
        var cType =httpRequest.getResponseHeader("Content-Type");
        //document.write(httpRequest.toString());
      // alert(cType);
       // var xmlDoc=httpRequest.responseText;
        //document.write(xmlDoc.toString());
      //  if (xmlDoc == null) {alert('null returned');}
        if (!httpRequest.status == 200) {
            alert('Request error. Http code: ' + httpRequest.status);
        }
        else
            {
                var profileXML = eval(<%=request.getAttribute("data")%>);
                if ( profileXML != null){ alert('null'); }//else { alert(profileXML(0)); }
               // httpRequest.getAttribute("data");


            }
    }
}
like image 804
sansknwoledge Avatar asked Dec 14 '09 12:12

sansknwoledge


People also ask

How can we call a Servlet using AJAX?

You can in the servlet distinguish between normal requests and Ajax requests as below: @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String foo = request. getParameter("foo"); String bar = request.

What is the use of AJAX () method?

The ajax() method is used to perform an AJAX (asynchronous HTTP) request. All jQuery AJAX methods use the ajax() method. This method is mostly used for requests where the other methods cannot be used.

How AJAX get data from server?

jQuery $.get() Method The $.get() method requests data from the server with an HTTP GET request. Syntax: $.get(URL,callback); The required URL parameter specifies the URL you wish to request.

Can AJAX send data to server?

AJAX stands for Asynchronous JavaScript And XML. In a nutshell, it is the use of the XMLHttpRequest object to communicate with servers. It can send and receive information in various formats, including JSON, XML, HTML, and text files.


1 Answers

var profileXML = eval(<%=request.getAttribute("data")%>);

Firstly, I would recommend you to learn about the wall between JavaScript and JSP. JS runs entirely at the client side and JSP/Java runs entirely at the server side. They certainly doesn't run in sync as you seem to think. To learn more, read this blog article.

function ajaxFunction ( )

Secondly, I would recommend you to use an existing, robust, thoroughly-developed, well-maintained JavaScript library with Ajaxical capabilities such as jQuery instead of reinventing the AJAX wheel and fighting/struggling/worrying with browser specific issues/troubles/behaviors/pains. I would also recommend to use JSON as data transfer format between Java Servlet at server and JavaScript at client. In the Java side you can use the great Gson library for this.

Here's a kickoff example with all of the mentioned techniques. Let's start with a Servlet and a JavaBean:

public class JsonServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Data> list = dataDAO.list();
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(new Gson().toJson(list));
    }
}

public class Data {
    private Long id;
    private String name;
    private Integer value;
    // Add/generate getters/setters.
}

The JsonServlet (you may name it whatever you want, this is just a basic example) should be mapped in web.xml on a known url-pattern, let's use /json in this example. The class Data just represents one row of your HTML table (and the database table).

Now, here's how you can load a table with help of jQuery.getJSON:

$.getJSON("http://example.com/json", function(list) {
    var table = $('#tableid');
    $.each(list, function(index, data) {
        $('<tr>').appendTo(table)
            .append($('<td>').text(data.id))
            .append($('<td>').text(data.name))
            .append($('<td>').text(data.value));
    });
});

The tableid of course denotes the idof the <table> element in question.

That should be it. After all it's fairly simple, believe me. Good luck.

like image 82
BalusC Avatar answered Sep 18 '22 12:09

BalusC