0

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;
    }
}
5
  • Why not using jQuery? Some things gets easier, ajax too.
    – jtheman
    Mar 7, 2013 at 23:29
  • This looks related: stackoverflow.com/questions/8233308/… Mar 7, 2013 at 23:29
  • This is for an assignment so I have to stick with doing it this way.
    – Corey
    Mar 7, 2013 at 23:30
  • Can you post a bit more code? For example, the HTML form and perhaps the full AJAX code? Sounds like you might just need to ensure your HTML syntax is correct, but it's hard to tell with so little code. Mar 7, 2013 at 23:30
  • I've added relevant code for the issue, thanks for your responses, still looking for an answer though!
    – Corey
    Mar 7, 2013 at 23:35

2 Answers 2

0

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);
1
  • Thank-you very much, your code worked to solve the issue i had.
    – Corey
    Mar 8, 2013 at 1:00
0

You can try jQuery to solve this.

Include jQuery on your HTML by adding this line to your <head> section:

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

Then use a jquery selector to get the value you need by replacing the following line in your AJAX file

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

by these:

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

Make sure the radio inputs have the property name. Disregard the id, since it is not useful for the purpose at hand. Also, set your own value when no button is checked (in the case you don´t leave a default value for it).

You can read also at https://stackoverflow.com/a/2564019/772020.

Please tell us if it helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.