使用jQuery ajax

时间:2016-08-21 02:12:28

标签: php contact-form ajaxform

所以我已经验证我的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!');

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

只有相反,ajax根本不起作用。相反,新页面只加载了“完成”一词(这是我在使用echo时所期望的:'完成')。

我不知道如何让ajax接受'done'然后用成功消息填充同一页面。

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

请告诉我有一个简单的解决方法,还是我需要重新开始使用Swift?

1 个答案:

答案 0 :(得分:1)

看完剧本后,它的设置有些奇怪。我会记下我认为你需要改变的内容,但首先回答你的问题:

  

我假设echo:'data',return:true应该将单词数据发送回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(或web.config for Windows)来保护此文件夹不被访问,除了php。网上有一些例子。您可以展开此xml以包含具有<include>标记的多个页面,并且调度程序将一个接一个地运行。

<?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));