通过ajax向数据库添加单选按钮选择


Add radio button selection to database via ajax?

当我测试我的表单时,它成功地将数据添加到我的数据库表中,但单选按钮选择始终是"Ungrouped",这是组中的第一个单选按钮。我试着给他们单独的id,但在我的ajax.js文件我的函数使用这个:

var group = encodeURI(document.getElementById('group').value);

这意味着现在我正在调用一个不存在的id(我认为这就是发生的事情)。我怎样才能使它,当我的ajax函数调用单选按钮选择,为了把它发送到我的php文件,将它添加到数据库,它选择正确的一个。

我希望这是有意义的,如果需要更多的细节,我可以补充更多。

这是我的形式,它是在一个php文件,因为它必须是每我的分配(必须用ajax调用):

<!-- Include AJAX Framework -->
<script src="ajax.js" language="javascript"></script>
<?php   $addContact = $_GET['addContact']; //index which sends new contact form to the html page via ajax function.
//form which users can use to enter the details of a new contact to add to the database.
echo "Add A Contact:";
echo "<form action='javascript:insert()' method='get'>";
echo "<table>";
echo "<tr>";
echo "<td>First Name:</td><td><input name='newFname' type='text' id='newFname' value='' size'20'></input></td>";
echo "</tr>";
echo "<tr>";
echo "<td>Last Name:</td><td><input name='newLname' type='text' id='newLname' value='' size'20'></input></td>";
echo "</tr>";
echo "<tr>";
echo "<td>Phone Number:</td><td><input name='newPhone' type='text' id='newPhone' value='' size'20'></input></td>";
echo "</tr>";
echo "<td>Email Address:</td><td><input name='newEmail' type='text' id='newEmail' value='' size'20'></input></td>";
echo "</tr>";
echo "<tr>";
echo "<td>Postal Address:</td><td><input name='newAddress' type='text' id='newAddress' value='' size'20'></input></td>";
echo "</tr>";
echo "<td>Group:</td><td><input type='radio' id='Ungrouped' name='group' value='Ungrouped'>No Group <input type='radio' id='Friends' name='group' value='Friends'>Friend";
echo "<input type='radio' id='Colleagues' name='group' value='Colleagues'>Colleagues <input type='radio' id='Family' name='group' value='Family'>Family";
echo "</table>";
//submit button that submits the contact information to an ajax function.
echo "<input type='submit' name='Submit' value='Add Contact'/>";
echo "</FORM>";

这是我的php文件,连接到我的数据库,并保存数据到它与插入语句:

<!-- Include Database connections info. -->
<?php include('config.php'); ?>
<?php
if(isset($_GET['newFname']) && isset($_GET['newLname']) && isset($_GET['newPhone']) && isset($_GET['newEmail']) && isset($_GET['newAddress']) && isset($_GET['group'])) 
{
    $newFname = $_GET["newFname"] ;
    $newLname = $_GET["newLname"] ;
    $newPhone = $_GET["newPhone"] ;
    $newEmail = $_GET["newEmail"] ;
    $newAddress = $_GET["newAddress"] ;
    $group = $_GET["group"] ;
    $insertContact_sql = "INSERT INTO `test`.`contacts` (`newFname`, `newLname`, `newPhone`, `newEmail`, `newAddress`, `group`) VALUES ('{$newFname}' , '{$newLname}' , '{$newPhone}' , '{$newEmail}' , '{$newAddress}' , '{$group}')";
    $insertContact= mysql_query($insertContact_sql) or die(mysql_error());
} 
else 
{ 
    echo 'Error! Please fill all fileds!';
}
?>

这是我的ajax(其相关的ajax代码,还有其他功能(即调用我的表单到我的html页面的功能),但它们不适用于这个问题的工作):

function createObject() 
{
    var request_type;
    var browser = navigator.appName;
    if(browser == "Microsoft Internet Explorer")
    {
        request_type = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else    
    {
        request_type = new XMLHttpRequest();
    }
    return request_type;
}
var http = createObject();
//value solve an Internet Explorer cache issue
var nocache = 0;
function insert() 
{
    // Optional: Show a waiting message in the layer with ID login_response
    document.getElementById('content02').innerHTML = "Just a second..."
    // Required: verify that all fileds is not empty. Use encodeURI() to solve some issues about character encoding.
    var newFname= encodeURI(document.getElementById('newFname').value);
    var newLname = encodeURI(document.getElementById('newLname').value);
    var newPhone = encodeURI(document.getElementById('newPhone').value);
    var newEmail = encodeURI(document.getElementById('newEmail').value);
    var newAddress = encodeURI(document.getElementById('newAddress').value);
    var group = encodeURI(document.getElementById('group').value);
    // Set te random number to add to URL request
    nocache = Math.random();
    // Pass the login variables like URL variable
    http.open('get', 'newContact.php?newFname='+newFname+'&newLname=' +newLname+'&newPhone=' +newPhone+'& newEmail=' +newEmail+'&newAddress=' +newAddress+'&group=' +group+'&nocache = '+nocache);
    http.onreadystatechange = insertReply;
    http.send(null);
    }
    function insertReply() {
    if(http.readyState == 4)
    { 
        var response = http.responseText;
        // else if login is ok show a message: "Site added+ site URL".
        document.getElementById('content02').innerHTML = 'Your contact was successfully added!'+response;
    }
}

您需要做的是遍历所有单选按钮并选择已选中的按钮。然后,您可以在AJAX请求中发送该单选按钮的值。像这样:

    var radios = document.getElementsByName('group');
    var selectedRadio = null;
    for (var i = 0; i < radios.length; i++) {
        if (radios[i].checked === true) {
            selectedRadio = radios[i]; 
            break;
        }
    }
    var group = encodeURI(selectedRadio.value);

你可以尝试使用jQuery来解决这个问题。

通过将这一行添加到您的<head>部分,在HTML中包含jQuery:

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.pack.js"></script>

然后使用jquery选择器通过替换AJAX文件

中的以下行来获得所需的值
var group = encodeURI(document.getElementById('group').value);
由这些:

var groupValue = ($("input[name='group']:checked") != null) ? $("input[name='group']:checked").value : "NOT_CHECKED";
var group = encodeURI(groupValue);

确保无线电输入具有name属性。忽略id,因为它对手头的目的没有用处。另外,当没有按钮被选中时,设置自己的值(在没有为它留下默认值的情况下)。

你也可以在https://stackoverflow.com/a/2564019/772020上阅读。

如果有帮助请告诉我们