簡體   English   中英

將表單數據寫入MySQL而無需刷新頁面

[英]Write form data to MySQL without page refresh

我正在嘗試創建一個頁面,單擊某個按鈕時將顯示一個表單。 然后,我希望用戶將信息輸入該表單,然后單擊“提交”按鈕。 我希望將這些信息提交給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()); 
?>

您需要在表單提交事件之后運行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調用將僅在提交表單時運行,而不是在頁面開始時運行。

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()的更多信息

我不是網絡開發人員,因此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);

這是完整的PHP代碼,用於運行任何SQL查詢並返回結果的格式化表格。 可怕的安全性,但對測試有益。

<?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. */
?>

您可以使用jquery的ajax.serialize

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

是的,JavaScript是一個很好的答案。 我認為,如果您想在這種情況下使用jQuery是一個不錯的選擇,請搜索jQuery Form Plugin(http://jquery.malsup.com/form/),這是一個很大的幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM