Isuru
Isuru

Reputation: 3958

Ajax request does not reach the servlet

I am trying to ajax call using jquery and jsp but I can't make it work.

<%@page import="in.isuru.twitter.Twits" %>
<%@page import="java.util.ArrayList" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <title>Twitter Sinhala</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
        <script src="script.js" type="text/javascript"></script>
    </head>
    <body>
        <form id="form" action="twitterv2" method="post">
            Enter Something
            <input id="term" type="text" name="term" />
            <input id="submit" type="submit" value="Show results" name="submit"/>
        </form>
        <p id="result"></p>
    </body>
</html>

This is the servlet.

package in.isuru.twitter;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.http.*;

import twitter4j.Query;
import twitter4j.QueryResult;
import twitter4j.Tweet;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;

@SuppressWarnings("serial")
public class TwitterV2Servlet extends HttpServlet {

    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setContentType("text/html");
        //Twits tweets = new Twits();
        Twitter twitter = new TwitterFactory().getInstance();
        //twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
        Query query = new Query("man");
        QueryResult result = null;
        try {
            result = twitter.search(query);
        } catch (TwitterException e) {
            e.printStackTrace();
        }
        for (Tweet tweet : result.getTweets()) {
            resp.getWriter().println(tweet.getFromUser() + ":" + tweet.getText() + "  <br/>");
        }
    }

}

This is script.js

$(document).ready(function() {
    $('#form').submit(function() {
        var number = $('#term').val();

        $.ajax({
            type:       "post",
            url:        "twitterv2",
            data:       "term=" + term,
            success:    function(msg) {
                $('#result').hide();
                $("#result").html("<h3>" + msg + "</h3>").fadeIn("slow");
            }
        });

        return false;
    });
});

This is web.xml

<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
    <servlet>
        <servlet-name>TwitterV2</servlet-name>
        <servlet-class>in.isuru.twitter.TwitterV2Servlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>TwitterV2</servlet-name>
        <url-pattern>/twitterv2</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
</web-app>

I cannot make it work. When I go to the servlet page and give argument like http://localhost:8888/twitterv2?term=people it shows twitter posts. So there is no errors in the servlet, I think the problem is in script.js. But I can't find an error.

Upvotes: 0

Views: 2575

Answers (2)

BalusC
BalusC

Reputation: 1108557

You're sending a POST request by ajax, however your servlet is only accepting GET requests. Using a decent browser-integrated web developer tool such as Firebug or the builtin one in Chrome (press F12), you should have noticed that the ajax request returned a HTTP 405 Method Not Allowed response which should by itself already have turned on a bulb in your head.

So, to solve your problem, just either rename doGet() method to doPost() in servlet, or let Ajax send a GET request instead.

Your script and servlet code looks in general fine. I do not recommend to rewrite it as suggested by the other answerer here, you'll totally lose graceful degradation (i.e. the form won't be submitted at all when the enduser has JavaScript disabled).

Upvotes: 3

Sanjay Kumar
Sanjay Kumar

Reputation: 1474

  1. Change your input type to button.
  2. Create a function and call it onclick of the button.
<input id="submit" type="button" value="Show results" onclick="submitForm()"   name="submit"/>

and then create a function..

    <script>
    function submitForm(){
        $.ajax({
            type:       "post",
            url:        "twitterv2",
            data:       "term=" + term,
            success:    function(msg) {

                $('#result').hide();

                $("#result").html("<h3>" + msg + "</h3>")
                .fadeIn("slow");
            }
        });
    }
</script>

Upvotes: 0

Related Questions