[英]submit post data using ajax to a php file
I have to submit only two value using ajax call to a php file. 我必须使用ajax调用只提交两个值到php文件。 The php file will handle data with $_POST[] function.
php文件将使用$ _POST []函数处理数据。 Problem is my ajax code not sending data properly so i am not getting any of result in console.log(result) function.
问题是我的ajax代码没有正确发送数据所以我没有得到任何结果在console.log(结果)函数。 How can i fix that?
我该如何解决这个问题? Any idea?
任何想法?
Jquery: jQuery的:
<script type="text/javascript">
$("#signup_submit").on( "click", function() {
//alert("foo");
var _username = "foo";
var _email = "test@gmail.com";
$.post("check.php", {username: _username, email: _email}, function(result){
console.log(result);
});
});
</script>
PHP: PHP:
$username = "";
$email = "";
if ($_POST["username"] && $_POST["email"]) {
$username = $_POST["username"];
$email = $_POST["email"];
}
if ($username != "" && $email != "") {
if (!username_exists($username) && !signup_email($signup_email)) {
json_encode("good");
}else{
json_encode("bad");
}
}
I've commented you the possible answer but I'll write it here to simplify. 我已经给你评论了可能的答案,但我会在这里写一下来简化。 Your javascript code seems to be fine but change PHP script to this and try:
您的javascript代码似乎没问题,但将PHP脚本更改为此并尝试:
$username = "";
$email = "";
$response = ""
if ($_POST["username"] && $_POST["email"]) {
$username = $_POST["username"];
$email = $_POST["email"];
}
if ($username != "" && $email != "") {
if (!username_exists($username) && !signup_email($signup_email)) {
$response = json_encode("good");
}else{
$response = json_encode("bad");
}
}
echo $response;
echo $response
cause if you don't add that line you won't get any result from your ajax request so console.log won't show anything. echo $response
因为如果你不添加该行,你将无法从你的ajax请求中获得任何结果,因此console.log不会显示任何内容。
Hope this helps you out! 希望这可以帮助你!
i think this code will work for you perfect. 我认为这段代码对你来说是完美的。
$("#signup_submit").on( "click", function() {
var _username = "foo";
var _email = "test@gmail.com";
$.ajax({
type: 'POST',
url: 'check.php',
dataType: 'text',
data: {
username: _username,
email: _email
},
success: function(response) {
console.log(response);
},
error: function(err) {
alert(err);
}
});
});
And like user #molinet writed - in php file do with $response and then echo it. 和用户#molinet writed一样 - 在php文件中用$ response做,然后回应它。
$username = "";
$email = "";
if ($_POST["username"] && $_POST["email"]) {
$username = $_POST["username"];
$email = $_POST["email"];
}
if ($username != "" && $email != "") {
if (!username_exists($username) && !signup_email($signup_email)) {
$response = "good";
}else{
$response = "bad";
}
}
echo $response;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.