提交表单刷新页面 [英] Submit form refresh the page

查看:108
本文介绍了提交表单刷新页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个index.html

I have an 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="submitForm" id="submitForm" action="process.php" 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>

这是AJAX功能到一个js脚本

An AJAX function into a js script

// magic.js
$(document).ready(function() {

// process the form
$('form').submit(function(event) {

    $('.form-group').removeClass('has-error'); // remove the error class
    $('.help-block').remove(); // remove the error text

    // get the form data
    // there are many ways to get this data using jQuery (you can use the class or id also)
    var formData = {
        'game'              : $('input[name=game]').val(),
        'question'          : $('input[name=question]').val(),
        'option'            : $('input[name=option[]]').val(),
        'choice'            : $('input[name=choice]').val()
    };

    // process the form
    $.ajax({
        type        : 'POST', // define the type of HTTP verb we want to use (POST for our form)
        url         : 'process.php', // the url where we want to POST
        data        : formData, // our data object
        dataType    : 'json', // what type of data do we expect back from the server
        encode      : true
    })
        // using the done promise callback
        .done(function(data) {

            // log data to the console so we can see
            console.log(data); 

            // here we will handle errors and validation messages
            if ( ! data.success) {

                // handle errors for game ---------------
                if (data.errors.game) {
                    $('#game-group').addClass('has-error'); // add the error class to show red input
                    $('#game-group').append('<div class="help-block">' + data.errors.game + '</div>'); // add the actual error message under our input
                }

                // handle errors for question ---------------
                if (data.errors.question) {
                    $('#question-group').addClass('has-error'); // add the error class to show red input
                    $('#question-group').append('<div class="help-block">' + data.errors.question + '</div>'); // add the actual error message under our input
                }

                // handle errors for option ---------------
                if (data.errors.option) {
                    $('#option-group').addClass('has-error'); // add the error class to show red input
                    $('#option-group').append('<div class="help-block">' + data.errors.option + '</div>'); // add the actual error message under our input
                }

                // handle errors for choice ---------------
                if (data.errors.choice) {
                    $('#choice-group').addClass('has-error'); // add the error class to show red input
                    $('#choice-group').append('<div class="help-block">' + data.errors.choice + '</div>'); // add the actual error message under our input
                }


            } else {

                // ALL GOOD! just show the success message!
                $('form').append('<div class="alert alert-success">' + data.message + '</div>');

                // usually after form submission, you'll want to redirect
                // window.location = '/thank-you'; // redirect a user to another page

            }
        })

        // using the fail promise callback
        .fail(function(data) {

            // show any errors
            // best to remove for production
            console.log(data);
        });

    // stop the form from submitting the normal way and refreshing the page
    event.preventDefault();
});

});

和一个process.php

And a process.php

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

//Define variables
$question=$_POST['question'];
$game=$_POST['game'];
$option=$_POST['option'];
$choice=$_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 ('$question', '$option[$i]', '$choice')";
        mysql_query(${$sql . $i});
    }   
?>

但是,当我发送的形式,页面重定向我process.php

But when i send the form, the page redirect me to process.php

我不希望这样的网站刷新页面

I don't want that the site refresh the page

修改

沃纳,我跟着你的建议增加preventDefault,但它不工作:(

Werner, I followed your suggestion adding preventDefault but it doesn't work :(

推荐答案

您的magic.js文件中的语法错误。你应该让你的控制台启动,看它是否有错误。

You have an syntax error in your magic.js file. You should start by enabling your console and watch it for errors.

Uncaught Error: Syntax error, unrecognised expression: input[name=option[]]

这是我能读的时候pressing提交按钮,然后躲开后停止提交。

That is what I could read when pressing the submit button and then Escape just after that to stop the submit.

问题出在哪里,你创建FORMDATA的一部分。 (你实际上可以创造出很多与 http://api.jquery.com/serialize/ 更容易)

The problem lies the part where you create your formData. (Which you can actually create a lot easier with http://api.jquery.com/serialize/)

您对线15注意额外的支架一个错字?你不应该添加,即使他们在外地的名字括号。我建议你​​使用序列化的解决方案,或者至少使用它们的ID选择字段(这是它们是什么,基本上是)。

You have a typo on line 15. Notice the extra brackets? You are not supposed to add the brackets even though they are in the name of the field. I recommend you to use the Serialize solution or at least select the fields using their IDs (that's what they are basically for).

$('input[name=option[]]') // Not valid
$('#option') // Better way to select a field

希望这将让你在正确的方向。

Hope this will get you in the right direction.

这篇关于提交表单刷新页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆