Search code examples
javascriptjspjstl

Why isn't this code working (js function)?


I'm working on Java EE web app and need to working with js also.There is two buttons on app jsp page :one of them upVote and downVote.I want to make the button call '${upVote}' at first click and call '${downVote}' when the same user clicking for second time. The logic of the process is to ensure that each user can vote one time per question.But I don't know why is not working as desired.

So I need to help about this.All answers appreciated.

My Code :

    <c:url var="User" value="/AQ/User">
        <c:param name="answerUserId" value="${question.USERID}" />
    </c:url>
    <c:url var="Question" value="/AQ/UpdateQuestion">
        <c:param name="questionId" value="${question.ID}" />
    </c:url>
    <c:url var="upVote" value="/AQ/UpVoteQuestion">
        <c:param name="questionId" value="${question.ID}" />
        <c:param name="qUserId" value="${question.USERID}"/>
    </c:url>
    <c:url var="downVote" value="/AQ/DownVoteQuestion">
        <c:param name="questionId" value="${question.ID}" />
        <c:param name="qUserId" value="${question.USERID}"/>
    </c:url>

<script type="text/javascript">
    var voteCounter = 0;
    var votedQuestion = 0; 

    function control() {     

        if('${sessionScope[userId]}' <= 0){window.location.href='SignIn'}
        else if(voteCounter >= 1 && votedQuestion == '${question.ID}') {window.location='${downVote}';}
        else{
            voteCounter++;
            votedQuestion = '${question.ID}';
            window.location='${upVote}';
             return false;
        }
    }

    function reverse() {
        if('${sessionScope[userId]}' <= 0){window.location.href='SignIn'}
        else if(voteCounter >= 1 && votedQuestion == '${question.ID}') {window.location='${upVote}';}
        else{
            voteCounter++;
            votedQuestion = '${question.ID}';
            window.location='${downVote}';
             return false;
        }
    }
</script>

And there is my buttons :

<pre style="max-width: 35px; margin-right: 10px;">

                <input class="vote-img" type="image"
                    src="${pageContext.request.contextPath}/resources/images/upVote.png"
                    id="vote" onclick="control()"/>
                <br>
                <label style="float: left; margin-left: 18px;"><c:out value="${question.VOTE }" /></label>
                <input class="vote-img" type="image"
                    src="${pageContext.request.contextPath}/resources/images/downVote.png"
                    id="vote" onclick="reverse()"/>
</pre>

Solution

  • window.location is refreshing your browser which means the js is loaded again and voteCounter == 0 every time.