I am submitting info to be saved in a MySQL database using Jquery/AJAX and PHP. This is what i've done so far:
我使用Jquery / AJAX和PHP提交要保存在MySQL数据库中的信息。这是我到目前为止所做的:
function Addinfo() {
var ew = document.getElementById("ew").value;
var mw = document.getElementById("mw").value;
var dataString = 'ew1=' + ew + '&mw=' + mw;
if (ew == '' || mw == '') {
alert("Please Fill All Fields");
} else {
$.ajax({
type : "POST",
url : "ajaxadd.php",
data : dataString,
dataType : 'text',
cache : false,
})
.done(function (data) {
$('#message1').html(data);
})
}
return false;
}
and my PHP code:
和我的PHP代码:
<?php
$ew2 = $_POST['ew1'];
$mw2 = $_POST['mw1'];
$connection = mysql_connect("localhost", "root", "");
$db = mysql_select_db("tp", $connection);
if (isset($_POST['ew1'])) {
$query = mysql_query("insert into table(ew, mw) values ('$ew2', '$mw2')");
$addresult = mysql_query("SELECT * FROM `table` WHERE `ew` = '" . $_POST['ew1'] . "' ORDER BY `id` DESC LIMIT 1");
$aircraft = mysql_fetch_assoc($addresult);
echo $aircraft;
}
mysql_close($connection); // Connection Closed
?>
It saves the information to the database successfully but I can't even get a success message let alone a variable from the PHP. I have read countless posts about asynchronous calls, callback functions and promises but I somehow can't get this to work. Any help would be appreciated.
它成功地将信息保存到数据库中,但我甚至无法获得成功消息,更不用说来自PHP的变量了。我已经阅读了关于异步调用,回调函数和承诺的无数帖子,但我不知道怎么能让它工作。任何帮助,将不胜感激。
4 个解决方案
#1
0
Jquery: (main.js file)
Jquery:(main.js文件)
$(document).ready(function(){
$('.ajaxform').on('submit', function(e){
e.preventDefault();
$.ajax({
// give your form the method POST
type: $(this).attr('method'),
// give your action attribute the value ajaxadd.php
url: $(this).attr('action'),
data: $(this).serialize(),
dataType: 'json',
cache: false,
})
.success(function(response) {
// remove all errors
$('input').removeClass('error').next('.errormessage').html('');
// if there are no errors and there is a result
if(!response.errors && response.result) {
// success
// loop through result and append values in message1 div
$.each(response.result, function( index, value) {
$('#message1').append(index + ': ' + value + '<br/>');
});
} else {
// append the error to the form
$.each(response.errors, function( index, value) {
// add error classes
$('input[name*='+index+']').addClass('error').after('<div class="errormessage">'+value+'</div>')
});
}
});
});
});
PHP (ajaxadd.php file)
PHP(ajaxadd.php文件)
<?php
// assign your post value
$inputvalues = $_POST;
// assign result vars
$errors = false;
$returnResult = false;
$mysqli = new mysqli('host', "db_name", "password", "database");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
// escape your values
foreach ($inputvalues as $key => $value) {
if(isset($value) && !empty($value)) {
$inputvalues[$key] = htmlspecialchars( $mysqli->real_escape_string( $value ) );
} else {
$errors[$key] = 'The field '.$key.' is empty';
}
}
if( !$errors ) {
// insert your query
$mysqli->query("
INSERT INTO `table`(`ew`, `mw`)
values ('".$inputvalues['ew1']."', '".$inputvalues['mw']."')
");
// select your query
// this is for only one row result
$addresult = "
SELECT *
FROM `table`
WHERE `ew` = '".$inputvalues['ew1']."'
ORDER BY `id` DESC
LIMIT 1
";
if( $result = $mysqli->query($addresult) ) {
// collect results
while($row = $result->fetch_assoc())
{
// assign to new array
// make returnResult an array for multiple results
$returnResult = $row;
}
}
}
// close connection
mysqli_close($mysqli);
// print result for ajax request
echo json_encode(['result' => $returnResult, 'errors' => $errors]);
exit;
?>
HTML:
HTML:
<!doctype html>
<html class="no-js" lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>Ajax form submit</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<form class="ajaxform" action="ajaxadd.php" method="POST">
<input type="text" name="ew1" />
<input type="text" name="mw" />
<button type="submit">Submit via ajax</button>
</form>
<div id="message1"></div>
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.12.0.min.js"><\/script>')</script>
<script src="main.js"></script>
</body>
</html>
#2
0
$.ajax({
type: "POST",
url: "ajaxadd.php",
ew1:ew,
mw1:mw,
data: dataString,
dataType: 'text',
cache: false,
})
#3
0
In PHP code at the end where you
在PHP代码的最后你
echo $aircraft
change it to echo json_encode($aircraft);
and in AJAX fucntion where you mentioned
echo $飞机改变它以回应json_encode($飞机);在你提到的AJAX fucntion中
cache:false
include success:function(response){alert response;}
cache:false包括success:function(response){alert response;}
It will give your aircraft variable value in AJAX function. Good Luck!
它将为您的飞机提供AJAX功能的变量值。祝你好运!
#4
0
You should modify your php code as below instead of directly return mysql_fetch_assoc because it returns only the first row of your SQL result.
您应该修改您的PHP代码,而不是直接返回mysql_fetch_assoc,因为它只返回SQL结果的第一行。
<?php
$ew2 = $_POST['ew1'];
$mw2 = $_POST['mw1'];
$connection = mysql_connect("localhost", "root", "");
$db = mysql_select_db("tp", $connection);
if (isset($_POST['ew1']))
{
$result = array();
$query = mysql_query("insert into table(ew, mw) values ('$ew2', '$mw2')");
$addresult = mysql_query("SELECT * FROM `table` WHERE `ew` = '" . $_POST['ew1'] . "' ORDER BY `id` DESC LIMIT 1");
while($aircraft = mysql_fetch_assoc($addresult))
{
$result[] = $aircraft;
}
#echo $aircraft; // wait until whole result is collected
echo json_encode($result);
}
mysql_close($connection); // Connection Closed
?>
Also you should edit your javascript code as below;
你也应该编辑你的javascript代码如下;
function Addinfo() {
var ew = document.getElementById("ew").value;
var mw = document.getElementById("mw").value;
var dataString = 'ew1=' + ew + '&mw=' + mw;
if (ew == '' || mw == '') {
alert("Please Fill All Fields");
} else {
$.ajax({
type : "POST",
url : "ajaxadd.php",
data : dataString,
dataType : 'text',
cache : false,
success: function(data)
{
//$('#message1').html(data);
alert(data);
},
error: function(data)
{
alert("Error");
}
});
}
return false;
}
In addition advice you may check $connection and $db for successful initialization of your database connection and database selection, and again an advice for your php code your should use mysqli extension instead of mysql extension which deprecated. You can just replace mysql part of your calling methods with mysqli. Also @RakhalImming's advice is quite good for security of your code.
另外建议您可以检查$ connection和$ db以成功初始化数据库连接和数据库选择,并再次建议您的php代码应该使用mysqli扩展而不是不推荐使用的mysql扩展。你可以用mysqli替换你的调用方法的mysql部分。另外@ RakhalImming的建议对于代码的安全性非常有用。
#1
0
Jquery: (main.js file)
Jquery:(main.js文件)
$(document).ready(function(){
$('.ajaxform').on('submit', function(e){
e.preventDefault();
$.ajax({
// give your form the method POST
type: $(this).attr('method'),
// give your action attribute the value ajaxadd.php
url: $(this).attr('action'),
data: $(this).serialize(),
dataType: 'json',
cache: false,
})
.success(function(response) {
// remove all errors
$('input').removeClass('error').next('.errormessage').html('');
// if there are no errors and there is a result
if(!response.errors && response.result) {
// success
// loop through result and append values in message1 div
$.each(response.result, function( index, value) {
$('#message1').append(index + ': ' + value + '<br/>');
});
} else {
// append the error to the form
$.each(response.errors, function( index, value) {
// add error classes
$('input[name*='+index+']').addClass('error').after('<div class="errormessage">'+value+'</div>')
});
}
});
});
});
PHP (ajaxadd.php file)
PHP(ajaxadd.php文件)
<?php
// assign your post value
$inputvalues = $_POST;
// assign result vars
$errors = false;
$returnResult = false;
$mysqli = new mysqli('host', "db_name", "password", "database");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
// escape your values
foreach ($inputvalues as $key => $value) {
if(isset($value) && !empty($value)) {
$inputvalues[$key] = htmlspecialchars( $mysqli->real_escape_string( $value ) );
} else {
$errors[$key] = 'The field '.$key.' is empty';
}
}
if( !$errors ) {
// insert your query
$mysqli->query("
INSERT INTO `table`(`ew`, `mw`)
values ('".$inputvalues['ew1']."', '".$inputvalues['mw']."')
");
// select your query
// this is for only one row result
$addresult = "
SELECT *
FROM `table`
WHERE `ew` = '".$inputvalues['ew1']."'
ORDER BY `id` DESC
LIMIT 1
";
if( $result = $mysqli->query($addresult) ) {
// collect results
while($row = $result->fetch_assoc())
{
// assign to new array
// make returnResult an array for multiple results
$returnResult = $row;
}
}
}
// close connection
mysqli_close($mysqli);
// print result for ajax request
echo json_encode(['result' => $returnResult, 'errors' => $errors]);
exit;
?>
HTML:
HTML:
<!doctype html>
<html class="no-js" lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>Ajax form submit</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<form class="ajaxform" action="ajaxadd.php" method="POST">
<input type="text" name="ew1" />
<input type="text" name="mw" />
<button type="submit">Submit via ajax</button>
</form>
<div id="message1"></div>
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.12.0.min.js"><\/script>')</script>
<script src="main.js"></script>
</body>
</html>
#2
0
$.ajax({
type: "POST",
url: "ajaxadd.php",
ew1:ew,
mw1:mw,
data: dataString,
dataType: 'text',
cache: false,
})
#3
0
In PHP code at the end where you
在PHP代码的最后你
echo $aircraft
change it to echo json_encode($aircraft);
and in AJAX fucntion where you mentioned
echo $飞机改变它以回应json_encode($飞机);在你提到的AJAX fucntion中
cache:false
include success:function(response){alert response;}
cache:false包括success:function(response){alert response;}
It will give your aircraft variable value in AJAX function. Good Luck!
它将为您的飞机提供AJAX功能的变量值。祝你好运!
#4
0
You should modify your php code as below instead of directly return mysql_fetch_assoc because it returns only the first row of your SQL result.
您应该修改您的PHP代码,而不是直接返回mysql_fetch_assoc,因为它只返回SQL结果的第一行。
<?php
$ew2 = $_POST['ew1'];
$mw2 = $_POST['mw1'];
$connection = mysql_connect("localhost", "root", "");
$db = mysql_select_db("tp", $connection);
if (isset($_POST['ew1']))
{
$result = array();
$query = mysql_query("insert into table(ew, mw) values ('$ew2', '$mw2')");
$addresult = mysql_query("SELECT * FROM `table` WHERE `ew` = '" . $_POST['ew1'] . "' ORDER BY `id` DESC LIMIT 1");
while($aircraft = mysql_fetch_assoc($addresult))
{
$result[] = $aircraft;
}
#echo $aircraft; // wait until whole result is collected
echo json_encode($result);
}
mysql_close($connection); // Connection Closed
?>
Also you should edit your javascript code as below;
你也应该编辑你的javascript代码如下;
function Addinfo() {
var ew = document.getElementById("ew").value;
var mw = document.getElementById("mw").value;
var dataString = 'ew1=' + ew + '&mw=' + mw;
if (ew == '' || mw == '') {
alert("Please Fill All Fields");
} else {
$.ajax({
type : "POST",
url : "ajaxadd.php",
data : dataString,
dataType : 'text',
cache : false,
success: function(data)
{
//$('#message1').html(data);
alert(data);
},
error: function(data)
{
alert("Error");
}
});
}
return false;
}
In addition advice you may check $connection and $db for successful initialization of your database connection and database selection, and again an advice for your php code your should use mysqli extension instead of mysql extension which deprecated. You can just replace mysql part of your calling methods with mysqli. Also @RakhalImming's advice is quite good for security of your code.
另外建议您可以检查$ connection和$ db以成功初始化数据库连接和数据库选择,并再次建议您的php代码应该使用mysqli扩展而不是不推荐使用的mysql扩展。你可以用mysqli替换你的调用方法的mysql部分。另外@ RakhalImming的建议对于代码的安全性非常有用。