简体   繁体   中英

How to prevent browser from opening a new page on form submit?

There's an email subscription form in a web page,
When someone enters his email and clicks on submit button ,
We don't want this page to be redirected to form action url ,
We just want it's submit button text value to be converted to another text ,
something like "Thank You!".
How is it possible? Should I go through ajax? or javascript?
Here's the form:

<form class="ml-block-form" action="//app.mailerlite.com/webforms/submit/myownID" data-code="myownID" method="POST" target="_blank">
<div class="form-group ml-field-email ml-validate-required ml-validate-email">
    <input class="newsletter-email" type="email" name="fields[email]" placeholder="Email*"/>
</div>
<input type="hidden" name="ml-submit" value="1" />
<p>
    <input class="newsletter-submit" type="submit" value="Get Updates!"/>
</p>

For starters remove target="_blank" from your form tag.

Then, within your jQuery , do something along the lines of this:

$(".ml-block-form").submit(function(){
    var vals = $(this).serialize();

    $.ajax({
        url: "postpage.php",  
        method: "POST",
        data: vals,
        success: function(data) {
            $("#formsubmit").val("Thank you!");
        }
    });

    return false; // prevent from submit
});

I've altered your HTML as well, as it was originally very messy. You can of course add the other elements back if you need:

<form class="ml-block-form" action="" data-code="myownID" method="post">
    <input id="mainval" type="email" name="fields[email]" placeholder="Email*">
    <input id="hiddenval" name="ml-submit" value="1" />
    <input id="formsubmit" type="submit" value="Get Updates!"/>
</form>

您只需删除target="blank"因为blank值会在新window打开链接的文档。

Instead of

<input class="newsletter-submit" type="submit" value="Get Updates!"/>

use

<button id="newsletter-submit" value="Get Updates!"/>

(note that I changed class for id )

And then use jQuery to handle the click on the button:

$("#newsletter-submit").click(function () {
    $(this).prop("value", "Thank You!");
    // do something else with the input values e.g. send them via ajax to a server script
});

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM