Use jQuery to replace form with 'Thank You'

2019-09-19 15:54发布

问题:

Hi is it possible to make a contact form hide after hitting submit? With a message saying Thank you where the form was?

回答1:

<form id="form">
   <input type="text" name="name" placeholder="Your name">
   <textarea name="message" placeholder="Message"></textarea>
   <input type="submit" value="Send">
</form>
<div id="thanks" style="display:none;">Thank you!</div>

var $form = $('#form');

$form.submit(function( evt ){
    evt.preventDefault();
    $.ajax(function(){
       url  : "send.php",
       type : "POST",
       data : $form.serialize()
    }).done(function( phpSays ){
        if( phpSays == "OK" ){  // make your .php script return an "OK" string
            $('#thanks').show();
        }else{
            // DO something else if something went wrong
        }
    });
});

You can notice that the <form> doesn't have the action and method attributes,
cause all that will be handled without page refresh by an AJAX call to your .php script.
This example might fail for that poor guy with JS disabled (handlable with a <noscript> info element) but useful to prevent load of junk emails (cause usually junk bots will crawl without JS support searching for the above mentioned method and action attributes).

http://api.jquery.com/jquery.ajax/



回答2:

Actually, it's not so simple.

Submission of a form will transfer the user to the document specified in the action= attribute of the <form> tag... UNLESS, as Lexib0y pointed out, you were to use AJAX to submit the form but remain on the same page. Upon receiving the submitted form elements in the 2nd document, you could simple duplicate the first page, but placing "Thank you for your submission" exactly where the form used to be.

Alternately, you could submit the form to the same document you are on (by specifying action=""), but even so you are redrawing the screen.

Next, here are some good posts for getting the basics of AJAX:

A simple example

More complicated example

Populate dropdown 2 based on selection in dropdown 1