0

There is a jsp form for recording a new flight. I need to check the availability of the flight number using ajax in the database. I'm trying to write an ajax request, but I'm beginner in JS.

    <div class="form-group">
    <div class="input-group">
        <input type="number" class="form-control" placeholder="Flight number" id="flightNumber" name="flightNumber" required>
        <p class="error-input" id="loginError">
            <c:if test="${duplicateFlightNumber == true}">
                <fmt:message key="validate.sameFlightNumber"/>
            </c:if>
        </p>
    </div>
</div>

<div class="form-group">
    <div class="input-group">
        <input type="text" class="form-control" placeholder="From city" id="fromCity" name="fromCity" required>
    </div>
</div>

<div class="form-group">
    <div class="input-group">
        <input type="text" class="form-control" placeholder="To city" id="toCity" name="toCity" required>
    </div>
</div>

Servlet that proceed this form without ajax:

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    Flight flight = new Flight();        flight.setFlightNumber(Integer.valueOf(req.getParameter("flightNumber")));
    flight.setFromCity(req.getParameter("fromCity"));
    flight.setToCity(req.getParameter("toCity"));

    if (!validation.flightNumberUnique(flightNumber)){
        req.setAttribute(DUPLICATE_FLIGHT_NUMBER, true);
        forward(Constants.Pages.Admin.ADD_FLIGHT_JSP, req, resp);
        return;
    }

    getFlightService().add(flight);

    LOGGER.trace("New flight added");
    redirectToAction(Constants.ServletPaths.Admin.ADMIN_ALL_FLIGHT_PATH, req, resp);
}

How can I replace this manipulation with ajax

Laxmikant Dange
  • 7,606
  • 6
  • 40
  • 65

1 Answers1

0
$("#flightNumber").change(function(){
    var flightnumber = $("#flightNumber").val();
    //get to and from values
    $.post("servletname",{"flightNumber":flightnumber,"fromCity":fromCity,"toCity":toCity}, function(data, status){
    //data contains elements that you print on your servlet
    $("#loginerror").text("your message to be displayed in error field");

    });
});

$(selector).post(URL,data,function(data,status,xhr),dataType) is used for ajax post request (Jquery)

Quest
  • 3
  • 3