在输入字段上按Enter键以更新数据库

时间:2014-02-15 12:10:43

标签: php jquery ajax

我创建了数据库,我已连接到它,我从中获取数据作为输入字段。当我编辑任何单个输入字段并按ENTER时,我想更新我的数据库。我需要使用AJAX将数据发送到数据库。 这是我的代码:

的index.html

   <script language="javascript" type="text/javascript">
    <!-- 
    //Browser Support Code
    function ajaxFunction(){
        var ajaxRequest;  // The variable that makes Ajax possible!

        try{
            // Opera 8.0+, Firefox, Safari
            ajaxRequest = new XMLHttpRequest();
        }catch (e){
            // Internet Explorer Browsers
        try{
            ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
        }catch (e) {
        try{
            ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
        }catch (e){
            // Something went wrong
            alert("Your browser broke!");
            return false;
           }
        }
    }
    // Create a function that will receive data 
    // sent from the server and will update
    // div section in the same page.
      ajaxRequest.onreadystatechange = function(){
       if(ajaxRequest.readyState == 4){
          var ajaxDisplay = document.getElementById('ajaxDiv');
          ajaxDisplay.innerHTML = ajaxRequest.responseText;
       }
     }
     // Create variables to pass
     var id;
     var firstname ;
     var lastname ;
     var age ;

     var queryString = "?firstname=" + firstname ;
     queryString +=  "&id=" + id + "&lastname=" + lastname + "&age=" + age;
     ajaxRequest.open("GET", "ajax-example.php" + queryString, true);
     ajaxRequest.send(null); 
    }
    //-->
    </script>
    <form name='myForm'>
    <input type='button' onclick='ajaxFunction()' value='Get Database Data'/>
    </form>
    <div id='ajaxDiv' style="background-color:red">Your result will display here</div> 

这是 ajax-example.php

<?php
$dbhost = "localhost";
$dbuser = "****";
$dbpass = "****";
$dbname = "ajax_example";
//Connect to MySQL Server
mysql_connect($dbhost, $dbuser, $dbpass);
//Select Database
mysql_select_db($dbname) or die(mysql_error());
// Retrieve data from Query String
$id = $_GET['id'];  
$firstname = $_GET['firstname'];
$lastname = $_GET['lastname'];
$age = $_GET['age'];

//build query
$query = "SELECT * FROM ajax_example ";

//Execute query
$qry_result = mysql_query($query) or die(mysql_error());

//Build Result String
$display_string = "<table>";
$display_string .= "<tr>";
$display_string .= "<th>Id</th>";
$display_string .= "<th>Firstname</th>";
$display_string .= "<th>Lastname</th>";
$display_string .= "<th>Age</th>";
$display_string .= "</tr>";

// Insert a new row in the table for each person returned
while($row = mysql_fetch_array($qry_result)){
$display_string .= "<tr>";
$display_string .= "<td><input type='text' name='id' value='".$row['id']."'></td>";
$display_string .= "<td><input type='text' name='firstname'    value='".$row['firstname']."'></td>";
$display_string .= "<td><input type='text' name='lastname' value='".$row['lastname']."'></td>";
$display_string .= "<td><input type='text' name='age' value='".$row['age']."'> </td>";
$display_string .= "</tr>";

}
echo "Query: " . $query . "<br />";
$display_string .= "</table>";
echo $display_string;
?> 

我是初学者,所以也许我的代码不是很好。如果我有一些重大错误请告诉我。但现在我想要的一切都很好。

2 个答案:

答案 0 :(得分:0)

您可以尝试在按下时检测回车键,确保您还要检查当前聚焦的文本框。我并不是真的自称jQuery或Javascript,但这个脚本可以帮我检测密钥。 您可以进一步使用jQuery从文本框中检索值,并在AJAX代码中进一步使用它。

<script>
    var map = {13: false};
    $(document).keydown(function(e) {
        if (e.keyCode in map) {
            map[e.keyCode] = true;
            if (map[13]) {

             // You code here to fire when enter is detected
                }
            }
        }
    }).keyup(function(e) {
        if (e.keyCode in map) {
            map[e.keyCode] = false;
        }
    });
</script>

答案 1 :(得分:0)

您应该为表单提供一个ID并将其放在容器div中。看我做了一点调整

<div id="container">
    <form id="myform" name='myForm'>
        <input type="hidden" name="id" id="my_example_id"/>
        <input type="text" name="firstname" id="my_example_firstname"/>
         <input type="text" name="lastename" id="my_example_lastname"/>
        <input type="text" name="age" id="my_example_age"/>
    </form>
<div id='ajaxDiv' style="background-color:red">Your result will display here</div> 
</div>    

现在你可以通过它的id获取容器,看看是否按下了enter,如果是,则执行ajax查询并序列化表单(序列化意味着它会将所有数据推送到ajax)

$(function() {
$("#container").keypress(function (e) {
    if (e.which == 13) {
         e.preventDefault(); // this prevents the default action of a enter 
            $.post('ajax-example.php',$("#myform").serialize() ,  function(response) { 
$('#ajaxDiv').html(response); // this will echo any response from ajax file
        });
    }   
});
}); 

这应该可以解决问题

BR的