简体   繁体   中英

Update data on submit button and stay on the same page

I have the following jsp page in which there is a table populated with data from arraylist in java code. I put table rows in input tag to be able to edit them. what I want to do now is to save data after editing them and still stay on the same page. I think I can use either javascript/jquery or ajax call and I've read about some solutions using them, but don't know actually how to use it to make it work! Any hints or suggestions would be appreciated alot!

        <stripes:form beanclass="SaveStudent.action">
          <table>
                <c:forEach var="array" items="${actionBean.importExcel }">
                    <tr>
                        <td><input type="text" value="${array.getStudent().getPersonalNumber() }" name="pnr"/></td>
                        <td><input type="text" value="${array.getStudent().getEmail() }" name="email"/></td>
                    </tr>
                </c:forEach>
            </table>

            <p>
                <stripes:submit name="saveExcel" value="save"/>
            </p>

        </stripes:form>

Edited version: I have an array in java which I passed to jsp to be displayed as a table to user. when user change a value in the page, I need that value get updated(done by Ajax call(answered already, see following!)) and then shown to the user and at the same time get updated in the array in java code. My problem now is that how to pass variable from JQuery to jstl/jsp. I tried following, but not working, I don't know what I'm doing wrong!

<script>        
   $(document).ready(function() {
     $("#click").click(function(){
        var pnr = $("#pnr").val();
        $.ajax({
            type:"POST",
            url:"newImport.jsp",
            data: pnr,
            success:function(data){
              $("#pnr").html(data);
              alert('Update success!');
            },
            failure: function(data){
               alert('Update Failed!');
            }
        });
    });
});             
</script>

<% 
    String pnr = request.getParameter("pnr");
    out.println(pnr);//For test
%>
<table>
<c:forEach var="array" items="${actionBean.importExcel }">
    <tr>
    <c:choose>
        <c:when test="${request.getParameter('pnr')=='null'}">
            <td><input type="text" value="${array.getStudent().getPersonalNumber() }" id="pnr" name="pnr"/>
            </td>
        </c:when>
        <c:otherwise>
            <td><input type="text" value="${request.getParameter('pnr') }" id="pnr" name="pnr"/>
            </td>
        </c:otherwise>
    </c:choose>
    </tr>
</c:forEach>
</table>

I dont know about stripes, but I know how to do it in ajax.

<form>
    <input type="text" id="phoneNumber" name="phoneNumber"/><br>
    <input type="text" id="email" name="email"/><br>
    <button type="button" id="submit">Submit</button>
<form>

<script type="text/javascript">
    $("#submit").click(function() {
        var phoneNo = $("#phoneNumber").val();
        var email = $("#email").val();
        $.ajax({
            url: 'yourActionPath',
            type: 'POST',
            data: {
                phoneNo: phoneNo,
                email: email
            },
            success: function(data) {
                alert('Update Success');
            },
            failure: function(data) {
                alert('Update Failed');
            }
        });
    )};
</script>

You can get the phoneNo and email by using request.getParameter("phoneNo") and request.getParameter("email").

Make changes in this code according to your technology.

Use jquery .post method to send data asynchronously.

jQuery.post(url,data,success(data, textStatus, jqXHR),dataType)

data refers your post data from form, like your pnr or email .

See demo here:

http://jsfiddle.net/52jb3xLk/

You need to create a server-side request handler of some sort to call with your updated data. Another jsp page, a rest-api, etc. Some url resource you can call, post data to, and have it update your data server side.

Regarding ajax, that is the way you would call that resource without leaving your page. JQuery is a javascript library that simplifies scripting in a lot of ways, including making ajax calls. Jquery ajax call

Then your ajax call needs to have functions defined to update your page depending on the server's response (depending on if your call was successful or failed). Here's some example code to serialize an HTML form to an object, then "stringify" it to json, run an ajax call to a rest api, and respond to it on your page.

//serializes an object, in this case used for a form
$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

//returns json representation of <form id="myForm">
function getData()
{
    var retVal = JSON.stringify($('#myForm').serializeObject());
    return retVal;
}

//makes the ajax call to server
function submitform()
{       
    $.ajax({
      type: "POST",
      url:'/LicenseService/v1/license',
      data: getData(),
      beforeSend: function(){$('#loadingDiv').show();}
    }).done(function(data) {
      //code to run when the call is successful
    }).fail(function(data) {
      //code to run when the call encounters an error
    }).complete(function(data){
        //code to run no matter what (runs after done or fail)
    });
}

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