将表单数据写入MySQL而不刷新页面

时间:2011-11-18 15:57:21

标签: php jquery mysql ajax

我正在尝试创建一个页面,当单击按钮时会显示一个表单。然后我希望用户在该表单中输入信息并单击提交按钮。我希望将此信息提交到MySQL数据库,而无需刷新/离开此页面。

我搜索了互联网,似乎我必须使用AJAX和jQuery来做这件事,但问题是我根本不知道其中任何一个。我试图按照我在几个网站上找到的示例和教程,但我无法让它们工作。

我已经创建了表单。它的代码如下。

<form name="classroom" method="post">
    <fieldset>
        <legend>Enter New MCP Information</legend>
        <label for="date">Date:</label>
        <input type="text" size="26" name="date" value="yyyy-mm-dd" onclick="this.value=''"onfocus="this.select()" onblur="this.value=!this.value?'yyyy-mm-dd':this.value;">

        <p>     
            <label for="objective">Objective:</label>
            <textarea name="objective" rows="3" cols="20" wrap="virtual"></textarea>
        <p>

        <label for="questions">Essential Questions:</label>
        <textarea name="questions" rows="2" cols="20" wrap="virtual"></textarea>

        <p>     
            <label for="criteria">Criteria for Success:</label>
            <textarea name="criteria" rows="2" cols="20" wrap="virtual" onclick="this.value=''"onfocus="this.select()">Must be separated by commas.</textarea>
        <p>

        <label for="agenda">Agenda:</label>
        <textarea name="agenda" rows="2" cols="20" wrap="virtual" onclick="this.value=''"onfocus="this.select()" >Must be separated by commas.</textarea>

        <p class="submit"><input type="submit" class="submit" value="Submit"></p>
    </fieldset>
</form>

我用来编写表单数据的php脚本如下。 (我故意遗漏了所有数据库连接和查询信息。一切正常)。

    <?php

$day=addslashes($_POST['date']);
$objective=addslashes($_POST['objective']);
$questions=addslashes($_POST['questions']);
$criteria=addslashes($_POST['criteria']);
$agenda=addslashes($_POST['agenda']);

$connnect = mysql_connect("database","user","password");
        if (!$connnect)
        {
        die('Could not connect: ' . mysql_error());
        }

        mysql_select_db("databasename") or die(mysql_error());      

mysql_query("INSERT INTO mcp (Date, TPO, Questions, Criteria, Agenda)
    VALUES ('$day', '$objective', '$questions', '$criteria', '$agenda')")
    or die(mysql_error()); 
?>

5 个答案:

答案 0 :(得分:3)

您需要在表单提交事件后运行ajax调用:

    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">
        $(function() {
            $('form').bind('submit', function(){
                $.ajax({
                    type: 'post',
                    url: "/path-to-php-file",
                    data: $("form").serialize(),
                    success: function() {
                        alert("form was submitted");
                    }
                });
                return false;
            });
        });
    </script>

现在,只有在提交表单时才会运行ajax调用,而不是在页面的开头。

答案 1 :(得分:1)

jQuery中的ajax()方法将为您解决此问题:

<script type="text/javascript" src="path/to/jquery.js"></script>
<script type="text/javascript">
    $(function() {
        $.ajax({
            type: 'POST',
            url: "mypage.php",
            data: $("FORM").serialize(),
            success: function() {
                alert("It worked!");
            }
        });
    });
</script>

您只需要创建mypage.php来处理帖子数据,然后将其插入数据库。

请点击以下链接,详细了解.ajax().serialize()

答案 2 :(得分:1)

我不是网络开发人员,所以jQuery的答案可能比这个更有意义。但如果你愿意,这里有一些不使用jQuery的页面的代码。

该页面包含一个带有单个textArea和一个按钮的表单。与按钮关联的onClick从textArea获取值并调用javascript函数来创建对php页面的请求。

PHP页面运行数据库逻辑,并返回HTML格式的结果表。

然后脚本获取结果并替换表单下面的内容。

<html>
<head>
    <script type="text/javascript">
function showResult(str)
{
    if (str=="")
    {
        document.getElementById("txtHint").innerHTML="";
        return;
    }

    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
        }
        else
        {
            document.getElementById("txtHint").innerHTML="ERROR";
        }
    }
    xmlhttp.open("GET","getQuery.php?q="+str,true);
    xmlhttp.send();
}
</script>
</head>
<body>

<form>
    <textarea name="thequery" cols=60 rows=6>SHOW TABLES;</textarea>
    <input type="button" value="Query" onClick="showResult(thequery.value)"/>
</form>
<br />
<div id="txtHint"><b>Query results will be listed here</b></div>

</body>
</html>

要修复字符编码,我在PHP页面的输入中使用以下行:

$query=$_GET["q"];
$query=stripslashes($query);

这是用于运行任何SQL查询并返回结果的格式化表的完整PHP代码。安全性很差,但对测试很有帮助。

<?php

/* set the database to connect to, the user, and the password */
$username="";
$password="";
$database="";
/* Here's the actual SQL query this page will run to get the data to display */
$query=$_GET["q"];

$query=stripslashes($query);

/* create a connection to the sql server with these credentials */
mysql_connect(localhost,$username,$password);

/* now connect to the specific database */
mysql_select_db($database) or die( "Unable to select database");

/* run the query we specified above - we get a "result set" */
$result=mysql_query($query);

if ($result) {

    /* you can call some mysql functions on the result set to get information. */
    /* here, we ask it how many rows were returned. */
    $numrows=mysql_numrows($result);

    /* ... and how many fields */
    $numcols=mysql_num_fields($result);

    /* This next block of code formats the result into a HTML table. */

    /* Start by defining a table. Bad formatting practices, but whatever. */
    print "<table width=600 border=1>\n";

    /* print column headings in bold */
    print "<tr>\n";
    for ($i = 0; $i < $numcols; $i++) {
        $colname = mysql_field_name($result, $i);
        print "\t<td><b>$colname</b></td>\n";
    }
    print "</tr>\n";

    /* Then fetch each row one-by-one and store it in $get_info.*/
    while ($get_info = mysql_fetch_row($result)){
        /* Everything between the { and } of the while loop will be run PER row */
        /* So start a HTML table row */
        print "<tr>\n";
        /* Now loop over all "fields", or, columns */
        /* this is the same as the while loop above, but now we take the 
           individual row and loop over its fields (as opposed to taking
           the entire result set and looping over its rows)*/
        foreach ($get_info as $field)
            /* start HTML column, print the data and then close the column*/
            print "\t<td>$field</td>\n";
        /* And close the HTML table row */
        print "</tr>\n";
        /* End the while loop */
    }
    /* Close the HTML table */
    print "</table>\n";

} else {
    print 'Invalid Query: ' . mysql_error();
}

/* And close the connection */
mysql_close();
/* this ends our php script block, so everything after it shows up normally. */
?>

答案 3 :(得分:0)

您可以使用jquery的ajax.serialize

$.ajax({
url:'/path',
type:'POST'
data:$("form").serialize(),
success:function(data){
//success handler code
},
error:function(jxhr){
console.log(jxhr.responseText);
}
});

答案 4 :(得分:-1)

是的JavaScript是一个很好的答案。 如果你想在这种情况下使用jQuery,我认为这是一个很好的选择,搜索jQuery Form Plugin(http://jquery.malsup.com/form/)这是一个很好的帮助。