我正在尝试使用js ajax在db中插入多个数据,但它无法正常工作,当我尝试仅插入一个数据时,它正在成功运行
这是我的indexa.php
<html>
<head>
<script type="text/javascript">
function insert() {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else{
xmlhttp = new ActionXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('success_failed_msg').innerHTML = xmlhttp.responseText;
} else {
console.log("faliled");
}
}
parameters = 'first_name='+document.getElementById('firstName').value;
console.log(parameters);
xmlhttp.open('POST','insert.inc.php',true);
xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xmlhttp.send(parameters);
}
</script>
</head>
<body>
First Name : <input type="text" id="firstName"><br/><br/>
Last Name : <input type="text" id="lastName"><br/><br/>
Username : <input type="text" id="userName"><br/><br/>
Password : <input type="password" id="password"><br/><br/>
Re-type Password : <input type="password" id="retypePassword"><br/><br/>
<input type="button" value="Submit" onclick="insert()">
<div id="success_failed_msg"></div>
</body>
</html>
我的include.inc.php
if (isset($_POST['first_name'])) {
$firstname = $_POST['first_name'];
if (!empty($firstname)) {
$insert_select = "INSERT INTO ajax_member_data(`first_name`) VALUES('".mysqli_real_escape_string($db_connect,$firstname)."')";
if ($insert_query_run = mysqli_query($db_connect,$insert_select)) {
echo 'Data inserted successfully';
} else {
echo 'Failed';
}
} else {
echo 'Please enter the value';
}
}
当我尝试这个脚本时
<script type="text/javascript">
function insert() {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else{
xmlhttp = new ActionXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('success_failed_msg').innerHTML = xmlhttp.responseText;
} else {
console.log("faliled");
}
}
parameters = 'first_name='+document.getElementById('firstName').value'&last_name='+document.getElementById('lastName').value'&username='+document.getElementById('userName').value'&password='+document.getElementById('password').value'&retype_password='+document.getElementById('retypePassword').value;
console.log(parameters);
xmlhttp.open('POST','insert.inc.php',true);
xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xmlhttp.send(parameters);
}
</script>
我的include.inc.php
if (isset($_POST['first_name']) && isset($_POST['last_name']) && isset($_POST['username']) && isset($_POST['password']) && isset($_POST['retype_password'])) {
$firstname = $_POST['first_name'];
$lastname = $_POST['last_name'];
$usrname = $_POST['username'];
$password = $_POST['password'];
$retype_password = $_POST['retype_password'];
if (!empty($firstname) && !empty($lastname) && !empty($usrname) && !empty($password) && !empty($retype_password)) {
$insert_select = "INSERT INTO ajax_member_data(`first_name`,`last_name`,`user_name`,`password`) VALUES('".mysqli_real_escape_string($db_connect,$firstname)."', '".mysqli_real_escape_string($db_connect,$lastname)."', '".mysqli_real_escape_string($db_connect,$usrname)."', '".mysqli_real_escape_string($db_connect,$password)."')";
if ($insert_query_run = mysqli_query($db_connect,$insert_select)) {
echo 'Data inserted successfully';
} else {
echo 'Failed';
}
} else {
echo 'Please enter the value';
}
}
答案 0 :(得分:2)
您尚未正确完成连接。见这里,
parameters = 'first_name='+document.getElementById('firstName').value'&last_name='+document.getElementById('lastName').value'&username='+document.getElementById('userName').value'&password='+document.getElementById('password').value'&retype_password='+document.getElementById('retypePassword').value;
^ missing + ^ missing + ^ missing + ^ missing +
应该是,
parameters = 'first_name='+document.getElementById('firstName').value+'&last_name='+document.getElementById('lastName').value+'&username='+document.getElementById('userName').value+'&password='+document.getElementById('password').value+'&retype_password='+document.getElementById('retypePassword').value;
旁注:了解prepared statements因为您的查询现在容易受到SQL注入的影响。另请参阅how you can prevent SQL injection in PHP。
答案 1 :(得分:2)
传递参数时缺少加号(+)。请更改您的代码,如下所示:
旧代码:
parameters = 'first_name='+document.getElementById('firstName').value'&last_name='+document.getElementById('lastName').value'&username='+document.getElementById('userName').value'&password='+document.getElementById('password').value'&retype_password='+document.getElementById('retypePassword').value;
新代码:(在需要的地方添加加号(+))
parameters = 'first_name='+document.getElementById('firstName').value + '&last_name='+document.getElementById('lastName').value + '&username='+document.getElementById('userName').value + '&password='+document.getElementById('password').value + '&retype_password='+document.getElementById('retypePassword').value;
答案 2 :(得分:2)
如果用表单包装输入字段并使用jQuery序列化可能更容易。
示例HTML:
<form>
First Name : <input type="text" id="firstName"><br/><br/>
Last Name : <input type="text" id="lastName"><br/><br/>
Username : <input type="text" id="userName"><br/><br/>
Password : <input type="password" id="password"><br/><br/>
Re-type Password : <input type="password" id="retypePassword"><br/><br/>
<input type="button" value="Submit">
<div id="success_failed_msg"></div>
</form>
示例JS:
//you can use the var sending to avoid
// more than one request at the same time
var sending = false;
$('form').on('submit', function(ev){
ev.preventDefault();
if (!sending) {
$.ajax({
url: 'insert.inc.php',
method: 'post',
dataType: 'json',
data: $('form').serialize(),
cache: false,
beforeSend: function() {
//here you can show an ajax loading icon
sending = true;
},
success: function(response){
//here you can show a success message and check if the
//response is correct
//response object depends on the server side response
if (response.success || response.success === 'true') {
//show success message...
} else {
//show error message...
}
},
error: function(err){
//here you can show an error message
},
complete: function(){
//here you can hide the ajax loading icon
sending = false;
}
});
}
});
来自jQuery的文档:
您可以从服务器端格式化json响应
json_encode(用这个你将php数组“转换”为js对象)http://php.net/manual/en/function.json-encode.php
header('Content-Type: application/json');
这个应用会知道给出了什么类型的回复
您可以在此处阅读有关json和ajax的更多信息:
关于如何在Firefox上查看请求的教程:https://developer.mozilla.org/en-US/docs/Tools/Network_Monitor
在Chrome上:https://developers.google.com/web/tools/chrome-devtools/network-performance/resource-loading
答案 3 :(得分:1)
var sending = false;
$('form').on('submit', function(ev){
ev.preventDefault();
if (!sending) {
$.ajax({
url: 'insert.inc.php',
method: 'post',
dataType: 'json',
data: $('form').serialize(),
cache: false,
beforeSend: function() {
console.log("processing");
sending = true;
},
success: function(response){
if (response.success || response.success === 'true') {
('#success_failed_msg').text(response);
} else {
('#success_failed_msg').text('response failed');
}
},
error: function(err){
('#success_failed_msg').text(err);
},
complete: function(){
console.log('process complete');
sending = false;
}
});
}
});