Skip to content
Advertisement

Add radio button selection to database via ajax?

When I test my form it adds data successfully to my database table but the radio button selection is always “Ungrouped” which is the first radio button in the group. I tried giving them separate id’s, but in my ajax.js file my function uses this:

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

Which means that now I am calling an id that doesnt exist (I think thats whats happening). How can I make it so that when my ajax function calls the radio button selection, in order to send it to my php file that adds it to the database, it selects the right one.

I hope this makes sense, if more details is needed I can add more.

Here is my form, it is in a php file as it has to be per my assignment (must be called with 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>";

Here is my php file that connects to my database and saves the data to it with an insert statement:

<!-- 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!';
}

?>

Here is my ajax (its the relevant ajax code, there are other functions (i.e. the function that calls my form to my html page) but they don’t apply to the working out of this issue):

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

Advertisement

Answer

What you need to do is cycle through all the radio buttons and select the one that has been checked. You can then send the value for just that radio button in your AJAX request. Something like this:

    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);
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement