在用PHP完成的jQuery表单提交之后

时间:2011-12-16 13:32:02

标签: php javascript jquery form-submit

我有一个php文件,它包含一个textfiled和submit按钮,div和下面是代码

page1.php中

<form name="form1" method="post">
  <input type="text" name="email1">
  <input type="submit" name="submit" value="send" class="submit_class">

  <div class="suc_box">You have Entered</div>
</form>

if($_POST['submit']) {
  $v1 = $_POST['email1'];

  // $query1 =  here some code to insert into database

  if($query1 > 0){
    //here i want to display the div `suc_box`.. Here how i can show that div
  }
}

和jQuery代码:

$(document).ready(function(){
    $('suc_box').hide();

    $('suc_box').click(function(){
        $(this).hide();
    });
});   

问题:如何在表单插入数据库后提交表单时显示/显示suc_box

2 个答案:

答案 0 :(得分:3)

您可以使用AJAX轻松完成。你有一个带有表单的php文件和另一个用于处理数据的文件:

<强> // form_file.php

<form id="my_form" onsubmit="validateform();">
  <input type="text" name="email1" />
  <input type="submit" value="OK" />
</form>

<div class="suc_box"></div>

<script>
$(document).ready(function(){
  $('.suc_box').click(function(){
    $(this).hide();
  });

  $('#my_form').submit(function(){
    var data = $(this).serialize();
    $.post('process.php',data,function(return_data){
      $('.suc_box').html(return_data);          
    });
    return false; //cancel the 'real' submit
  });
});   
</script>

<强> // process.php

<?php
$email = mysql_real_escape_string($_POST['email1']);
//write data to DB
if($succeeded) {
  echo 'You have Entered';
} else {
  echo 'Something went wrong, try again!';
}

这是未经测试的,但你明白了。

验证电子邮件字段

    function validateform(){
        if (!/^\S+@\S+\.\w+$/.test(document.sweetform.Email.value)) {
            alert("Not a valid e-mail address");
            return false;
        }
        else {
            return true;
        }

    }

答案 1 :(得分:0)

如果你说得对,你可以做到这一点,但我建议你调查ajax做你想做的事情

    <div class="suc_box">
         You have Entered
    </div>
    </form>
    <?php  
    if($_POST['submit'])
    {
     $v1 = $_POST['email1'];

     // $query1 =  here some code to insert into database

      if($query1 > 0){
       ?>


       <script type="text/javascript">
          $('suc_box').show();

       </script>
<?php
    }

    }
?>