【问题标题】:Success message not displaying using jQuery ajax使用 jQuery ajax 不显示成功消息
【发布时间】:2016-12-27 20:50:26
【问题描述】:

所以我已经验证了我的contact.php(phpmailer 文件)正在工作。但是最后,如果响应成功,contact.php 会显示echo: 'done'

if(!$mail1->send()) {
    echo 'error';
    //echo 'Mailer Error: ' . $mail->ErrorInfo;
    return false;
} else {
    echo 'done';
    return true;
}

那时(我猜是因为我花钱请开发人员为我创建表单,但直到最近才尝试使用我自己的主机进行测试。这是他提供的代码。

/************
 AJAX Method
*************/
function submitForm()
    {
        //1. user clicked on submit/send button after filling form
        $('#contactform').on('submit',function(e){
            //2. this line will prevent the window's reload!
            e.preventDefault();
        });//end form submit

        //3. handilg the success div
        $('#success_message').show();
        $('#success_message h2').text('Processing, wait please...');
        $('#submit_cf').attr('disabled','disabled');

        //4. the actual ajx process starting from here
        $formData = $('#contactform').serialize();

        $.ajax({
            url : "contact.php",
            type: "POST",
            data : $formData,
            success: function(data) {
                //data - response from server
                //console.log(data);
                if(data == 'done'){
                    $('#success_message h2').text('Mail Sent Successfully!');
                }else{
                    $('#success_message h2').text('There is an error, try again later!');
                    // $('#submit_cf').attr('disabled','disabled');
                }
            }//end success
        });//end ajax
    }//end submitForm() function
})(jQuery, window, document);
</script>

我假设 echo: 'data'return: true 应该将单词 data 发送回 ajax 表单,其中:

if(data == 'done'){
    $('#success_message h2').text('Mail Sent Successfully!');

将接管并使用Mail Sent Successfully 填充div#success_message h2 html。

只是,ajax 根本不起作用。取而代之的是一个新页面,上面只加载了“完成”一词(这是我期望使用 echo:'done' 时会发生的情况)。

我不知道如何让 ajax 接受“完成”,然后使用成功消息填充同一页面。

我将 jquery 加载到标题中,因为它用于其他几个脚本。 ajax 脚本在 html 中,而不是在外部脚本中。

请告诉我有一个简单的修复方法,还是我需要从 Swift 重新开始?

【问题讨论】:

  • 可以出示表格吗?

标签: php contact-form ajaxform


【解决方案1】:

看过剧本后,它的设置有点奇怪。我会注明我认为您需要更改的内容,但首先回答您的问题:

我假设 echo: 'data', return: true 应该将单词 data 发送回 ajax 表单...

不,data 是从 ajax 页面返回的内容,在我的回答中,我已将其更改为 response,因此更清楚它的作用。它将包含成功/错误消息

而是加载一个新页面,上面只有“完成”这个词...

这个通常表示有问题,要么是没有先加载jQuery,要么是有错误导致jquery无法正常运行,所以本应阻止表单正常提交的那一行(e.preventDefault()) 被中断。

我将 jquery 加载到标题中,因为它用于其他几个脚本。 ajax 脚本在 html 中,而不是在外部脚本中。

这不应该太难补救,你可以拥有这个脚本而不是 html。它必须位于事件侦听器之间,而不是您拥有它的方式,并确保它位于 jQuery 库加载之后:

<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="/js/myScript.js"></script>

请告诉我有一个简单的修复方法,还是我需要从 Swift 重新开始?

您不必在 Swift 中重新开始

/js/myScript.js

$(document).ready(function(){
    // Make a function on this would make more sense, but you only need it if you
    // want to re-use this feature, otherwise you can incorporate it back
    // I made it as a function so it cleans up the submit a bit
    function doSuccess(acton,message,disable)
        {
            $(acton).show();
            $(acton+' h2').text(message);
            $(disable).attr('disabled','disabled');
        }

    // It's strange to have the on('submit') inside the function since it's
    // a listener, you shouldn't need to wrap this in a function, but wrap 
    // everything inside the listener instead
    $('#contactform').on('submit',function(e){
        // This is fine, it does prevent the form from submitting
        e.preventDefault();
        // Assign to variable this form
        var thisForm = $(this);
        // Run messaging
        doSuccess('#success_message','Processing, please wait...','#submit_cf');
        // Run ajax
        $.ajax({
            url : "contact.php",
            type: "POST",
            // You can serialize the form here
            data : thisForm.serialize(),
            success: function(response) {
                // Just do the text here from php
                $('#success_message h2').text(response);
            }
        });
    });
});

在 PHP 端,只需回显消息。由于您没有任何复杂的回报,因此变得更容易:

# You can use a ternary since there are only two options
echo ($mail1->send())? 'Your message sent successfully' : 'There is an error, try again later!';
# Unless there is a reason to return true or false (unless this is part of a
# function or method), you don't need it. It's not doing anything

最后一点,无论您在哪里使用 submitForm()(可能在您的提交按钮上或作为内联 javascript 的东西上),您应该能够删除它,因为该函数将不再存在。



编辑/只是作为一个方面:我只是要演示我是如何做到这一点的(在尽可能简单的例子中)为了获得一致的结果和结束。在这个阶段它可能对你来说太复杂了,但是,如果你有兴趣并阅读这些符号,它就很简单了。如果您复制所有内容并将它们放在我在下面标记的正确文件夹中,您可以在决定实施之前先看到它的工作原理。

它涉及一个调度程序页面、一个 xml 页面和一个 javascript ajax 对象。这个想法是您可以构建它并使用 xml 作为自动化指令执行自动化工作流程:

/dispatcher.php

这是接收您的 ajax 调用的页面。它将接收所有 ajax 调用并发送正确的指令。您可能希望在其中构建一些检查(如表单令牌匹配),因为这种自动化可能很危险。这些是它的基础:

// Check specifically for actions
if(!empty($_POST['action'])) {
    // This will fetch an xml file and parse it (see next section)
    $config =   simplexml_load_file(__DIR__."/xml/settings.xml");
    // Assign the action
    $action =   $_POST['action'];
    // Check the parsed file for the proper ajax action
    if(!empty($config->ajax->action->{$action})) {
        // Loop through the action
        foreach($config->ajax->action->{$action} as $do) {
            // If there is an include action
            if(isset($do->{"include"})) {
                // Loop through the includes
                foreach($do->{"include"} as $include) {
                    // If the file exists, include it
                    if(is_file($inc = __DIR__.$include))
                        include($inc);
                }
            }
        }
    }
    // Stop processing
    exit;
}

/xml/settings.xml

这只是一个基本的 xml 文件,可帮助您自动调用。这很简单。需要注意的一点是,您需要将 xml 文件夹放在根目录之外,或者使用 .htaccess(或 Windows 的 web.config)来保护除 php 之外的该文件夹不被访问。网上有这方面的例子。您可以扩展此 xml 以包含多个带有 &lt;include&gt; 标签的页面,并且调度程序将一个接一个地运行。

<?xml version="1.0" encoding="UTF-8"?>
<config>
    <ajax>
        <action>
            <!-- This would correlate to a hidden field in your form. See html form example -->
            <email_user>
                <include>/contact.php</include>
                <!-- To run more actions on this call, just add another tag here -->
                <!-- <include>/another/page/here.php</include> -->
            </email_user>
        </action>
    </ajax>
</config>

/js/myScript.js

这与上面的版本略有不同。我会使用一个 Ajax 对象,以便它可以重复使用。

// @param $ [object] This accepts jQuery object
var AjaxEngine  =   function($)
    {
        // Used to overwrite default url
        var useUrl;
        // Default url for call
        var url     =   '/dispatcher.php';
        // This is the do before function
        var beforeFunc;
        // This is the default do before
        var useBefore = false;
        // This is what overwrites the url (not needed in this instance)
        this.useUrl =   function(useUrl)
            {
                url =   useUrl;
                return this;
            }
        // This assigns the beforeSend action in ajax
        this.doBefore   =   function(beforeFunc)
            {
                useBefore   =   beforeFunc;
                return this;
            }
        // This is the actual send function
        // @param data [object] This is what data to send to the dispatcher
        // @param fun [object]  This is the anonymous function that will run
        //                      on success of the form 
        this.send   =   function(data,func)
            {
                $.ajax({
                    // Runs before the sending (this is where you add waiting messages)
                    beforeSend: useBefore,
                    url: url,
                    data: data,
                    type: 'post',
                    // This will take the response and drop it into the
                    // anonymous function
                    success: function(response){
                        func(response);
                    }
                });

                return this;
            };
    }
// Wait for document to be ready
$(document).ready(function(){
    // If you use a class, you can act on any form that has the "ajax_form" class
    // This is very powerful. It means you can have many different forms on
    // the same page and use the same script/dispatcher to run/process each
    $('.ajax_form').on('submit',function(e){
        e.preventDefault();
        var thisForm = $(this);
        // Create new ajax engine, you have to pass jQuery for ajax to work
        var Ajax    =   new AjaxEngine($);
        // Set do before action, in your case you have 3 things that must
        // happen before ajax sends. In this example, this function is fixed
        // (not ideal), but you can add automation so you send the correct 
        // doBefore function on a per-form basis
        Ajax.doBefore(function() {      
                $('#success_message').show();
                $('#success_message h2').text('Processing, please wait...');
                $('#submit_cf').attr('disabled','disabled');
            })
            // Send the form data and response function to "/dispatcher.php"
            .send(thisForm.serialize(),function(response) {
                // Do a "try/catch" here, that way you can catch errors
                // Most common in this scenario would be an empty response, or
                // mal-formed json (like a fatal error in php or whatever)
                try {
                    // Parse the response
                    var parseResp   =   JSON.parse(response);
                    // See if there are instructions
                    var instr       =   (parseResp.instructions !== "undefined")? parseResp.instructions : 'text';
                    // Apply instructions, these are just some examples.
                    switch(instr) {
                        case('html'):
                            // Take from php apply html
                            $(parseResp.sendto).html(parseResp.data);
                            break;
                        default:
                            // Take from php apply text
                            $(parseResp.sendto).text(parseResp.data);
                    }
                }
                catch(Exception) {
                    // This will show you in the console what is wrong
                    console.log(Exception.message);
                    // This will show you what was received back so you can address issue
                    console.log(response);
                }
            });
    });
});

/index.php

网站根目录中的示例表单:

<form action="/tester.php" id="contactform" class="ajax_form">
    <div id="success_message">
        <h2>Hey</h2>
    </div>
    <input type="text" name="test" value="1050724273" />
    <!-- Send this to the dispatcher and match the value in the xml file -->
    <input type="hidden" name="action" value="email_user" />
    <input type="submit" value="Save" />
</form>

/contact.php

最后,这是将在我们的自动化中基于 xml 文件中的标记运行的页面。关键是返回 json:

<?php
// Do all your code first, then output json at the very bottom
// For complex html output, do a buffer so you can capture it easily
ob_start();
?>
<h1>Hello people</h1>
<?php
// Get the above text/html from the buffer
$data   =   ob_get_contents();
// Clear out the buffer
ob_end_clean();
// This is what will be sent back as the "response" in the ajax
$response   =   array(
                    // This will tell the ajax where to drop the response
                    'sendto'=>'#contactform',//'#success_message h2',
                    // This is the content from above (<h1>Hello people</h1>)
                    'data'=>$data,
                    // This is just incase you want to expand out the ajax
                    // to include checks for success and failure
                    'success'=>true,
                    // This tells your ajax how to output using the switch
                    'instructions'=>'html'//'text'
                );
// If you have extra includes that you want to run in the ajax call,
// don't die here, but in this instance, since there is only one include (contact.php),
// just die and output the response
die(json_encode($response));

【讨论】:

  • 感谢您如此深入的回复。直到今天晚上我才能使用这个,但我要感谢你的回答。
  • 没问题,我试着说得很清楚,但如果您遇到任何问题,请告诉我。我会在附近。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-27
  • 1970-01-01
  • 2023-03-25
  • 2023-04-06
  • 1970-01-01
相关资源
最近更新 更多