提交网页后刷新

时间:2014-03-14 15:00:09

标签: javascript jquery ajax forms

当我开始使用JS开发网页时,我添加了一个jQuery函数,如果用户插入的数据是正确的,并且返回false(return false;),则表单没有刷新页面。现在,添加AJAX后,表单刷新,我不知道为什么。这是我的JS代码:

<script>
        $("form").submit(function(){
            // in this area I have a lot of IF's that checks if everything is currect, this area worked and did not make the problem until I added the AJAX.

        if(allow && style){
                $.ajax({
                    type: "POST",
                    url: "join.php",
                    data: { name: name.val(), url: url.val(), email: email.val(), country: country.val(), language: language.val(), age: age.val(), image: image.val(), type: style.val()}
                })
                .done(function( msg ) {
                    // Success.
                })
                .fail(function() {
                    alert( "ERROR. Resubmiting the form." );
                    //$("form").submit();
                });
            }

            return false;
        });
    </script>

在IF的区域,JS检查插入的文本是否为当前,并为没有插入的文本添加红色边框。只有当所有内容都已完成时,当allowstyletrue时,页面才会刷新。

1 个答案:

答案 0 :(得分:-2)

您应该将event.preventdefault添加到提交功能的开头。同时将事件添加为参数。 像这样:

  $("form").submit(function(event){
  event.preventDefault();
 // in this area I have a lot of IF's that checks if everything is currect, this area worked and did not make the problem until I added the AJAX.

        if(allow && style){

这会停止表单跟踪操作并刷新页面,您只能通过$("form").submit();提交帖子

编辑:这应该解决它,可能会有一些语法错误,但你应该没问题。

$("form").submit(function () {
    // in this area I have a lot of IF's that checks if everything is currect, this area worked and did not make the problem until I added the AJAX.

    if (allow && style) {
        $.ajax({
            type: "POST",
            url: "join.php",
            data: { name: name.val(), url: url.val(), email: email.val(), country: country.val(), language: language.val(), age: age.val,(), image: image.val(), type: style.val()},
            success: function (data) {
            // succes code here
        },
        error: function (data) {
            alert("ERROR. Resubmiting the form.");
            //$("form").submit();
        }

    });

    }

    return false;
})
;