3

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.

Jamiec
  • 133,658
  • 13
  • 134
  • 193
raajaag
  • 175
  • 4
  • 18
  • what's your server-side technology? for .NET what you're after is [SignalR](http://signalr.net/) – Jamiec Jul 24 '15 at 11:23
  • http://stackoverflow.com/questions/13749156/ajax-heartbeat-using-setinterval-preventing-multiple-calls-at-the-same-time – Silviu Burcea Jul 24 '15 at 11:24
  • @Jamiec I am using java servlets – raajaag Jul 28 '15 at 11:08
  • I have tagged your question appropriately - it will help you get better answers because people who know java and its associated libraries/frameworks better will be drawn to this question. – Jamiec Jul 28 '15 at 11:11

2 Answers2

1

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.

W van Rij
  • 536
  • 2
  • 16
  • 2
    This is _incorrect_. The websocket API is part of the standard javascript library, so you can do this using Javascript. It's true that Websockets should also be supported and implemented by the server (NodeJS is just _one_ option for websocket handling)... But **it IS possible**. – Myst Jul 28 '15 at 17:18
1

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);
    };
Alex Nikulin
  • 8,194
  • 4
  • 35
  • 37
  • Thanks for the reply. As the ajax call is already implemented with XmlHttpRequest I cannot use jquery or some other thing. Can you please guide me how to achieve through XmlHttpRequest. I edited my question and added the ajax call. At server side I am using java servlets – raajaag Jul 28 '15 at 11:16
  • You already done the function that send data to server and recive response.Create more common function like this "sendRequest(url,data,callback)" and use this with interval. – Alex Nikulin Jul 28 '15 at 11:26
  • I cannot send the data again and again. So I cannot use interval (timer) to send the data. I need to send the data once with number of iterations. I tried web socket code you have given but I am getting "Firefox can't establish a connection to the server at ws://localhost:8080/servlet/requestServlet" I tried to print the error but I am getting "[object Event]" – raajaag Jul 28 '15 at 12:29
  • See, is this helpful for you http://www.coderanch.com/t/633446/Tomcat/Tomcat-creating-connection-web-socket – Alex Nikulin Jul 28 '15 at 12:43
  • for print objects in console (js) - use console.dir(whatEverYouWant) – Alex Nikulin Jul 28 '15 at 12:46
  • I'm only just noticing that the "examples" web app that comes with Tomcat 7 contains 4 complete examples of how to use WebSocket – Alex Nikulin Jul 28 '15 at 12:50