淡出表格提交中的div

时间:2013-12-10 23:32:56

标签: php jquery ajax

我需要做的是使用Ajax提交表单,将表单内容作为发布数据发布到相同的页面,并在完成后淡出div。

我遇到的问题是:

  1. 通过ajax提交表单而不刷新
  2. 将表单的内容发布到相同的页面
  3. 表格提交后淡出我的div
  4. 我目前的代码是:

    <script src='http://code.jquery.com/jquery-1.8.2.js'></script>
    <script>
    $("submits").click(function() { 
        $('form').bind('submit', function () {
          $.ajax({
            type: 'post',
            url: 'index.php',
            data: $('form').serialize(),
            success: function () {
                alert('Success');
            }
        });
        $(".element")
            .css({ opacity:0, visibility:"visible" })
            .animate({ opacity:1 }, "slow");
    });
    </script>
    
    <?php
    If(!Empty($_POST)){
    ?>
    <div class="availability" id="availability">
    <?php
    Include 'functions/functions.php';
    
    $Username = $_POST['username'];
    
    If(Class_Exists('AIM')){ // note: this is just a check since i move my files a lot
        AIM::Execute($Username); 
    }
    ?>
    </div>
    

    不试图抓住表单提交,一切都按预期工作。

    如果您需要提供任何其他代码来提供帮助,请发表评论,非常感谢您提供任何帮助,谢谢。

2 个答案:

答案 0 :(得分:2)

ajax提交并淡出成功:

$.ajax({
    url: window.location.href,
    type: "post",
    data: values,
    success: function(){
        $('#my_form_wrapper').fadeOut(1000); // fade out your form/wrapper 1sec
    },
    error:function(){
        alert("failure");
        $("#result").html('There is error while submit');
    }
});

答案 1 :(得分:1)

  1. 首先,这段代码很乱,组织起来,尝试将所有可以放在文件顶部。

  2. 您需要有一个表单通过AJAX中的POST提交数据。

  3. 您可以使用所需代码的完整示例:

    //Put your PHP at the top
    Include 'functions/functions.php';
    
    $Username = $_POST['username'];
    
    If(Class_Exists('AIM')){ // note: this is just a check since i move my files a lot
        AIM::Execute($Username); 
    }
    
    //Check if is a POST at the top of your file as well, with a variable
    $isPost = true;
    If(!Empty($_POST))
    {
        $isPost = false;
    }
    
    ?>
    
    <script src='http://code.jquery.com/jquery-1.8.2.js'></script>
    
    //This is your ajax script
    function submitFormViaAJAX()
    {
    
        //this fadeOut your div, but you can change to another code to accomplish your effect
        $("#availability").hide(900);
    
        //set your form as content to POST via AJAX
        var data = $('#myForm').serialize();
    
        //put your file name (current in your case) to make the request
        $.post('myFile.php', data);
    }
    </script>
    
    <?php
    //This "if" is not necessary, since the post will be via ajax.. 
    if(!$isPost){
    ?>
    <div class="availability" id="availability">
    
        <form id="myForm">
            <!--form content there-->
    
                   <a href="javascript:submitFormViaAJAX();">Send Form via AJAX</a>
        </form>
    
    </div>
    
    <?php } ?>
    
  4. 随意更改名称和一些代码行