javascriptjqueryajaxjsp

Something wrongs with JSP getParameter and JQuery GET ajax


I need to add GET parameters using jQuery ajax when I click on button. For example there is a code:

<button id="20" class="click">Click me</button>
<button id="21" class="click">Click me</button>
<button id="22" class="click">Click me</button>

By clicking on specific button I need to pass the button id:

myapp.com/mainpage.jsp?check=20

But, it should be work using JQuery ajax API. I mean, the param should not be visible in URL, because each time when I will be do changing check value, this action will be refresh a page, I needn't it. I wrote a code like this:

$(document).ready(function() {
                $(".btn-info").click(function() {
                    $.ajax({
                        url: "stuff",
                        type: "GET",
                        data:{ checkId: this.id },
                        success: function(response) {
                            console.log("success: " + response);
                        },
                        error: function(xhr) {
                            console.log("error exception: " + xhr);
                        }
                    });
                });
            });

And in the end, I added the JSP code

My result: <%= request.getParameter("checkId") %>

When I click by specific button, for example by button

<button id="20" class="click">Click me</button>

In browser logs I saw a html document with value is 20:

enter image description here

And this correct! But on page this value didn't change and still be null:

enter image description here

Could you tell me please, why it happens, and what I'm doing wrong?


Solution

  • This is not the true way for the thing u want.

    First you should send the request to a servlet (doGet method of servlet). And servlet will return a 'response' value to your jsp. Then in success part of ajax function you can change the value of True result

    $(document).ready(function() {
      $(".btn-info").click(function() {
        $.ajax({
          url: "stuff",
          type: "GET",
          data: {
            checkId: this.id
          },
          success: function(response) {
            console.log("success: " + response);
            $('#trueResult').html(response);
          },
          error: function(xhr) {
            console.log("error exception: " + xhr);
          }
        });
      });
    });
    
    True result <span id="trueResult"></span>