简体   繁体   中英

Handle form submission in jQuery

I have a web form to let user enter some information and submit. I want such behavior that if the submission is successful, the it will go to a page. But if there are some form submission errors (in my case is due to existing ID), I want the form stay there without going to the next page and alert the user "ID already exists". I used jQuery to handle the success and fail events:

function checkForm() {

$.post("/myapp/rest/customer/created", $("form").serialize(), function(
    data, status) { })
.done(function() {alert("post success");})
.fail(function() {alert("post error");});
return false;
}

My form is:

<form action="/myapp/rest/customer/created"
    onsubmit="return checkForm();" method="POST">
    <table border="1">
        <tr>
            <td>Customer name:</td>
            <td><input type="text" id="name" name="name"></td>
        </tr>
        <tr>
            <td>Customer ID:</td>
            <td><input type="text" id="id" name="id"></td>
        </tr>
        <tr>
            <td>Customer DOB:</td>
            <td><input type="text" id="dob" name="dob"></td>
        </tr>
    </table>
    <br /> <input type="submit" value="Submit">
</form>

After submission, no matter whether the submission is a success or failure, I only see the popup message box saying "post success" or "post error". But it will never go to the next page if it's successful. I even tried a different approach like the code below but it didn't work either:

function checkForm() {
    $.post("/myapp/rest/customer/created", function(data, status) {
      if (status === "success") {
        alert("post success");
      } else {
        alert("post error");
      }
    });

    return false;
}

So how to correct it to make it redirect to the next page ( /myapp/rest/customer/created ) if the submission is successful?

You can redirect within your success conditional using window.location.href :

if (status === "success") {
  window.location.href = 'http://url.com'
}

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