On every page I have jQuery modal which contains a contact form and which on every page need sent data to different email address. When a form is submitted I need to display successful response using json_encode
. Also on every page I use page identifier as $pages_id=1
, $pages_id=2
, etc., for identify which form is submitted. However, very important, without jQuery file, complete my PHP code it's executed correctly, all data are successfully inserted into database and in Xdebug I also see that code on every line it's executed successfully. But, if I include jQuery file then in Xdebug the value for $pages_id
return null. I exactly think at this line of code:
$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();
However, below is my complete PHP code:
<?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('[email protected]');
$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
And below you can see submitHandler for my jQuery file which causes me problem:
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
And the page which contains contact form is below:
<?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" >
<!-- This will hold response from the server --></h4>
<fieldset>
<legend>Vaši podaci</legend>
<div ><input minlength="6" type="text" name="fname" placeholder="Your name and surname ..." value="<?php echo Input::get('fname'); ?>"><i aria-hidden="true"></i><span ><?=$fname_error; ?></span></div><!-- end .form-control -->
<div ><input minlength="9" type="text" name="tel" placeholder="Your phone number..." value="<?php echo Input::get('tel'); ?>"><i aria-hidden="true"></i><span ><?=$tel_error; ?></span></div><!-- end .form-control -->
<div ><input type="text" name="userMail" placeholder="Your e-mail..." value="<?php echo Input::get('userMail'); ?>" autocomplete="email"><i id="" aria-hidden="true"></i><span ><?=$userMail_error; ?></span></div><!-- end .form-control -->
<div ><textarea maxlength="1000" name="userMessage" cols="46" rows="8" placeholder="Your message..."><?php echo Input::get('userMessage'); ?></textarea><i aria-hidden="true"></i><span ><?=$userMessage_error; ?></span></div><!-- end .form-control -->
</fieldset>
<input type="submit" id="submitOwner" name="submitOwner" value="SENT"/>
</form>
<script defer src="/JS/validateOwner.js"></script>
So, I can not figure out what is the problem and why $pages_id return null when include jQuery file. Also, I was forget to mention that code inside line if(is_array($emails_other) && count($emails_other)>0){
return number 0, so complete seguent code isn't executed, but of course this is normal, because $pages_id is null. However, I hope that somebody understand what is the problem and so, thanks in advance for any kind of help that you can give me.
CodePudding user response:
page_id is null in your script because you dont set it in the script.
So why not just adding an hidden input field in your froms with the page id and then in your PHP code
$page_id = $_POST['pageId'];
i think you did not understood ajax correclty. if you post your data to /inc/FormProcess.php it is not like an include before, where you could create variables first and then include it. AJax is like a sub call to the script. it is like if you would open ONLY this scrirpt provided in URL. so at this point you dont have your variables.
you need to get the variables or send your ajax request NOT to /inc/FormProcess.php but to the script where you define the variable