I am currently trying to reload a specific form, which is the form inside which the button was submitted, purely for the purpose of instant feedback. I am creating a Favorites button. This is my current setup. The ajax works but I still have to reload the page for it to show the new styles and even to change the METHOD type, which is required to unfavorite-favorite.
$.ajax({
type: method,
url: url,
data: form.serialize(),
success: function() {
form.reload();
}
});
So i would do it like this
//mainpage.php
<html>
// ... snip html ...
<?php include("form.php") ?>
<script>
$("form").one('submit', function (evt) {
evt.preventDefault();
var $this = $(this);
$.ajax({
url: $this.attr('action'),
method: $this.attr('method'),
}).done(function (data, status, xhr) {
var $newForm = $(data);
$this.html($newForm.html());
$this.attr("method", $newForm.attr("method"));
});
});
</script>
// ... snip more html ...
then the form page just returns the <form>
html
//form.php
<form method="<?php $method ?>" action="form.php">
<input name="foo">
<input type="submit" value="submit">
</form>
Note: you may have to rebind the form after you submit, you will have to double check that.
I guess you could clear all fields :
$.ajax({
type: method,
url: url,
data: form.serialize(),
success: function() {
form.find('input:text, input:password, input:file, select, textarea').val('');
form.find('input:radio, input:checkbox')
.removeAttr('checked').removeAttr('selected');
}
});
Taken from this answer .
EDIT :
As precised in comments, maybe you should get your server send back infos from the newly created item.
Then you could populate a "template" you have, and replace the form with it :
var newItem = $("<div class='newItem'></div>");
$.ajax({
type: method,
url: url,
data: form.serialize(),
success: function( data ) {
//Get response from server like : {'name':'Name', 'attribut':'Attribut'}
for( var key in data ) {
newItem.append("<p>" + key + " : " + data[key] + "</p>");
}
form.replaceWith(newItem);
}
});
An example JSFiddle .
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.