繁体   English   中英

Javascript不使用HTML形式将变量传递给PHP

[英]Javascript not passing variable to PHP with HTML form

我有联系表,使用Javascript和PHP。

我的问题是javascript不会将其变量传递给PHP脚本。 我发现了以下内容:

变量确实会在javascript中设置,因为它通过了javascript内部的变量检查并使用了显示变量的警报。

当它移动到PHP脚本时,变量不再存在。 我试图注释掉PHP脚本中的检查,然后成功发送了一封邮件,但是除了PHP脚本中的静态内容外,该邮件是空的。

我尝试了各种不同的方法,包括直接从http.send()函数传递变量。

这是相关的代码(这些都是Web服务器上的所有3个不同的文件):

HTML:

div class="contact_form">
            <h4>Get in touch</h4>
            <form method="post">
                <input type="text" name="Name" id="name" value="Name" onfocus="this.value = this.value=='Name'?'':this.value;" onblur="this.value = this.value==''?'Name':this.value;" />
                <input type="text" name="Email" id="email" value="Email" onfocus="this.value = this.value=='Email'?'':this.value;" onblur="this.value = this.value==''?'Email':this.value;" />
                <input type="text" value="Subject (Hosting, Requests, Appeal, Report, etc.)" id="subject" onfocus="this.value = this.value=='Subject (Hosting, Requests, Appeal, Report, etc.)'?'':this.value;" onblur="this.value = this.value==''?'Subject (Hosting, Requests, Appeal, Report, etc.)':this.value;" />
                <textarea name="Message" id="body" onfocus="this.value = this.value=='Message'?'':this.value;" onblur="this.value = this.value==''?'Message':this.value;">Message</textarea>
                <input type="submit" name="submit" id="submit" value="send" class="submit-button" onClick="return check_values();" />
            </form>
            <div id="confirmation" style="display:none; position: relative; z-index: 600; font-family: 'Open Sans', sans-serif; font-weight: 300; font-size: 16px; color: #4e4e4e;"></div>
        </div> <!-- end .contact_form -->

Javascript:

var http = createRequestObject();
var areal = Math.random() + "";
var real = areal.substring(2,6);

function createRequestObject() {
    var xmlhttp;
    try { xmlhttp=new ActiveXObject("Msxml2.XMLHTTP"); }
  catch(e) {
    try { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
    catch(f) { xmlhttp=null; }
  }
  if(!xmlhttp&&typeof XMLHttpRequest!="undefined") {
    xmlhttp=new XMLHttpRequest();
  }
    return  xmlhttp;
}

function sendRequest() {
    var rnd = Math.random();
    var name = escape(document.getElementById("name").value);
    var email = escape(document.getElementById("email").value);
    var subject = escape(document.getElementById("subject").value);
    var body = escape(document.getElementById("body").value);

    try{
        http.open('POST','pform.php');
        http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        http.send('name='+name+'&email='+email+'&subject='+subject+'&body='+body+'&rnd='+rnd);
        http.onreadystatechange = handleResponse;
    }
    catch(e){}
    finally{}
}

function check_values() {
    var valid = '';

    var name = document.getElementById("name").value;
    var email = document.getElementById("email").value;
    var subject = document.getElementById("subject").value;
    var body = document.getElementById("body").value;
    if(trim(name) == "" ||
        trim(email) == "" ||
        trim(subject) == "" ||
        trim(body) == "") {
            alert("Please complete all fields");
    } else {
        if(isEmail(email)) {
            document.getElementById("submit").disabled=true;
            document.getElementById("submit").value='Please Wait..';
            sendRequest();
        } else {
            alert("Email appears to be invalid\nPlease check and try again");
            document.getElementById("email").focus();
            document.getElementById("email").select();
        }
    }
}

function handleResponse() {
    try{
    if((http.readyState == 4)&&(http.status == 200)){
        var response = http.responseText;
      document.getElementById("confirmation").innerHTML = response;
      document.getElementById("confirmation").style.display ="";
        }
  }
    catch(e){}
    finally{}
}

function isUndefined(a) {
   return typeof a == 'undefined';
}

function trim(a) {
    return a.replace(/^s*(S*(s+S+)*)s*$/, "$1");
}

function isEmail(a) {
   return (a.indexOf(".") > 0) && (a.indexOf("@") > 0);
}

PHP:

<?php
error_reporting(0);

$page_title = "Contact Us Form";
$email_it_to = "email@example.com";
$error_message = "Please complete the form first";
$confirmation = "Thank you, your message has been successfully sent.";

if(!isset($rnd) || !isset($name) || !isset($email) || !isset($subject) || !isset($body)) {
    echo $error_message;
    die();
}

    $email_from = $email;
    $email_subject = "Contact Form: ".stripslashes($subject);
    $email_message = "Please find below a message submitted by '".stripslashes($name);
    $email_message .="' on ".date("d/m/Y")." at ".date("H:i")."\n\n";
    $email_message .= stripslashes($body);

    $headers = 'From: '.$email_from."\r\n" .
   'Reply-To: '.$email_from."\r\n" .
   'X-Mailer: PHP/' . phpversion();

    mail($email_it_to, $email_subject, $email_message, $headers);

    echo "<b>$confirmation</b>";
    die();
?>

您没有使用$_POST变量来获取任何内容,而是使用了未设置的变量。

将所有呼叫更改为使用$_POST

if(!isset($rnd) || !isset($name) || !isset($email) || !isset($subject) || !isset($body))

改成:

if(!isset($_POST['rnd']) || !isset($_POST['name']) || !isset($_POST['email']) || !isset($_POST['subject']) || !isset($_POST['body']))

并且您需要在使用未定义变量的其他任何地方进行更改。

或者,您可以执行以下操作:

$rnd = mysql_real_escape_string($_POST['rnd']);
$name = mysql_real_escape_string($_POST['name']);
... and so on

尝试这个:

try{
    http.open('POST','pform.php?name='+name+'&email='+email+'&subject='+subject+'&body='+body+'&rnd='+rnd);
    http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    http.onreadystatechange = handleResponse;
}

使用$ _POST访问POST变量:

if (!isset($_POST["my_post_variable"]) {
 die('No post arguments passed.');
} 

这是因为Javascript是客户端脚本语言,而PHP是服务器端。 因此无法通过PHP直接访问javascript变量。

您可以通过以下方式访问HTML表单发布的值:

<?php
$var_name = $_POST['name_of_the_variable_to_access'];
//then access these variables in your code.
?>

您也可以在php脚本的开头尝试这一行代码,但是您需要确保未在php代码中重新分配变量值。

<?
extract($_POST);
//your code here.
?>

使用上面的代码,您将获得变量-$ Name,$ Email,$ Message中的HTML Page值。

而且,您需要在“消息”字段中命名。 最好只使用小写字母写名字

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM