4

I'm working on a map creation web app using javascript and JSP's. At some point I want my users to be able to save the map they've created to my db, but I have to check whether or not the name of the map already exists. I need do so without leaving the page itself or I'll lose about the map stored in that JSP.

So the question is: How can I get a response from my server without having to change page/url?

cweiske
  • 30,033
  • 14
  • 133
  • 194
OrangeCactus
  • 111
  • 1
  • 9

2 Answers2

5

Just to expand on Suresh's answer. (Can't comment yet)

On your jsp you'll add a script, something like

<script>
  $(document).ready(function(){
     $.ajax({
      url: "/YOUR_DOMAIN/SERVLET",
      type: "POST",
      data : {json: "hello" }, //in servlet use request.getParameters("json")
      dataType : 'json',
      success: function(data) {}, //data holds {success:true} - see below
      error: errorFunction
     }); 
  })
</script>

You'll want to look into a parser (http://www.json.org/java) if you're sending/receiving json from the servlet.

You can return data from the servlet like this.

response.setContentType("text/plain"); 
response.setCharacterEncoding("UTF-8");
response.getWriter().print("{success: true}");
brdu
  • 284
  • 1
  • 3
  • 17
  • 2
    Good +1.That is all you need. Note: Jquery is getting used here. Make sure that you are adding library files of jquery. – Suresh Atta Jan 10 '14 at 11:07
  • 1
    the literal string you're feeding print should be "{\"success\": true}" otherwise it will throw a parse error instead of triggering success as described here http://stackoverflow.com/a/15699216/2995881 – OrangeCactus Jan 13 '14 at 14:41
3

So the question is: How can I get a response from my server without having to change page/url?

This is the perfect candidate for using Asynchronous call AKA Ajax.

Learn AJAX.

http://api.jquery.com/jquery.ajax/

Note:

Keep in mind that do not call jsp and write a servlet here for Ajax. Jsp's are not intended to serve Ajax requests.

How to use Servlets and Ajax?

Community
  • 1
  • 1
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307