简体   繁体   中英

Write form data to MySQL without page refresh

I'm trying to create a page where when a button is clicked a form displays. Then I want the user to input information into that form and click a submit button. I want this information to be submitted to a MySQL database without refreshing/leaving this page.

I've searched the internet and it seems like I have to use AJAX and jQuery to do this, but the problem is I don't know either of those at all. I've tried to follow examples and tutorials I've found on several sites, but I can't get any of them to work.

I have the form created already. The code for it is below.

<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>

The php script I'm using to write the form data is below. (I left out all the database connection and query info on purpose. It all works fine).

    <?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()); 
?>

You'll need to run the ajax call after the form submit event:

    <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>

The ajax call will now run only when the form is submitted, not at the start of the page.

The ajax() method in jQuery will take care of this for you:

<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>

You'll just need to create the mypage.php to deal with the post data, and insert it into your database.

Follow these links for further information about .ajax() and .serialize()

I'm not a web developer, so the jQuery answers might be more relevant than this one. But if you like, here's some code for a page that doesn't use jQuery.

The page has a form with a single textArea and a button. The onClick associated with the button takes the value from the textArea and calls the javascript function to create a request to a php page.

The PHP page runs the DB logic, and returns the HTML-formatted result table.

The script then takes the result and replaces the content below the form.

<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>

To fix the character encoding, I use the following line on the input in the PHP page:

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

Here's the full PHP code for running any SQL query and returning a formatted table of the results. Horrible for security, but good for testing.

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

you can use jquery's ajax and .serialize

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

Yes JavaScript is the great Answer. If you want to use jQuery in this case a good choice i think, search for the jQuery Form Plugin (http://jquery.malsup.com/form/) this is a great help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM