Reputation: 225
I have this code that submits to a database without refresing, but the problem is when its sent, the variables still remains in the textfield
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script>
$(document).ready(function(){
$("form").on('submit',function(event){
event.preventDefault();
data = $(this).serialize();
$.ajax({
type: "POST",
url: "insert.asp",
data: data
}).done(function( msg ) {
});
});
});
</script>
i was thinking if there's a way the variables will disappear from the textfiled after its been sent to the database and even bring an alert which fades automatically when data is saved.
Upvotes: 0
Views: 132
Reputation: 151
I think what you'll want to do is add your desired behavior in the callback following the ajax request. Currently you're using "done" as the callback, which in my understanding will execute whenever the ajax call completes, regardless of success or failure. If that's what you desire, add the textfield clearing and alert code within this callback, otherwise a callback like "success" may be more appropriate.
I'm not entirely sure what you mean by an "alert"... If you're referring to an alert box, ie.: alert(), I wouldn't suggest it. This will pause your script until the user clicks the button, thus there is no way to kill the alert once it has been displayed. Also alert boxes aren't the nicest thing to present to the user imo. An alternative would be to define a div somewhere in your page, add the success message to it with jquery within the success/done callback and then set a time out so that it fades (included in my example below). If you're looking for something more elaborate jquery ui has some alternatives to alert boxes in their widgets.
Maybe this code can give you some ideas to get started:
<script>
$(document).ready(function(){
$("form").on('submit',function(event){
event.preventDefault();
data = $(this).serialize();
$.ajax({
type: "POST",
url: "insert.asp",
data: data
}).success(function() {
$("#feedback").append("<div class='messages' style='border:1px green solid; padding:2px; margin:5px;'>successfully submitted!</div>");
setTimeout(function() {
$(".messages").fadeOut(function(){
$(".messages").remove();
});
}, 1000);
$("input[type=text]").val("");
});
});
});
</script>
Where there's a div with an id="feedback" where you'd like to display messages.
Upvotes: 0
Reputation: 29846
You can do something like this:
$('input[type=text]').val(''); // select all text inputs and assign value of ''
Your code:
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script>
$(document).ready(function(){
$("form").on('submit',function(event){
event.preventDefault();
data = $(this).serialize();
$.ajax({
type: "POST",
url: "insert.asp",
data: data
}).done(function( msg ) {
$('input[type=text]').val('');
});
});
});
</script>
Upvotes: 1