В моем приложении у меня есть индексная страница с именем Contacts.html. У меня есть форма newContactForm.php, которую я показываю на странице Contacts.html с помощью функции ajax. Когда пользователь вводит данные в форму, пресса передает его, используя действие формы для отправки данных и функции ajax, называемой insert. функция insert принимает данные и отправляет их на newContact.php, который сохраняет данные в моей таблице базы данных. функция insert (onreadystatechange) запускает функцию ajax, называемую showGroup, которая отображает все контакты в базе данных на странице Contacts.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 used to solve an Internet Explorer cache issue
var nocache = 0;
function insert()
{
// 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 = showGroup;
http.send(null);
}
function showGroup(str)
{
document.getElementById("content01").innerHTML="";
if (str=="")
{
document.getElementById("content01").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("content01").innerHTML=xmlhttp.responseText;
document.getElementById("content02").innerHTML = "";
}
}
xmlhttp.open("GET","getGroup.php?contactGroup="+str,true);
xmlhttp.send();
}
мой файл newContact.php:
<!-- Include Database connections info. -->
<?php include('config.php'); ?>
<?php
//If the values are set (i.e the txt fields/radio button are filled in then run the sql insert statement to add the contact.
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"] ;
//SQL insert statement used to add the user entered data to the database table.
$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 if the fields do not contain data then display this error message.
else
{
echo 'Error! Please fill all fileds!';
}
?>
Мой newContactForm.php файл:
<!--This line of code is used to direct the "form action='javascript:insert()' to the 'insert' function located in the mentioned .js file"-->
<script src="ajax_framework.js" language="javascript"></script>
<?php $addContact = $_GET['addContact']; //index which sends new contact form to the html page via ajax function "showAddContact" which is located in the ajax.js file.
//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 id='newFname' name='newFname' type='text' size'20'></input></td>";
echo "</tr>";
echo "<tr>";
echo "<td>Last Name:</td><td><input id='newLname' name='newLname' type='text' size'20'></input></td>";
echo "</tr>";
echo "<tr>";
echo "<td>Phone Number:</td><td><input id='newPhone' name='newPhone' type='text' size'12'></input></td>";
echo "</tr>";
echo "<td>Email Address:</td><td><input id='newEmail' name='newEmail' type='text' size'30'></input></td>";
echo "</tr>";
echo "<tr>";
echo "<td>Postal Address:</td><td><input id='newAddress' name='newAddress' type='text' size'65'></input></td>";
echo "</tr>";
echo "<td>Group:</td><td> <input id='group' type='radio' name='group'/>No Group <input id='group' type='radio' name='group'/>Friend";
echo "<input id='group' type='radio' name='group'/>Colleagues <input id='group' type='radio' name='group'/>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>";
?>
привет, спасибо за это, я добавил значения к своим переключателям. У меня была непредвиденная ошибка, я не знаю, почему, поскольку я не изменил какой-либо другой код, но теперь, когда я нажимаю кнопку «Отправить», он не работает, а затем проверяет элемент страницы, на котором говорит консоль «Uncaught ReferenceError: insert is not defined», все соответствующие код должен быть выше, я выписал свою функцию вставки, и я правильно привязал ее к нужным местам, не уверен, почему это происходит. – Corey