raajaag
raajaag

Reputation: 175

receive multiple responses in javascript with one request

How can I receive multiple responses from a server using javascript.

I have a requirement where a request is posted one time with the data and number of iterations and at server side the request is processed for the number of iterations. On completion of each iteration the server sends back the response. So for one request and 10 iterations my java script need to receive the 10 responses and show it on the web page. Is there any way that I can handle this using javascript. I cannot use any other technology.

Right now I am using the following way

    function showResponse(){
    xmlHttp = GetXmlHttpObject();
    var dataString = document.getElementById("request-parameters").value;
    var iterations = document.getElementById("iterations").value;
    if(xmlHttp==null){
        alert("your browser does not support AJAX!");
    }
    var url = "http://localhost:8080/servlet/requestServlet";

    xmlHttp.onreadystatechange=stateChanged;
    xmlHttp.open("POST",url,true);
    xmlHttp.send(dataString);
}

function GetXmlHttpObject(){
    var xmlHttp=null;
    try{
        //Firefox, Opera, Safari
        xmlHttp=new XMLHttpRequest();
    }catch(e){
        //IE
        try{
            xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
        }catch(e){
            xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    return xmlHttp;
}

function stateChanged(){
    if(xmlHttp.readyState==4){

        if(xmlHttp.status == 200){
             var resp = xmlHttp.responseText;
             var responseDiv = document.getElementById("response");
            responseDiv.innerHTML=responseDiv.innerHTML+resp1[1];

            }
    }
}

I cannot modify this approach. Is it possible to get it done with XmlHttp object.

Upvotes: 3

Views: 7245

Answers (2)

Alex Nikulin
Alex Nikulin

Reputation: 8689

1) HTTP Try request once to one controller, and then get answer from other controller, you can do this with jQuery or with native XmlHttpRequest (it is not one request).

 $.get("server/controllerJob",{data:"data"});
 var askInterval = window.setInterval(function(){
         $.get("server/askAnswerFromJob",{data:"data"}).done(function( data ) {
          if(data.complete){
                /** do staff**/
               window.clearInterval(askInterval);
          }else{
             /** do staff**/
          }
      });
    },200);

2) webSocket Or try to find something about WebSocket webSocket documentation, it is techonolgy with one connection with multiple request and response (full-duplex connection stream).

Also you need other server controller realization and see websocket supported browsers

Notice the ws:. This is the new URL schema for WebSocket connections. There is also wss: for secure WebSocket connection the same way https: is used for secure HTTP connections

I'm only just noticing that the "examples" web app that comes with Tomcat 7 contains 4 complete examples of how to use WebSocket (for java developers)

var connection = new WebSocket('ws://server/yourService',['soap','xmpp']);  

    connection.onopen = function () {
      connection.send('ask'); // Send the message to server
    };

     //Each time on new messages from server, this callbacks will be executed (depends on result)

    // Log errors from server
    connection.onerror = function (error) {
      console.log('WebSocket Error ' + error);
    };

    // Get messages from the server
    connection.onmessage = function (e) {
      console.log('Answer: ' + e.data);
    };

Upvotes: 1

W van Rij
W van Rij

Reputation: 536

With just 'basic javascript' you cannot do this.

It just works like this: Client sends request, servers returns 'something'. The server cannot simply keep sending data back to this client for multiple reasons. A: There is not a 'link' aka connection between both party's except for the first 'call' of a request, but the client just waits for the response. B: The script does not expect an other answer back.

What you need is a websocket for example. This way the client can listen to the server and actually process data send from the server to the client.

So in short:

Javascript works always like this:

Client -> Server | and the server respond back

For a socket you can have:

Client -> Server Server -> Client

You can use some sort of 'javascript' even tho its a different technology.. like NodeJS.

The other way is to make a loop. Rather than posting a dataset with an amount of iterations, just iterate it in JS and for each iteration send it to the server to actually 'perform' on your data.

Upvotes: 1

Related Questions