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
142 views
in Technique[技术] by (71.8m points)

javascript - How to avoid page reload in php form submission

I am currently using php in my html page and there is an action in the same page which gets executed upon form submission. Currently whole form gets reloaded while I want the php action to be run in the background with out reloading. How do I do it. I would also want to clear the text box after submit button is clicked. Following is the code I am currently using

<html>
<head>
</head>

<body>
    <form action="index.php" method="post"  role="form">
        <input type="email" placeholder="Enter email"  name="email_address">
        <button class="btn btn-primary custom-button red-btn">Sign Up</button>
    </form>

<?php



if(isset($_POST['email_address'])  !(trim($_POST['email_address']) == ''))

// do some action
}

?>
</body>

</html>

Note: Following code worked for me

<script type="text/javascript">
    $('#contactForm').submit(function () {
       $.post("mailer.php",$("#contactForm").serialize(), function(data){
       });
        return false;
    });
</script>
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You need to use AJAX for this, for without reloading. Or, if you want to do it without disturbing the page, you need to set target.

Using AJAX

$("form").submit(function(){
  $.post($(this).attr("action"), $(this).serialize());
  return false;
});

Using target

<form action="index.php" method="post" role="form" target="_blank">

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

1.4m articles

1.4m replys

5 comments

57.0k users

...