Question

I am new to javascript and the whole front-end side of development.

Here is what I am using:

  • Java servlet running on Tomcat7
  • twitter-bootstrap for the layout/theme
  • Pubnub to keep track of how many times a form is submitted
  • Javascript/jquery to display this value on a webpage.

I have added the PUBNUB.subscribe callback which updates the value on the webpage just fine. However, when I first load the webpage, I don't know what value I should display.

Here is what I did to overcome this issue: I added a method to the servlet that, when passed in the correct parameter in a POST request, it will send out a pubnub message with the amount to be displayed which is working fine.

Next, I tried to call a POST request using jquery like this:

$.post("../servlets/theservlet",
        {
            update : "true"
        });

I tried placing that inside a $(window).load function but when I loaded the webpage, it did not do what I expected. I expected it to do the POST after everything was loaded, which would cause the pubnub message to be published from the servlet, which would activate the callback method in the PUBNUB.subscribe function. However, the value didn't change, it stayed as the placeholder that is hardcoded in the html.

Currently, I am now calling setTimeout("updateUses()", 1500); from within the $(window).load function. updateUses() is the exact same $.post call I showed earlier.

Now when I load the page, the placeholder value is there for a little bit (seems longer than 1.5ms) and then it is updated to the correct value. If I remove the setTimeout and just call updateUses() directly, then nothing happens again.

What do I need to change so that it loads the value instantly (or at least without a noticeable delay)?

Was it helpful?

Solution

If the page builder is JSP and what I have just read is correct then you should be able to do something like this:

RequestDispatcher rd=application.getRequestDispatcher("path/to/pubnub/servlet");
rd.include(request,response);

If you choose to stick with the ajax approach then the javascript should look something like this:

$(function(){
    $.post("path/to/pubnub/servlet", {update:"true"}, function(response){
        //do whatever is necessary with the response here, eg.
        //$("#myElementId").html(response);
    });
});

The $(function(){...}) wrapper ensures the code inside it is executed at the earliest opportunity after the DOM becomes ready. Hence no need for a timeout. jQuery is typically written inside such a wrapper.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top