javascript jQuery .submit() .ajax() 必须点击发送按钮两次才能得到正确的响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19229629/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 14:49:14  来源:igfitidea点击:

jQuery .submit() .ajax() have to click send button two times to get the correct response

javascriptphpjqueryajax

提问by Dan-Levi T?mta

I have a form with 5 fields that i am sending with AJAX to a PHP Script that does some simple validation and returns a string.

我有一个包含 5 个字段的表单,我使用 AJAX 将其发送到一个 PHP 脚本,该脚本执行一些简单的验证并返回一个字符串。

I have made a little jQuery script for the actual submission, and when i try to send the form i have to click the send button two times.

我为实际提交制作了一个小 jQuery 脚本,当我尝试发送表单时,我必须单击发送按钮两次。

Update: Url to live site: http://www.dan-levi.no/new/#!/Kontakt

更新:网址:http://www.dan-levi.no/new/#!/ Kontakt

Here are some code:

下面是一些代码:

HTML

HTML

<form id="contact_form" class="form-horizontal" action"includes/contact.php" method"post">
            <div class="control-group">
                <label class="control-label" for="contact_name">Ditt navn og evt. bedrift</label>
                <div class="controls">
                    <input type="text" class="input-large" id="contact_name" name="contact_name" placeholder="Ditt navn og evt. bedrift" />
                </div>
            </div>

            <div class="control-group">
                <label class="control-label" for="contact_email">E-post</label>
                <div class="controls">
                    <input type="email" class="input-large" id="contact_email" name="contact_email" placeholder="E-post" />
                </div>
            </div>

            <div class="control-group">
                <label class="control-label" for="contact_tel">Telefon</label>
                <div class="controls">
                    <input type="tel" class="input-large" id="tel" name="contact_tel" placeholder="Telefon" />
                </div>
            </div>

            <div class="control-group">
                <label class="control-label" for="contact_subject">Emne</label>
                <div class="controls">
                    <input type="text" class="input-large" id="subject" name="contact_subject" placeholder="Emne for melding" />
                </div>
            </div>

            <div class="control-group">
                <label class="control-label" for="contact_desc">Din beskjed</label>
                <div class="controls">
                    <textarea rows="10" class="input-large" id="contact_desc" name="contact_desc" placeholder="Din beskjed"></textarea>
                </div>
            </div>
            <div class="text-error pull-right" id="error_message"></div><br>
            <input class="btn btn-large pull-right" type="submit" name="" value="Send" /><br>
</form>

javaScript

脚本

$(document).ready(function() {
    $('#contact_form').submit(function(e) {
        data = $('#contact_form').serialize();
        $.ajax({
            url: 'includes/contact.php',
            type: 'POST',
            data: data,
        })
        .done(function(response) {
            if (response == 'empty') {
                $('#error_message').text('Noen av feltene er tomme.')
            } else {
                $('.message').html(response);
                $('#contact_form').fadeOut('400');
                $('#info_line').fadeIn('400').text('Takk for din henvendelse');
            };  
        })        
        e.preventDefault();
    });
});

PHP

PHP

$contact_name = $_POST['contact_name'];
$contact_email = $_POST['contact_email'];
$contact_tel = $_POST['contact_tel'];
$contact_subject = $_POST['contact_subject'];
$contact_desc = $_POST['contact_desc'];

if ($contact_name == '' || $contact_email == '' || $contact_tel == '' || $contact_subject == '' || $contact_desc == '') {
    echo "empty";
    die();
}
echo $contact_name.'<br><br>';
echo $contact_email.'<br><br>';
echo $contact_tel.'<br><br>';
echo $contact_subject.'<br><br>';
echo $contact_desc.'<br><br>';

I cant find out why i have to click the button two times, i have tried some trial and error, read the forum for answers. I tried to serialize the form outsite the submit function, i just cant get this to behave the way i want. All help is greatly appreciated.

我不知道为什么我必须点击按钮两次,我尝试了一些试验和错误,阅读论坛以获得答案。我试图在提交功能之外序列化表单,我只是无法让它按照我想要的方式运行。非常感谢所有帮助。

Oh, worth to mention. The actual response is that the fields are empty (php validation) the first time i click, but the second time it works as it should.

哦,值得一提。实际的响应是我第一次单击时这些字段为空(php 验证),但第二次它可以正常工作。

采纳答案by Justin

Make the ajax call using a regular input button instead of a submit button.

使用常规输入按钮而不是提交按钮进行 ajax 调用。

$("#button").click(function () { ... ajax ... }

$("#button").click(function () { ... ajax ... }

回答by Jonathon

I'm not sure if it makes a difference but have you tried putting what you want to happen afterwards in a success callback?

我不确定它是否有所作为,但是您是否尝试过将您想要在成功回调中之后发生的事情放入其中?

$(document).ready(function() {
    $('#contact_form').submit(function(e) {
        data = $('#contact_form').serialize();
        $.ajax({
            url: 'includes/contact.php',
            type: 'POST',
            data: data,
            success: function(response) {
                if (response == 'empty') {
                    $('#error_message').text('Noen av feltene er tomme.')
                } else {
                    $('.message').html(response);
                    $('#contact_form').fadeOut('400');
                    $('#info_line').fadeIn('400').text('Takk for din henvendelse');
                }; 
            }
        });     
        e.preventDefault();
    });
});

回答by stevemiketa

I'm guessing it's because the default action (submit the form) is processing before your $.ajax request. Try making e.preventDefault() first in your submit callback.

我猜这是因为在您的 $.ajax 请求之前正在处理默认操作(提交表单)。尝试在提交回调中首先制作 e.preventDefault() 。

$(document).ready(function() {
    $('#contact_form').submit(function(e) {
        e.preventDefault();
        data = $('#contact_form').serialize();
        $.ajax({
            url: 'includes/contact.php',
            type: 'POST',
            data: data,
            success: function(response) {
                if (response == 'empty') {
                    $('#error_message').text('Noen av feltene er tomme.')
                } else {
                    $('.message').html(response);
                    $('#contact_form').fadeOut('400');
                    $('#info_line').fadeIn('400').text('Takk for din henvendelse');
                }; 
            }
        });     
    });
});