2013-08-06 02:16
浏览 60

如何从jquery .post访问$ _POST变量?

I am trying to using jquery post to try to send form data asynchronously to a php file that will upload the data to my database.

<!DOCTYPE html>
  <script src=""></script>
  <div id="contact_form">  
    <form id="contact" name="contact" method="post">  
    <label for="name" id="name_label">Name</label>  
    <input type="text" name="name" id="name" size="30" value="" class="text-input" />  

    <label for="email" id="email_label">Return Email</label>  
    <input type="text" name="email" id="email" size="30" value="" class="text-input" />  

    <label for="phone" id="phone_label">Return Phone</label>  
    <input type="text" name="phone" id="phone" size="30" value="" class="text-input" />  

    <br />  
    <input type="submit" name="submit" class="button" id="submit_btn" value="Submit" />  
  <div id="result"></div>

/* attach a submit handler to the form */
$("#submit_btn").submit(function(event) {

  /* stop form from submitting normally */

 $.post("process.php", $("#contact").serialize());

  return false;


I know it is serial encoding the data but my php script isn't picking it up, I am not sure what I am doing wrong. I know it is simple, but I have been working a few days on this and can't seem to figure it out. I understand how to do this without jquery but I really need it in this case. Here is my php:

    $var_name = $_POST['name'];
    $var_email = $_POST['email'];
    $var_phone = $_POST['phone'];

//This establishes a connection to the database. It also says what to do if the connection fails.
try {
    $db_handle = new PDO("mysql:host=$server;dbname=$database", $db_username, $db_password);
    $db_handle->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $stmt = $db_handle->prepare('INSERT INTO contact(name, email, phone) VALUES(:name, :email, :phone)');   
        ':name' => $var_name,
        ':email' => $var_email,
        ':phone' => $var_phone,
    } catch(PDOException $e) {
    echo 'Error: ' . $e->getMessage();
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • doucheng3811 2013-08-06 03:25

    When you serialize a form with jQuery, submit button is not included so you should replace



    if ($_SERVER['REQUEST_METHOD'] === 'POST')


    Change $("#submit_btn").submit(...); by $("#contact").submit(...);

    打赏 评论
  • dsfdsfds521521 2013-08-06 02:18

    Should be:


    Your selector is incorrect, so you aren't actually sending anything to the server. Next time, check the request in your browser tools.

    打赏 评论
  • du7535 2013-08-06 02:56

    The jquery API states that submit button values will not be passed. So the post may be getting to your php request just fine would suggest looking for a required field instead of looking for $_POST['submit'] in your conditional.

    You can also try using var_dump($_POST) before your code and see what is getting to the script.

    打赏 评论

相关推荐 更多相似问题