Jquery ajax call misses servlet

I am trying to make a simple ajax call. No matter what I do, it always executes a block of errors. I have sysout in doPost that never hits. Someone please tell me what I'm doing wrong. Here is my code.

Javascript ----

$.ajax({ url: "GetBulletAjax", dataType: 'json', success: function(data) { alert("success"); }, error: function(jqXHR, textStatus, errorThrown) { alert(jqXHR+" - "+textStatus+" - "+errorThrown); } }); 

Java ----

 public class GetBulletAjax extends HttpServlet { private static final long serialVersionUID = 1L; public GetBulletAjax() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("made it to servlet"); PrintWriter out = response.getWriter(); User user = (User) request.getSession().getAttribute("user"); int userId = user.getId(); List<Bullet> bullets; BulletDAO bulletdao = new BulletDAOImpl(); try { bullets = bulletdao.findBulletsByUser(userId); Gson gson = new Gson(); String json = gson.toJson(bullets); System.out.println(json); out.println(json); out.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } 

web.xml ----

 <servlet> <servlet-name>GetBulletAjax</servlet-name> <servlet-class>bulletAjax.GetBulletAjax</servlet-class> </servlet> <servlet-mapping> <servlet-name>GetBulletAjax</servlet-name> <url-pattern>/GetBulletAjax</url-pattern> </servlet-mapping> 
+4
source share
2 answers

What is the url for your customer? Your URL will be relative, so if your page URL is <server>/foo/bar.html , your ajax request will be sent to <server>/foo/GetBulletAjax . But your servlet definition is <server>/GetBulletAjax .

Change your url in your ajax request to /GetBulletAjax . You need a leading slash to tell the browser that the resource is outside the root of the site.

+4
source

in jquery documentation

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

type (default: 'GET') Type: String The request type ("POST" or "GET") by default is "GET". Note. Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers.

it seems like you missed the type attribute, which should be a POST. the default is GET, as indicated in the documentation. You do not have doGet in your servlet to support this.

 $.ajax({ url: "GetBulletAjax", dataType: 'json', type:POST, success: function(data) { alert("success"); }, error: function(jqXHR, textStatus, errorThrown) { alert(jqXHR+" - "+textStatus+" - "+errorThrown); } }); 
+1
source

All Articles