我有一个PHP
文件,它接收从表单发布的数据。然后它将其发送到数据库。但是我需要获取这些变量并将它们放在JavaScript
中。我已经完成了以下操作,但是当记录应该存储php数据的变量时(在脚本文件中),它返回undefined
。
我做错了什么?我是所有语言的新手。这些文件都是独立的 - PHP
和脚本文件是外部文件。
SCRIPT:
$(function(){
var data1 = $("#username").val();
console.log(data1);
$.ajax({
type: "POST",
url: 'signUp.php',
data: ({data1}),
success: function(data) {
console.log("success");
}
});
});
PHP
if (isset($_POST['signup'])){
//The connection to the database
include_once 'databaseHandler.php';
//Gets the infomation submitted from the form
//Protects the database by converting everything to text...
//The database therefore cannot read the inputs as code
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
echo (".$user.");
HTML
<form action="signUp.php" method="POST">
<input id="usernameSignUp" type="text" name="username" placeholder="Username">
<br>
<input id="passwordSignUp" type="password" name="password" placeholder="Password">
<br>
<button class="BUTTON" type="submit" name="signup">SIGN UP</button>
</form>
答案 0 :(得分:0)
您永远不会设置post参数'signup'。反过来,这不会让你输入你的if结构,因此php不会给你什么。
尝试:
data:{
"username":$('usernameSignUp').val(),
"password":$('passwordSignUp').val(),
"signup":1,
}
答案 1 :(得分:0)
我认为,你不能正确发送变量。
var data1 = $("#usernameSignUp").val();
var data2 = $("#passwordSignUp").val();
$.ajax({
type: "POST",
url: 'signUp.php',
data: {signup:'1',username:data1,password:data2 },//Supose data1= username data, data2 = password data
success: function(data) {
console.log("success");
}
});
&#13;
答案 2 :(得分:0)
这里有很多错误,很难知道从哪里开始。
data1
的字段传递给服务器(它不寻找)id="username"
(不存在)为该字段指定输入值username
或password
的字段传递给PHP(它正在寻找)signup
的字段传递给PHP(在执行任何操作之前使用isset
进行测试)$user
的变量,您尚未对其进行定义你需要更像的东西:
$(function() {
$("form").on("submit", function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: 'http://example.com/signUp.php',
data: ({
signup: 1,
username: $("#usernameSignUp").val(),
password: $("#passwordSignUp").val()
}),
success: function(data) {
console.log("Success", data);
},
error: function(data) {
console.log("This is a cross origin request to a dummy URL, what did you expect");
}
});
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="signUp.php" method="POST">
<input id="usernameSignUp" type="text" name="username" placeholder="Username">
<br>
<input id="passwordSignUp" type="password" name="password" placeholder="Password">
<br>
<button class="BUTTON" type="submit" name="signup">SIGN UP</button>
</form>
&#13;
然后有一些不好的做法但不会直接影响代码的工作能力。
mysqli_real_escape_string
代替placeholders。