Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
238 views
in Technique[技术] by (71.8m points)

javascript - AJAX call print success message then replace with clear form

I have an ajax call that prints out a message successfully.

I want to print out the success message on top of the form and then hide that message and make a new clear form visible.

I have tried:

  • resetting and showing the form after the success message with the reset() and show() functions but the div from the message remains on screen.
  • calling fadeOut() on the message but the div background remains on screen

I believe the problem is that the message div replaces the form and there is no way to call back the form?

Here is what I have:

$(document).ready(function(){

    $("#form-id" ).on( "submit", function(e) {
 
        var dataString = $(this).serialize();

        $.ajax({
            type: "POST",
            url: "/handlers/form-handler.php",
            data: dataString,
            success: function () {
                $("#form-id").html("<div id='message'></div>");
                $("#message").append("<img src='images/checkmark.png'>").hide().fadeIn(1000, function () {$("message").append("<p>Thank You!</p>").fadeOut(2000);});
                $("#form-id")[0].reset(); 
                $("#form-id").show();
            },
        });
    e.preventDefault();
    });
});
</script>
question from:https://stackoverflow.com/questions/65845357/ajax-call-print-success-message-then-replace-with-clear-form

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Replying to my own post in case someone else is in the same position.

What I wanted was:

  • a reset on my form
  • a fade in message over my reset form
  • a fade out of the message
  • the newly reset form

The steps I followed:

  • placed my div with the success message within my form
  • gave my message div a higher z-index from my form
  • gave my message div a position:absolute
  • gave my form a position: relative
  • gave my message div a display:none

Result:

  • upon submitting successfully the message div fades in and out of the form and a fresh new form is revealed.

My new success function and message:

success: function () {
  $("#form-id")[0].reset();
  $('#message').hide().fadeIn(1000, function(){ $("#message"); 
  }).fadeOut(2000);
}

In my form file:

<form id="form-id" action="">
  <div id="message">Thank you for contacting us!</div>
</form>

My style sheet:

#message{
  display: none;
  z-index: 900 !important;
  position: absolute;
}

#form-id{
  position:relative;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...