I want to submit a form without refreshing the page, and I have this form:
<form method="post" action="user-add.php" id="user-add-form">
<input type="text" id="username" name="username" maxlength="15">
<button type="submit" name="add_user" class="btn btn-primary" id="user-add-submit">Add user</button>
</form>
and this jquery function ( using jquery validation plugin ):
submitHandler: function() {
$('#user-add-submit').button('loading');
var post = $('#user-add-form').serialize();
var action = $('#user-add-form').attr('action');
$("#message").slideUp(350, function () {
$('#message').hide();
$.post(action, post, function (data) {
$('#message').html(data);
$('#message').slideDown('slow');
if (data.match('success') !== null) {
$('#user-add-form input').val('');
$('#user-add-submit').button('reset');
} else {
$('#user-add-submit').button('reset');
}
});
});
}
But my question is what user-add.php should look like for the script to work?
You callback function answers this question itself:
The above holds if we assume that the function will not be modified. But it would be a good idea to modify the function to make it more computer-friendly. You could instead return some JSON that looks like this:
Here
htmlis what you want to show andsuccessfulis for internal consumption. This way you don’t have to couple the string"success"with determining if the operation was successful indeed. With this scheme your callback would look like this: