MartinOShea
MartinOShea

Reputation:

Problem with JSP servlet and Ajax

I have a JSP with a Javascript tree control and I want the user to be able to hide or show this tree at the touch of a button and for this change of state to be carried through to other pages visited, i.e. if on page A, the user hides the tree, then on page B, the tree should remain hidden and so on until the user decides to show the tree.

To do this, I'm using AJAX to set a session variable on the server which is checked when a page is loaded. Now this works fine when the page in question has no query string in its URL.

But with a page with a URL like:

http://localhost:8084/myApp/myAppPage?myAppParam=0

If I invoke the show/hide button, I get a Java NumberFormatException error because the query string is lost. But manually reloading the page after this shows the page with the tree updated.

The tree's HTML is built on the server and displayed in an HTML div on each page.

My understanding is that AJAX is meant to update only a part of the page and the page is written in this manner to only allow the contents of a div to be updated. But I can not work out why the query string is being lost.

I wonder if the AJAX is trying to force a full page reload?

I do know that the AJAX call is reaching the servlet correctly. But the servlet is not set to call another page.

Has anyone seen this before and do you know a workaround?

Upvotes: 2

Views: 1519

Answers (3)

BalusC
BalusC

Reputation: 1109695

The query string of the initial request URL won't be passed automagically whenever you fire an ajaxical request on the response of the initial request. You have to append it to the URL of the ajaxical request yourself. The query string of the initial request is available by window.location.search.

var ajaxurl = '/someservlet' + window.location.search;

Upvotes: 2

MartinOShea
MartinOShea

Reputation:

John

Thanks for your reply.

I have partially fixed things now and it was to do with triggering the Ajax from a form button which must also have been doing an implicit page refresh.

Martin O'Shea.

Upvotes: 0

John Topley
John Topley

Reputation: 115422

Without seeing the code involved it's difficult to speculate. Some things to consider:

  • How are you making the AJAX request i.e. are you using an established framework such as jQuery or Prototype, or have you rolled your own?
  • What code is behind the show/hide button?
  • How does your servlet respond to the request?

You can use Firebug to verify that your AJAX requests are correct and logging within your servlet to see what's going on (or use a debugger of course).

Upvotes: 0

Related Questions