简体   繁体   中英

How come my AJAX post request is not working?

I am trying to click on the "Change" button and send the form data to another JSP page in order to perform an UPDATE statement in the database. For some reason I cannot get the "update" id button to execute the click() function with the AJAX call in it as the "ham" alert does not pop up. Sorry I have multiple commented out approaches to this in the script tags since I tried out multiple things. Would someone be able to help me out with this? The current jsp page looks as follows:

<!DOCTYPE html>

<head>
  <script src="/.jquery-1.9.1.js" type="text/javascript" charset="utf-8"></script>
  <script src="http://code.jquery.com/jquery=latest.min.js" type="text/javascript">
    var getUrlParameter = function getUrlParameter(sParam) {
      var sPageURL = decodeURIComponent(window.location.search.substring(1)),
        sURLVariables = sPageURL.split('&'),
        sParameterName,
        i;
      for (i = 0; i < sURLVariables.length; i++) {
        sParameterName = sURLVariables[i].split('=');
        if (sParameterName[0] == sParam) {
          return sParameterName[1] == undefined ? true : sParameterName[1];
        }
      }
    };

    $(document).ready(function() {
      var key = getUrlParameter("key");

    });
    $(form).submit(function() {
          if (-1 == this.action.indexOf('register')) {
            var jForm = $(this);
            $.post(this.action, $(this).serialize(), function(data) {
                if (data.status == 'SUCCESS') {
                  jForm[0].action = data.redirectUrl;
                  jForm.submit();
                }
                return false;
              }
            }
          });

        window.onload = function() {
          document.getElementById("submit").onclick = function() {
            location.href = "/View.jsp";
          }
        }

        window.onload = function() {
          document.getElementById("update").onclick = function() {
            location.href = "/View.jsp";
          }
        }
        $(document).ready(function() {
            $('#update').on('click', function(e) {
                  alert('ham');
                  $.ajax({
                    type: "post",
                    url: "change.jsp",
                    data: $("#form").serialize(),
                    success: function(msg) {
                      alert(msg.data);
                    },
                    error: function(xhr, ajaxOptions, thrownError) {
                      alert(xhr.status);
                      alert(thrownError);
                    }
                  });


                  $(document).ready(function() {
                    function click() {
                      alert('ham');
                      $.ajax({
                        type: "post",
                        url: "change.jsp",
                        data: $("#form").serialize(),
                        success: function(msg) {
                          alert(msg.data);
                        },
                        error: function(xhr, ajaxOptions, thrownError) {
                          alert(xhr.status);
                          alert(thrownError);
                        }
                      });

                      window.location.href = "change.jsp";
                      return false;
                    }
                  });



                  /*function validateForm(){
                  var x=document.forms["insert"]["ID"].value;
                  alert(x.len());
                  if(x==null||x==""){
                  alert("ID must be filled out");
                  return false;
                  }
                  }*/

  </script>
</head>

<body>
  ...
  <form id="myForm" action="register" method="post" name="insert">
    ID:
    <input type="text" name="ID" required value="<%=id%>" />
    <br/> RHINO:
    <input type="text" name="rhino" required value="<%=rhino%>" />
    <br/> OX:
    <input type="text" name="ox" required value="<%=ox%>" />
    <br/> HORSE:
    <input type="text" name="horse" required value="<%=horse%>" />
    <br/>

    <input type="submit" value="Submit" id="submit" />
    <!--<input type="submit" value="Update" id="change"/>-->
    <button id="update" onclick="return click()">Change</button>
  </form>
  ...
</body>

</html>

You're defining the function in a closed scope:

$(document).ready(function() {
    function click() {
        //...
    }
});

So it only exists within that anonymous function being used as the ready handler. Once that function terminates, anything defined in that scope is no longer used if nothing references it.

Then you try to invoke the function from global scope:

<button id="update" onclick="return click()">Change</button>

So the function can't be found.

Instead of trying to invoke it from inline code in the HTML, use the jQuery library that you're already using and attach the handler to the click event:

$(document).ready(function() {
    $('#update').click(function () {
        // the code in your click() function goes here
    }
});

And remove that inline handler:

<button id="update">Change</button>

(Note: There may very well be other problems in this code. It's actually quite difficult to follow without any indentation at all. But at the very least this problem seems the most immediate upon clicking that button. It needs to be able to find the function in order to execute it.)

Update: Another user has formatted the code in your question, and there do appear to be other problems. Specifically, you are making multiple simultaneous attempts to attach very different behaviors to the click of that button. One of those events appears to even be a redirect, which would simply cancel any other operations because the page is reloading. Simplify your code. Perform exactly and only the operation you want on that button click.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM