拨开荷叶行,寻梦已然成。仙女莲花里,翩翩白鹭情。
IMG-LOGO
主页 文章列表 如果包含jQuery档案,为什么PHPPDObindParam回传null

如果包含jQuery档案,为什么PHPPDObindParam回传null

白鹭 - 2022-02-16 1934 0 0

在每个页面上,我都有 jQuery 模式,其中包含一个联系表单,并且在每个页面上都需要将资料发送到不同的电子邮件地址。提交表单时,我需要使用json_encode. 同时在每一页上我使用的页面识别符号$pages_id=1$pages_id=2等等,对于识别的形式提交。然而,非常重要的是,没有 jQuery 档案,完成我的 PHP 代码,它正确执行,所有资料都成功插入到数据库中,在 Xdebug 中,我还看到它成功执行的每一行上的代码。但是,如果我包含 jQuery 档案,那么在 Xdebug 中$pages_id回传 null 的值。我正是在这行代码中认为:

$query = "SELECT owners_email.email_address_id, email_address, owner_name, owner_property, owner_sex, owner_type FROM visitneum.owners_email INNER JOIN visitneum.pages ON (pages.email_address_id = owners_email.email_address_id) WHERE `owner_sex`='M' AND `owner_type`='other' AND `pages_id` = ?";
$dbstmt = $pdo->prepare($query);
$dbstmt->bindParam(1,$pages_id);
$dbstmt->execute();

但是,下面是我完整的 PHP 代码:

<?php
// set error reporting
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL | E_STRICT);

$fname = $tel = $userMail = $userMessage = $email_address_id = "";
$fname_error = $tel_error = $userMail_error = $userMessage_error = "";
$error=false;
//Load the config file
$dbHost = "secret";
$dbUser = "secret";
$dbPassword = "secret";
$dbName = "secret";
$dbCharset = "utf8";
$pdo="";
try{
    $dsn = "mysql:host=" . $dbHost . ";dbName=" . $dbName . ";charset=" . $dbCharset;
    $pdo = new PDO($dsn, $dbUser, $dbPassword);
    array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8");
    $pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}catch(PDOException $e){
    echo "Connection error: " . $e->getMessage();
}
use PHPMailer\PHPMailer\PHPMailer;
require 'PHPMailer/PHPMailer.php';
require 'PHPMailer/SMTP.php';
require 'PHPMailer/Exception.php';
if($_SERVER['REQUEST_METHOD'] == 'POST'){
if(isset($_POST['submitOwner'])){
    $fname = $_POST['fname'];
    $tel = $_POST['tel'];
    $userMail = $_POST['userMail'];
    $userMessage = $_POST['userMessage'];
if(empty($_POST['fname'])){
        $error=true;
        $fname_error = "Name and surname cannot be empty!";
    }else{
        $fname = $_POST['fname'];   
        if(!preg_match("/^[a-z?????A-Z?????\s]*$/", $fname)){
            $fname_error = "Name and surname can only contain letters and spaces!";
        }
    }
    if(empty($_POST['tel'])) {
        $tel_error = "Phone number cannot be blank!";
    }else{
        $tel = $_POST['tel'];
        if(!preg_match('/^[\ ]?[0-9]{9,15}$/', $tel)) {
            $tel_error = "The phone number should contain a minimum of 9 to 15 numbers!";
        }
    }
if(empty($_POST['userMail'])){
        $userMail_error = "Email cannot be blank!";
    }else{
        $userMail = $_POST['userMail'];
        if(!filter_var($userMail, FILTER_VALIDATE_EMAIL)) {
            $userMail_error = "Email address is incorrect!";
        }
    }
    if(empty($_POST['userMessage'])) {
        $userMessage_error = "The content of the message cannot be empty!";
    }else{
        $userMessage = $_POST['userMessage'];
        if(!preg_match("/^[a-z?????A-Z?????0-9 ,.!?\'\"]*$/", $userMessage)){
            $userMessage_error = "The content of the message cannot be special characters!";
        }
    }
if($fname_error == '' && $tel_error == '' && $userMail_error == '' && $userMessage_error == ''){
    $mail = new PHPMailer(true);
    $mail->CharSet = "UTF-8";
    $mail->isSMTP();
    $mail->Host = 'secret';
    $mail->SMTPAuth = true;
    $mail->Username = 'secret';
    $mail->Password = 'secret';
    $mail->Port = 465; // 587
    $mail->SMTPSecure = 'ssl'; // tls
    $mail->WordWrap = 50;  
    $mail->setFrom('secret@secret.com');
    $mail->Subject = "New message from visit-neum.com";
    $mail->isHTML(true);
    $query = "SELECT owners_email.email_address_id, email_address, owner_name, owner_property, owner_sex, owner_type FROM visitneum.owners_email INNER JOIN visitneum.pages ON (pages.email_address_id = owners_email.email_address_id) WHERE `owner_sex`='M' AND `owner_type`='other' AND `pages_id` = ?";
$dbstmt = $pdo->prepare($query);
$dbstmt->bindParam(1,$pages_id); 
$dbstmt->execute(); //in Xdebug this line of code return NULL for $pages_id if include jQuery file
$emails_other = $dbstmt->fetchAll(PDO::FETCH_ASSOC);
$jsonData=array();
    if(is_array($emails_other) && count($emails_other)>0){
      foreach($emails_other as $email_other){
        //var_dump($email_other['email_address']);
        $mail->addAddress($email_other['email_address']);
        $body_other = "<p>Dear {$email_other['owner_name']}, <br>" . "You just received a message from the site <a href='https://www.visit-neum.com'>visit-neum.com</a><br>Details of your message are below:</p><p><strong>From: </strong>" . ucwords($fname) . "<br><strong>Phone: </strong>" . $tel . "<br><strong>E-mail: </strong>" .strtolower($userMail)."<br><strong>Message: </strong>" . $userMessage . "</p>";
$mail->Body = $body_other;
if($mail->send()){
            
            $mail = "INSERT INTO visitneum.contact_owner(fname, tel, userMail, userMessage, email_address_id) VALUES(:fname, :tel, :userMail, :userMessage, :email_address_id)";
            $stmt = $pdo->prepare($mail);
            $stmt->execute(['fname' => $fname, 'tel' => $tel, 'userMail' => $userMail, 'userMessage' => $userMessage, 'email_address_id' => $email_other['email_address_id']]);

                // Load AJAX
                if($error==false){
                    $information['response'] = "success";
                    $information['content'] = "Thanks " . ucwords($fname) . "! Your message has been successfully sent to the owner of property! You will get an answer soon!";
                    $jsonData[] = $information;
                }
}//end if mail send         
else{   
    $information['response'] = "error";
    $information['content'] = "An error has occurred! Please try again..." . $mail->ErrorInfo;
    $jsonData[]=$information;  
}
echo(json_encode($jsonData));
} // end foreach($emails_other as $email_other)
} // end if(is_array($emails_other) && count($emails_other)>0)
} // end if validation
} // end submitOwner
} // end REQUEST METHOD = POST

在下面你可以看到我的 jQuery 档案的 submitHandler 这导致了我的问题:

 submitHandler: function(form){  
      var formData=jQuery("#contactOwner").serialize();
      console.log(formData);
      jQuery.ajax({
        url: "/inc/FormProcess.php",
        type: "post",
        dataType: "json",
        data: formData,
      success:function(jsonData) {
         jQuery("#responseOwner").text(jsonData.content);
         console.log(jsonData);
      error: function (jqXHR, textStatus, errorThrown) {
                    console.log(JSON.stringify(jqXHR));
                    console.log("AJAX error: "   textStatus   ' : '   errorThrown);
                  }
      }); // Code for AJAX Ends
// Clear all data after submit
      var resetForm = document.getElementById('contactOwner').reset();
      return false;
    } // end submitHandler

包含联系表格的页面如下:

<?php
include_once './inc/FormProcess.php';
?>
<form  spellcheck="false" autocomplete="off" autocorrect="off" id='contactOwner' class='form' name='contactOwner' action='' method='POST'>
<h4 id="responseOwner" class="success">
<!-- This will hold response from the server --></h4>
  <fieldset>
    <legend>Va?i podaci</legend>
        <div class="form-control halb InputIconBg"><input minlength="6" type="text" class="input username" name="fname" placeholder="Your name and surname ..." value="<?php echo Input::get('fname'); ?>"><i class="fas fa-user" aria-hidden="true"></i><span class="error"><?=$fname_error; ?></span></div><!-- end .form-control -->
            
        <div class="form-control halb InputIconBg"><input minlength="9" type="text" class="input phone" name="tel" placeholder="Your phone number..." value="<?php echo Input::get('tel'); ?>"><i class="fas fa-phone-alt" aria-hidden="true"></i><span class="error"><?=$tel_error; ?></span></div><!-- end .form-control -->

        <div class="form-control single InputIconBg"><input type="text" class="input mail" name="userMail" placeholder="Your e-mail..." value="<?php echo Input::get('userMail'); ?>" autocomplete="email"><i id="" class="fas fa-envelope owner_icon" aria-hidden="true"></i><span class="error"><?=$userMail_error; ?></span></div><!-- end .form-control --> 
            
        <div class="form-control InputIconBg"><textarea maxlength="1000" name="userMessage" class="textinput message" cols="46" rows="8" placeholder="Your message..."><?php echo Input::get('userMessage'); ?></textarea><i class="fas fa-pencil-alt owner_icon" aria-hidden="true"></i><span class="error"><?=$userMessage_error; ?></span></div><!-- end .form-control -->
            
    </fieldset>
    <input type="submit" class="btn_submit" id="submitOwner" name="submitOwner" value="SENT"/>
</form>
<script defer src="/JS/validateOwner.js"></script>

所以,我无法弄清楚是什么问题以及为什么 $pages_id 在包含 jQuery 档案时回传 null。另外,我忘记提到行内的代码if(is_array($emails_other) && count($emails_other)>0){回传编号 0,因此不会执行完整的后续代码,但这当然是正常的,因为 $pages_id 为空。但是,我希望有人了解问题所在,因此,在此先感谢您提供的任何帮助。

uj5u.com热心网友回复:

page_id 在您的脚本中为空,因为您没有在脚本中设定它。

那么为什么不直接在您的 froms 中添加一个带有页面 id 的隐藏输入栏位,然后在您的 PHP 代码中添加

$page_id = $_POST['pageId'];


我想你没有理解ajax correclty。如果您将资料发布到 /inc/FormProcess.php,它不像以前的包含,您可以先创建变量然后包含它。AJax 就象是对脚本的子呼叫。就像你只打开 URL 中提供的这个脚本一样。所以在这一点上你没有你的变量。

您需要获取变量或将您的 ajax 请求发送到您定义变量的脚本而不是 /inc/FormProcess.php

标签:

0 评论

发表评论

您的电子邮件地址不会被公开。 必填的字段已做标记 *