表单提交后避免刷新页面

时间:2014-09-15 10:37:03

标签: javascript php jquery forms

我的表单有问题:我不想要,当我按下Create Poll按钮时,页面刷新,所以我在js文件中创建了一个函数,但问题仍然存在。

index.html是主页

<!DOCTYPE html>
<html lang="it">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>League of Legends Straw Poll</title> 
    <link rel="stylesheet" type="text/css" href="css/bootstrap.css">
    <link rel="stylesheet" type="text/css" href="css/styles.css" />
</head>
<body>
    <div class="container">
        <div class="row">
            <div class="col-md-8 col-md-offset-2">
                <h1 class="text-center">Game Straw Poll</h1>
            </div>
        </div>
        <br>
        <div class="row">
            <div class="col-md-6 col-md-offset-3">
                <div class="panel panel-default">
                    <div class="panel-body">
                        <!-- FORM -->
                        <form name="form" id="form" method="post">
                            <div class="row">   
                                <div class="col-md-12">
                                    <!-- GAME -->
                                    <select class="form-control" id="game-group" name="game" onchange="ChangeBackground();">
                                        <option selected disabled>Select your Game...</option>
                                        <option value="League_of_Legends">League of Legends</option>
                                        <option value="Heartstone">Hearthstone</option>
                                    </select>
                                </div>
                            </div>
                            <br>
                            <div class="row">
                                <div class="col-md-12">
                                    <!-- QUESTION -->
                                    <div class="input-group" id="question-group">
                                        <input type="text" class="form-control" name="question" id="question" placeholder="Start typing your question...">
                                        <span class="input-group-addon">
                                            <i class="glyphicon glyphicon-question-sign"></i>
                                        </span>
                                    </div>
                                </div>
                            </div>
                            <br>
                            <div class="row">
                                <!-- OPTIONS -->
                                <div class="form-group form-group-options col-md-12 col-sm-12 col-xs-12">
                                    <div class="input-group input-group-option col-md-12 col-sm-12 col-xs-12" id="options-group">
                                        <input type="text" name="option[]" id="option" class="form-control" placeholder="Options...">
                                        <span class="input-group-addon input-group-addon-remove">
                                            <span class="glyphicon glyphicon-remove"></span>
                                        </span>
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-12">
                                    <!-- CHOICE -->
                                    <div class="checkbox" id="choice-group">
                                        <label>
                                            <input type="checkbox" id="choice" name="choice" value="Yes">Allow multiple choice
                                        </label>
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-12">
                                    <button type="submit" class="btn btn-primary btn-lg pull-left" name="submit_button" id="submit_button" data-toggle="modal" data-target="#myModal">Create Poll</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div id="myModal" class="modal fade">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title">Poll created</h4>
                </div>
                <div class="modal-body">
                    <p>Share it: <a href="http://gamepoll.net/<?php echo $rand_value; ?>">http://gamepoll.net/<?php echo $rand_value; ?></a></p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Chiudi</button>
                    <button type="button" class="btn btn-primary">Invia</button>
                </div>
            </div>
        </div>
    </div>

    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script type="text/javascript" src="js/bootstrap.js"></script>
    <script type='text/javascript' src='js/addfield.js'></script>
    <script type='text/javascript' src='js/changebackground.js'></script>
    <script type='text/javascript' src='magic.js'></script>
</body>
</html>

magic.js是处理表单

的脚本
$(document).ready(function() {
$("#submit_button").click(function(e) {
e.preventDefault();
var game = $("#game").val();
var question = $("#question").val();
var option = $("#option[]").val();
var choice = $("#choice").val();

if (game == '' || question == '' || option == '' || choice == '') {
alert("Insertion Failed Some Fields are Blank....!!");
} else {
// Returns successful data submission message when the entered information is stored in database.
$.post("process.php", {
game1: game,
question1: question,
option1: option,
choice1: choice
}, function(data) {
alert(data);
$('#form')[0].reset(); // To reset form fields
});
}
});
});

process.php将数据添加到数据库中

<?php
//Include configuration file
include('includes/config.php');

//Define variables
$game2=$_POST['game'];
$question2=$_POST['question'];
$option2=$_POST['option'];
$choice2=$_POST['choice'];

//Generate random number
$rand_value=rand();

//Create temporary folder
mkdir($rand_value);

//Copy page of Ask Poll
copy('page.php', $rand_value . '/page.php');
rename($rand_value . '/page.php', $rand_value . '/index.php');

//Add data into database
mysql_connect($db_host, $db_username, $db_password) or die ("Errore di connessione!");
mysql_select_db($db_name) or die ("Impossibile selezionare database!");
$sql1="CREATE TABLE `" . $rand_value . "` (Question VARCHAR(200), Options VARCHAR(200), Choice   INT(11))";
mysql_query($sql1) or die ("Impossibile eseguire la query!");

//Count number of Options available
$count=count($option);

    for ($i=0; $i<($count-1); $i++)
    {
        ${$sql . $i}="INSERT INTO `" . $rand_value . "` (Question, Options, Choice) VALUES ('$question2', '$option2[$i]', '$choice2')";
        mysql_query(${$sql . $i});
    }   
?>

更新

我修复了magic.js addind preventDefault并修正了submit_button的按钮ID,但现在脚本没有将数据传递给process.php:(

4 个答案:

答案 0 :(得分:0)

默认情况下,单击输入提交会触发表单提交,因此如果您不希望发生这种情况,则可以阻止该行为。

例如,您可以避免使用输入提交并使用简单的<button>,这样就没有&#34;真实&#34;提交。

或者您可以在javascript上的点击处理程序中阻止输入提交的默认行为。

替换它:

$("#submit").click(function() {

用这个:

$("#submit").click(function(e) { 
e.preventDefault();

答案 1 :(得分:0)

您应该阅读有关ajax的更多信息。这里的问题是你仍然有正常的按钮形式,你用$ .post和普通的post方法发送数据。

使用此:

$("#submit").click(function(e) { 
   e.preventDefault();
   ...
}

答案 2 :(得分:0)

您可以通过从按钮标记中删除type =“submit”将按钮类型从提交按钮更改为简单按钮,这样就不需要e.preventDefault();,然后在jquery中为每个字段获取数据,如

var game = $("#game-group:selected").val();

并确保您的数据即将到来尝试提醒

alert(game); 
每个字段

答案 3 :(得分:0)

$("#submit_button").click(function(e) {
   //code
   return false;
}

返回false会阻止浏览器重定向到链接位置。

此问题已在此处得到解答: How to prevent buttons from submitting forms