将一个变量从PHP传递给javascript和html表单 [英] Passing a variable from PHP to javascript and on to an html form

查看:193
本文介绍了将一个变量从PHP传递给javascript和html表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常小的问题,我使用jQuery,jQuery表单和PHP邮件在WordPress中设置的联系表单发送表单生成的电子邮件。

I'm having one, admittedly very minor issue with a contact form I've set up in WordPress using jQuery, jQuery form and PHP Mail to send a form-generated email.

为了替换当前的联系表单,在联系表单页面中执行pHp验证,然后使用PHP邮件发送,我设计了以下简单的html 5表单(可以在此页面上看到: http://edge.donaldjenkins.net/contact ):

To replace my current contact form which performs a pHp validation from within the contact form page and then sends using PHP Mail, I've designed the following simple html 5 form (which can be seen on this page: http://edge.donaldjenkins.net/contact):

<form id="contact" method="post" action="">
<fieldset>  

    <label for="name">Name</label>
    <input type="text" name="name" placeholder="Your Name" title="Enter your name" class="required">

    <label for="email">E-mail</label>
    <input type="email" name="email" placeholder="yourname@domain.com" title="Enter your e-mail address" class="required email">

    <label for="phone">Phone</label>
    <input type="tel" name="phone" placeholder="ex. (555) 555-5555">

    <label for="website">Website</label>
    <input type="url" name="url" placeholder="http://">

    <label for="message">Question/Message</label>
    <textarea name="message"></textarea>

    <label for="checking" class="hidden">If you want to submit this form, do not enter anything in this field</label><input type="text" name="checking" class="hidden">

    <input type="submit" name="submit" class="button" id="submit" value="Send Message" />

</fieldset>

然后我使用jQuery验证[jquery.validate.js]和表单[jquery.form.js]插件执行客户端验证:

I then use the jQuery validate [jquery.validate.js] and form [jquery.form.js] plugins to perform a client-end validation:

<script src="js/jquery.validate.js"></script>
<script src="js/jquery.form.js"></script>

<script>
$(function(){
$('#contact').validate({
submitHandler: function(form) {
    $(form).ajaxSubmit({
    url: 'send-message.php',
    success: function() {
    $('#contact').hide();
    $('#instructions').hide();
    $('#status').show();
    $('#popular-posts').show();
    $('#status').append("<p>Thanks! Your request has been sent.  One will try to get back to you as soon as possible.</p>")
    }
    });
    }
});         
});
</script>

验证后,上述脚本使用jQuery.form的 ajaxSubmit函数将日期提交给服务器的PHP页面,send-message.php(原因是该javascript可以' t发送电子邮件)。我使用这个PHP文件对数据进行第二次服务器端验证(尽管这可能是多余的,因为安装程序依赖于javascript将数据传递到服务器,可以放心地假定没有人会能够使用没有启用javascript的窗体)。它还对表单中添加的隐藏输入字段中的数据执行蜜罐验证检查。然后发送电子邮件:

After the validation, the above script uses jQuery.form's ajaxSubmit function to submit the date to a server PHP page, send-message.php (the reason being that javascript can't send email). I use this PHP file to carry out a second, server-side validation of the data (though this is probably redundant, since because the setup relies on javascript to pass the data on to the server, one can safely assume that no one will be able to use the form without javascript enabled). It also performs a honeypot captcha check on data in a hidden input field added in the form. The email is then sent:

<?php 
//invoke wp_load in order to use WordPress wp_mail plugin function instead of mail for    better authentification of the sent email
require_once("/path/to/wp-load.php");

//Check to see if the honeypot captcha field was filled in
if(trim($_POST['checking']) !== '') {
$captchaError = true;
$errors .= "\n Error: Captcha field filled in";
} else {

//Check to make sure that the name field is not empty
if(trim($_POST['name']) === '') {
    $errors .= "\n Error: Name field empty";
    $hasError = true;
} else {
    $name = strip_tags($_POST['name']);
}

//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) === '')  {
    $emailError = 'You forgot to enter your email address.';
    $hasError = true;
} else if (!eregi("^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
    $errors .= "\n Error: Message field empty";
    $hasError = true;
} else {
    $email = strip_tags($_POST['email']);
}

//Check to make sure comments were entered  
if(trim($_POST['message']) === '') {
    $errors .= "\n Error: Message field empty";
    $hasError = true;
} else {
    $phone = strip_tags($_POST['phone']);
    $url = strip_tags($_POST['url']);
    if(function_exists('stripslashes')) {
        $message = stripslashes(trim($_POST['message']));
    } else {
        $message = strip_tags($_POST['message']);
    }
}
//If there is no error, send the email
if(!isset($hasError)) {

    // Send Message 
    $emailTo = 'me@mydomain.com';
    $subject = 'Contact Form Submission from '.$name;
    $body = "Name: $name \n\nEmail: $email \n\nPhone: $phone \n\nWebsite: $url \n\nMessage: $message";
    $headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;

    wp_mail($emailTo, $subject, $body, $headers);

    $alert = 'Thanks! Your request has been sent.  One will try to get back to you as soon as possible.';
} else {
    $alert = $errors;
}
} ?>

服务器跟踪是否找到错误,还是以变量$ alert成功发送电子邮件。

The server keeps track of whether errors were found or whether the email was successfully sent in variable $alert.

在pHp功能完成后,脚本将隐藏联系人页面中的表单,并显示一个先前隐藏的html元素,附加警报消息。

After the pHp function completes, the script hides the form from the contact page and displays a previously hidden html element to which it appends an alert message.

我无法解决的问题是使javascript更改该警报消息的措辞,以反映电子邮件是否被成功发送,因为我不知道如何通过必要的pHp变量($ alert)包含服务器PHP进程中的错误消息列表到联系人表单页面中插入的脚本。当然,这也是一个非常理论的问题,因为上述原因,首先会出现一个容易出错的消息甚至不能达到PHP阶段。

The issue I can't solve is making javascript change the wording of that alert message to reflect whether the email was or not successfully sent, because I don't know how to pass the requisite pHp variable ($alert) containing a list of the error messages in the server PHP process to the script for insertion in the Contact Form page. Of course, again, this is a very theoretical concern, since for the reasons stated above, it's unlikely that an error-prone message would even have reached the PHP stage in the first place.

我尝试在PHP文件末尾插入以下代码,无效:

I've tried inserting the following code at the end of the PHP file, to no avail:

<script type="text/javascript">
alert = <?php echo $alert; ?>;
</script>

后者的尝试不会在Firebug中产生任何错误,但是变量值不会被传递上。欢迎任何想法或想法。

The latter attempt doesn't generate any errors in Firebug, but the variable value doesn't get passed on. Any ideas or thoughts welcome.

更新:我添加了此工作流程图,以澄清此问题的设置:

UPDATE: I added this workflow chart to clarify the setup for this issue:

推荐答案

p>在send-message.php中,将警报文本放在IDd < div /> 中:

In send-message.php, put the alert text in an IDd <div />:

<div id="statusmsg" style="display: none">
<?php echo $alert ?>
</div>

然后您在调用页面上的Javascript应该如下所示:

Then your Javascript on the calling page ought to look like this:

<script type="text/javascript">
$(function() {
    $('#contact').validate({
        submitHandler: function(form) {
            $(form).ajaxSubmit({
                url: 'send-message.php',
                success: function(data) {

                    $('#contact').hide();
                    $('#instructions').hide();
                    $('#status').show();
                    $('#popular-posts').show();

                    // Make DOM object from result
                    var $DOMObj = $(data);

                    // Retrieve status message, if any
                    var $status = $('#statusmsg', $DOMObj);

                    // Show status message, if any
                    if ($status) {
                          $status
                                 .css('display', '')
                                 .appendTo('#status');
                    }
            }
            });
        }
    });         
});
</script>

希望您可以看到我如何使用参数 success callback以检索AJAX请求响应的HTML内容,位于statusmsg div并将其附加到调用页面上的相关元素。

Hopefully you can see how I've used a parameter to the success callback to retrieve the HTML contents of the AJAX request response, located the statusmsg div and appended it to the relevant element on the calling page.

更多最好的是,send-message.php将打印JSON而不是HTML,使得这个过程更容易一些。至少在这个问题的线程中,我会把它作为读者的练习。

More optimally, send-message.php would print JSON rather than HTML, making this process a little easier. I'll leave that as an exercise for the reader.. at least in this question thread.

这篇关于将一个变量从PHP传递给javascript和html表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆