Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get data from my Server to my JSP using javascript?

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?

like image 945
OrangeCactus Avatar asked Feb 14 '23 03:02

OrangeCactus


2 Answers

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}");
like image 50
brdu Avatar answered Feb 17 '23 02:02

brdu


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?

like image 42
Suresh Atta Avatar answered Feb 17 '23 03:02

Suresh Atta