在AJAX请求中传递表单数据的麻烦

时间:2014-04-18 17:01:31

标签: javascript php jquery ajax

我在通过AJAX请求将表单值传递给PHP时遇到问题。根据我的下面的代码,变量可以传回,所以我怀疑问题可能是data: $('#signup-form').serialize()

JS:

$.ajax
({
    type: "POST",
    url: "http://www.domain.com/includes/register.php",
    data: $('#signup-form').serialize(),
    success: function(data)
        {
            $('#signup-response').hide();
            $('#signup-response').fadeIn();
            $('#signup-response').html(data);
        },
    error: function()
    {
        alert("fail");
    }
})

形式:

<form id="signup-form" action="" method="POST">
    <input name="email" type="email" class="form-control" id="signupEmail" placeholder="Email address">
    <input name="password1" type="password" class="form-control" id="signupPassword" placeholder="Password">
    <input name="password2" type="password" class="form-control" id="signupPassword2" placeholder="Password">
    <select name="country" id="signupCountry" class="selectpicker">
        <option value="0">Country</option>
        <option>United States</option>
        <option>United Kingdom</option>
        <option>Canada</option>
    </select>
    <select name="gender" id="signupGender" class="selectpicker">
        <option value="0">Gender</option>
        <option>Female</option>
        <option>Male</option>
    </select>
    <button id="signup" class="btn btn-success btn-block signup" type="submit">Sign up</button>
</form>

register.php

<?php
$username = $_POST['signupEmail'];
echo "hello"; // works
echo $username; // doesn't work
?>

1 个答案:

答案 0 :(得分:2)

试试这个,您需要使用输入名称 <input name="email" type="email" class="form-control" id="signupEmail" placeholder="Email address">而不是使用输入字段ID。

 $username = $_POST['email'];

而不是

  $username = $_POST['signupEmail'];