How to post form with ajax after form validate?

Viewed 50

I try to post my form with ajax.But when i use click instead of submit in jquery part, it works but this time form hasnt validate. when i use submit this this ajax doesn't trigger after validation.Whats wrong?

<input type="text" class="form-control" id="Name" name="Name" aria-describedby="Name" required />
</div>
<div class="form-group">
  <label for="Surname" class="h6">Surname</label>
  <input type="text" class="form-control " id="Surname" name="Surname" aria-describedby="Surname" required />
</div>

<button id="btnAddUser" name="btnAddUser" type="submit" class="btn btn-primary float-right">Add User</button>
$(document).ready(function() {
  $('#btnAddUser').submit(function() {
    var user = {};
    user.Name = $('#Name').val();
    user.Surname = $('#Surname').val();
    user.ActiveDirectory = $('#ActiveDirectory').val();
    user.Role = $('#Role').val();
    user.Status = $('#Status').val();

    $.ajax({
      url: '/Processes.asmx/addUser',
      method: 'post',
      data: '{usr: ' + JSON.stringify(user) + '}',
      contentType: "application/json; charset=utf-8",
      success: function() {

        alert('Success');
      },
      error: function(err) {
        alert(err);
      }
    });
    return false;
  });
});
1 Answers

The issue is because button elements do not raise a submit event. To fix your issue you need to wrap the controls in a form element then hook your JS to the submit event of that, like this:

<form action="/yourpage" method="POST">
  <input type="text" class="form-control" id="Name" name="Name" aria-describedby="Name" required />

  <div class="form-group">
    <label for="Surname" class="h6">Surname</label>
    <input type="text" class="form-control " id="Surname" name="Surname" aria-describedby="Surname" required />
  </div>

  <button id="btnAddUser" name="btnAddUser" type="submit" class="btn btn-primary float-right">Add User</button>
</form>
jQuery($ => {
  $('form').on('submit', function(e) {
    e.preventDefault();
    var user = {
      Name: $('#Name').val(),
      Surname: $('#Surname').val();
      ActiveDirectory: $('#ActiveDirectory').val();
      Role: $('#Role').val();
      Status: $('#Status').val();
    };

    $.ajax({
      url: '/Processes.asmx/addUser',
      method: 'post',
      data: '{usr: ' + JSON.stringify(user) + '}',
      contentType: "application/json; charset=utf-8",
      success: function() {
        console.log('Success');
      },
      error: function(err) {
        console.log(err);
      }
    });
  });
});

I would also suggest you review how you create the data you send in the AJAX request. Encoding JSON manually is a code smell, along with nesting JSON within JSON.

Depending on the model binding you're using in your WebMethod and the form HTML, you could simplify it to just data: $(this).serialize().

Related