使用Ajax将PHP的响应返回给Jquery [英] Return response from PHP to Jquery using Ajax
本文介绍了使用Ajax将PHP的响应返回给Jquery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用Jquery / AJAX和PHP提交要保存在MySQL数据库中的信息。
这是我到目前为止所做的:
I am submitting info to be saved in a MySQL database using Jquery/AJAX and PHP. This is what i've done so far:
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;
}
和我的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
?>
它成功地将信息保存到数据库但我甚至无法获得成功消息,更不用说了来自PHP的变量。我已经阅读了无数关于异步调用,回调函数和承诺的帖子,但我不知道如何才能使它工作。任何帮助将不胜感激。
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.
推荐答案
Jquery:(main.js文件)
Jquery: (main.js file)
$(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文件)
PHP (ajaxadd.php file)
<?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:
<!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>
这篇关于使用Ajax将PHP的响应返回给Jquery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文