Dhaval Simaria
Dhaval Simaria

Reputation: 1964

post comments using jsp, servlet and ajax

I am trying to create a comment section using jsp, servlet and ajax. The problem I am facing is that each comment replaces it's previous one instead of showing next to it.

Highly appreciate any kind of help.

<script type="text/javascript" src="js/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
        $('#submitBtn').click(function() {
        var cmt = $('#cmt').val();
        $.ajax({
            type : 'POST',
            data : {
                cmt : cmt,
                action : 'EnterMsg'
            },
            url : 'SubmitComment',
            success : function(result) {
                $('#view2').text(result);
            }
        });
    });
});

</script>
</head>
<body>
    <fieldset>
        <legend>Enter Message</legend>
    <form>
        Ques.<input type="text" id="cmt"> <input type="button"
            value="Send" id="submitBtn"><br> <span id="post1"></span>
    </form>
</fieldset>
<fieldset>
    <legend>View Message</legend>
    <form>
        <div id='view2'></div>
        <br>
    </form>
</fieldset>

Upvotes: 0

Views: 1480

Answers (1)

Madushan Perera
Madushan Perera

Reputation: 2598

Try

 var html='';
   $.ajax({
    dataType: "json",
    url: "SubmitComment",
    error: function () {
          alert('error occured');
    },
    success: function (result) {
    for(var key in result) {
    var value = result[key];
        html+='<div>'+key+':'+value+'</div>'
    }
    $("#view2").append(html);

    }
});

Instead of

 success : function(result) {
            $('#view2').text(result);
        }

Because of you get multiple comments from the ajax respose and you have to iterate each one of them and append to your div tag

Upvotes: 1

Related Questions