kosterz
kosterz

Reputation: 117

How to make dynamic content with servlet + ajax

I'm trying to learn jsp + servlet and everything is going well if I make it basically ( jsp send data to servlet then servlet fetch data from db and set attribute and forward to new page) but the problem occurred when I try to updating some content without reload page ( using ajax to send data to servlet and forward to jsp file and I use jquery to load specific ) , it's nothing change that content.

Servlet

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
        /* TODO output your page here. You may use following sample code. */
        int id = Integer.parseInt(request.getParameter("id"));

        Database db = new Database();
        ProductTable productTable = new ProductTable(db);
        Product product = productTable.findByID(id);
        db.close();

        request.setAttribute("productDetail", product);
        request.getRequestDispatcher("/view/backend/selectProduct.jsp").forward(request, response);
    } finally {
        out.close();
    }
}

JSP modal

<!-- language: html -->
<div class="modal fade" id="modalEditProduct" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title" id="myModalLabel">Modal title</h4>
            </div>
            <div class="modal-body">
                <div class="tableSelectProduct">
                    <%@include file="selectProduct.jsp" %>
                </div>
            </div>
            <div class="modal-footer">
                 <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                 <button type="button" class="btn btn-primary" id="btnOK">Save</button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

Script for modal

$(document).ready(function() {
    $(".viewdetail").click(function() {
        var id = $(this).attr('id');
        $.ajax({
            url: "/BookStore/SelectProduct",
            data: {"id": id},
            type: 'POST',
            cache: false,
            error: function() {
                alert('error');
            }
        });

        $(".tableSelectProduct").load("/view/backend/selectProduct.jsp");
        $("#modalEditProduct").modal('show');
        $("#btnOK").click(function() {
            $("#modalEditProduct").modal('hide');
        });
    });
});

selectProduct.jsp ( want to update this content by doesn't reload main page)

<!-- language: lang-html-->
<table width="100%" border="0" class="table" id="center" align="center">
    <tr>
        <td width="14%"></td>
        <td width="63%">
            <label for="thumbnail">Pic</label>
            <a class="thumbnail">
                <img class="resize" src="/BookStore/images/${productDetail.photo}" id="imgprofile" 
                     data-src="/BookStore/asset/js/holder.js/130x100">
            </a>
        <td width="23%"><span id="titleNotice"> * ( required )</span></td>
    </tr>
    <tr>
        <td width="14%"></td>
        <td width="63%">
            <label for="titleNotice">Title</label>
            <input type="text" class="form-control" name="title" 
                   onblur="checkEmpty(this, 'titleNotice')" value="${productDetail.title}"></td>
        <td width="23%"><span id="titleNotice"> * ( required )</span></td>
    </tr>
    <tr>
        <td></td>
        <td>
            <label for="titleNotice">ISBN</label>
            <input type="text" class="form-control" id="form-control" 
                   value="${productDetail.isbn}" onblur="checkEmpty(this, 'ISBNNotice')">
        </td>
        <td><span id="ISBNNotice"> * ( required )</span></td>
    </tr>
    <tr>
        <td></td>
        <td>
            <label for="titleNotice">Catagory</label>
            <input type="text" class="form-control" id="form-control" readonly="true"
                   value="${productDetail.catagory}" name="catagory" onblur="checkEmpty(this, 'ISBNNotice')">
        </td>
        <td>
            <label for="titleNotice"></label>
            <button type="button" class="btn btn-primary" id="addCatagory">
                Change Catagory
            </button>
        </td>
    </tr>
    <tr>
        <td></td>
        <td>
            <label for="titleNotice">Author</label>
            <input type="text" class="form-control" id="form-control" 
                   value="${productDetail.author}" name="author" onblur="checkEmpty(this, 'authorNotice')"></td>
        <td><span id="authorNotice"> * ( required )</span></td>
    </tr>
    <tr>
        <td height="130"></td>
        <td>
            <label for="titleNotice">Detail</label>
            <textarea name="detail" rows="5" class="form-control" id="form-control" 
                      onblur="checkEmpty(this, 'detailNotice')" >${productDetail.detail}
            </textarea>
        </td>
        <td><span id="detailNotice"> * ( required )</span></td>
    </tr>
    <tr>
        <td></td>
        <td>
            <label for="titleNotice">Price</label>
            <input type="text" class="form-control" id="form-control" 
                   value="${productDetail.price}" name="price" onblur="checkEmpty(this, 'priceNotice')">
        </td>
        <td><span id="priceNotice"> * ( required )</span></td>
    </tr>
    <tr>
        <td></td>
        <td>
            <label for="titleNotice">Stock</label>
            <input type="text" class="form-control" id="form-control" 
                   value="${productDetail.quantity}" name="quantity" 
                   onblur="checkEmpty(this, 'stockNotice')"></td>
        <td><span id="stockNotice"> * ( required )</span></td>
    </tr>
</table>

Upvotes: 3

Views: 6937

Answers (2)

ChiranjeeviIT
ChiranjeeviIT

Reputation: 529

To find out the real issue in your ajax, better to use below AJAX call structure. It's better to maintain this always for JQuery AJAX calls.

$.ajax({

    type:         "POST",
    url:          "/BookStore/SelectProduct",
    dataType:     "text/xml",
    data:         "",
    processData:  false,  // default to true will parse data as an Array whereas we send XML
    contentType:  "text/xml",
    async:        false,
    beforeSend: function (request)
    {
        // to set some formats
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {  

        if (XMLHttpRequest.status == 400) {
             // Bad Request
             if (XMLHttpRequest.responseText.indexOf("DOMAIN_NOT_FOUND") != -1) {
              alert('invalid domain');

              return false;
             }
      }
      else if (XMLHttpRequest.status == 401) {
             // User/Pass Invalid
       alert('invalid authentication');
          return false;
      }
      else{
       alert('error'+XMLHttpRequest.responseText);
         return false;
      }
    },
    success: function(xml) {
        /* right your logic here */
        return;  
    }  });

Thanks, Chiranjeevi

Upvotes: 1

Bob Tate
Bob Tate

Reputation: 1381

Looks like you are missing the success property.

 $.ajax({
        url: "/BookStore/SelectProduct",
        data: {"id": id},
        type: 'POST',
        cache: false,
        success: function(response) {
            //  Add in what to do when ajax call is successful
        },
        error: function(xhr, ajaxOptions, thrownError) {
            alert('error');
        }

Upvotes: 1

Related Questions