I am using Opencart V2.0.1.1 for one project and i have a custom form in product page(.tpl). I want to send mail to store owner on submit of that form. I am able to process it and receiving the data till model but from model i am not able to send the mail and i am getting below error.
SyntaxError: Unexpected token < OK Notice: Undefined property:
Mail::$ErrorInfo in
/opt/lampp/htdocs/dutees/catalog/model/catalog/product.php on
line 784{"success":"success"}
Below is my code
// CONTROLLER FUNCTION
public function getquote()
{
$data = array(); $json = array();
if (isset($this->request->post['name'])) {
$data['name'] = $this->request->post['name'];
}
if (isset($this->request->post['email'])) {
$data['email'] = $this->request->post['email'];
}
if (isset($this->request->post['mobile'])) {
$data['mobile'] = $this->request->post['mobile'];
}
if (isset($this->request->post['address'])) {
$data['address'] = $this->request->post['address'];
}
if (isset($this->request->post['description'])) {
$data['description'] = $this->request->post['description'];
}
if($this->config->get('config_email') != 'null' || $this->config->get('config_email') !='')
$data['store_email'] = $this->config->get('config_email');
if($this->config->get('config_name') != 'null' || $this->config->get('config_name') !='')
$data['store_name'] = $this->config->get('config_name');
$this->load->model('catalog/product');
$gq_status = $this->model_catalog_product->sendQuote($data);
if($gq_status = "success"){
$json['success'] = "success";
}else{
$json['error'] = "Error : We are unable to send your request now, please use contact-us form";
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
// MODEL FUNTION
public function sendQuote($data = array()) {
$status = ""; $name ="";$email ="";$mobile ="";$address ="";$description ="";
if(isset($data['name']))
$name = $data['name'];
else
$name = "Not Available";
if(isset($data['email']))
$email = $data['email'];
else
$email = "Not Available";
if(isset($data['mobile']))
$mobile = $data['mobile'];
else
$mobile = "Not Available";
if(isset($data['address']))
$address = $data['address'];
else
$address = "Not Available";
if(isset($data['description']))
$description = $data['description'];
else
$description = "Not Available";
if(isset($data['store_email']))
$store_email = $data['store_email'];
else
$store_email = "abc#def.net";
if(isset($data['store_name']))
$store_name = $data['store_name'];
else
$store_name = "Enquiry";
$message = '
<html>
<body>
<MY HTML MAIL CONTENT GOES HERE>
</body>
</html>
';
$this->load->mail;
$mail = new Mail();
$mail->protocol = $this->config->get('config_mail_protocol');
$mail->parameter = $this->config->get('config_mail_parameter');
$mail->hostname = $this->config->get('config_smtp_host');
$mail->username = $this->config->get('config_smtp_username');
$mail->password = $this->config->get('config_smtp_password');
$mail->port = $this->config->get('config_smtp_port');
$mail->timeout = $this->config->get('config_smtp_timeout');
$mail->setTo($store_email);
$mail->setFrom($email);
$mail->setSender($store_name);
$mail->setSubject("Product Get Quote");
//$mail->setText("test message body text");
$mail->setHtml($message);
if(!$mail->send()) {
$status = 'Mailer Error: ' . $mail->ErrorInfo;
} else {
$status = 'success';
}
return $status;
}
// VIEW AJAX
<script>
$('#gq-submit').click(function(){
var name=$('#gq-name').val();
var email=$('#gq-email').val();
var mobile=$('#gq-mobile').val();
var address=$('#gq-address').val();
var description=$('#gq-description').val();
if(name != '' && email != ''&& mobile != '' && description != ''){
$.ajax({
type:'post',
url:'index.php?route=product/product/getquote',
dataType: 'json',
data:'name='+name+'&email='+email+'&mobile='+mobile+'&address='+address+'&description='+description,
beforeSend: function() {
$('#gq-submit').button('loading');
},
complete: function() {
$('#gq-submit').button('reset');
},
success: function(json) {
$('.alert-success, .alert-danger').remove();
$('.form-group').removeClass('has-error');
if (json['error']) {
$('#gq-showcheck').after('<div class="alert alert-danger"><i class="fa fa-exclamation-circle"></i> ' + json['error'] + '</div>');
}
if (json['success']) {
$('#gq-showcheck').after('<div class="alert alert-success"><i class="fa fa-check-circle"></i> ' + json['success'] + '<button type="button" class="close" data-dismiss="alert">×</button></div>');
}
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});}else{
$('#gq-showcheck').after('<div class="alert alert-danger"><i class="fa fa-exclamation-circle"></i> ' + "Please fill all the fields" + '</div>');
}
});
</script>
You can't send mail, maybe the mail settings are incorrect and
the Opencart own Mail class hasn't any ErrorInfo field inside it.
See: system/library/mail.php
First of all set the the correct mail parameters and don't use $mail->ErrorInfo because it doesn't exist. When error occured during sending mail it calls a trigger_error.
Related
I have a contact form that is performing validation on the back end, what I want to check for is if the user has successfully completed the captcha or not and if not print an error message.
Currently, I am getting an error message:
Notice: Undefined index: g-recaptcha-response in /var/www/html/mangoForm.php on line 99
So it isn't printing the error message that is in the JSON:
{"success":false,"errors":{"captcha":"ReCaptcha is required."}}
Line 99:
$captcha = checkCaptcha($formData['g-recaptcha-response']);
Code Block in Question:
if (!empty($validationMSG)) {
return $validationMSG;
}
else {
$captcha = checkCaptcha($formData['g-recaptcha-response']);
if(!$captcha['isSuccess']){
$validationMSG['captcha'] = 'ReCaptcha is required.';
return $validationMSG;
}
//End of Validation Function
}
}
Full Code:
<?php
//show errors - enable this
//ini_set('display_errors', 1);
//ini_set('display_startup_errors', 1);
//error_reporting(E_ALL);
//Var Dump (Debugging)
//var_dump($_POST);
//Load Required Components
require_once 'src/recaptcha_autoload.php';
require_once "functions.php";
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'src/Exception.php';
require 'src/PHPMailer.php';
require 'src/SMTP.php';
function validate($formData)
{
// Initiate Array
$validationMSG = array(); // array to hold validation errors
$pname_exp = '/^[a-zA-Z0-9\_]{2,20}/';
if (!isset($formData['firstName'])) {
$validationMSG['firstName'] = 'First Name is required.';
}elseif (!preg_match($pname_exp, $formData['firstName'])){
$validationMSG['firstName'] = 'First Name is not valid.';
}
// Validate lastName
if (!isset($formData['lastName'])) {
$validationMSG['lastName'] = 'Last Name is required.';
}
// Check RegEx for Last Name
elseif (!preg_match($pname_exp, $formData['lastName'])) {
$validationMSG['lastName'] = 'Last Name is not valid.';
}
// Validate companyName
if (!isset($formData['companyName'])) {
$validationMSG['companyName'] = 'Company Name is required.';
}
// Validate companyAddress
if (!isset($formData['companyAddress'])) {
$validationMSG['companyAddress'] = 'Company Address is required.';
}
// Validate state
if (!isset($formData['state'])) {
$validationMSG['state'] = 'State is required.';
}
// Validate city
if (!isset($formData['city'])) {
$validationMSG['city'] = 'City is required.';
}
// Validate Zipcode - If Field is Empty
if (!isset($formData['zipcode'])) {
$validationMSG['zipcode'] = 'Zipcode is required.';
}
// Validate emailAddress
if (!isset($formData['emailAddress'])) {
$validationMSG['emailAddress'] = 'Email Address is required.';
}
// Check if emailAddress is a valid email address
elseif (!filter_var($formData['emailAddress'], FILTER_VALIDATE_EMAIL)) {
$validationMSG['emailAddress'] = 'Email address is not valid.';
}
//Validate phoneNumber
if (!isset($formData['phoneNumber'])) {
$validationMSG['phoneNumber'] = 'Phone Number is required.';
}
//Validate phoneNumber
elseif (preg_match("/^[0-9]{3}-[0-9]{4}-[0-9]{4}$/", $formData['phoneNumber'])) {
$validationMSG['phoneNumber'] = 'Must be a valid phone number.';
}
var_dump($formData);
// Validate message
if (!isset($formData['message'])) {
$validationMSG['message'] = 'Message is required.';
}
if (!empty($validationMSG)) {
return $validationMSG;
}
else {
$captcha = checkCaptcha($formData['g-recaptcha-response']);
if(!$captcha['isSuccess']){
$validationMSG['captcha'] = 'ReCaptcha is required.';
return $validationMSG;
}
//End of Validation Function
}
}
function checkCaptcha($g_recaptcha_response)
{
$recaptcha_secret_key = 'REDACTED';
$recaptcha = new \ReCaptcha\ReCaptcha($recaptcha_secret_key);
$resp = $recaptcha->verify($g_recaptcha_response, $_SERVER['REMOTE_ADDR']);
return [
'isSuccess' => $resp->isSuccess(),
'errorCodes' => $resp->getErrorCodes(),
];
}
function sendMail($formData)
{
$mail = new PHPMailer(true); // Passing `true` enables exceptions
// Server settings
//$mail->SMTPDebug = 2; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.server.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'user#server.com'; // SMTP username
$mail->Password = 'REDACTED'; // SMTP password
$mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465; // TCP port to connect to
// Recipients
$mail->setFrom('user#server.com', 'Mailer');
$mail->addAddress('user#server.com', 'Joe User'); // Add a recipient
// Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'New Message from Contact Form';
// prepare email body
$body_message = "";
$body_message.= "Sender IP: " . get_client_ip() . "<br />";
// #todo: make the other rows the same way, i.e. $formData['key'];
$body_message.= "First Name: " . $formData['firstName'] . "<br />";
$body_message.= "Last Name: " . $formData['lastName'] . "<br />";
$body_message.= "Company Name: " . $formData['companyName'] . "<br />";
$body_message.= "Company Address: " . $formData['companyAddress'] . "<br />";
$body_message.= "City: " . $formData['city'] . "<br />";
$body_message.= "State: " . $formData['state'] . "<br />";
$body_message.= "Sender email: " . $formData['emailAddress'] . "<br />";
$body_message.= "Sender Phone: " . $formData['phoneNumber'] . "<br />";
$body_message.= "\n\n" . $formData['message'];
$mail->Body = $body_message;
$mail->send();
}
/////////////////////////////////////////////////
// process
//this will be our whole response (jsoned later)
$response = [
//we'll change these later, possibly:
'success' => false,
'errors' => [],
// 'message' => 'There has been an issue sending your message!!!!',//could be an "OK" error message as well, depends on the 'success' key.
];
// Copy $_POST to $formData
//$formData = $_POST;
//$formData = json_decode($_POST, true);
$formData = json_decode(file_get_contents("php://input"), true);
//validate
$errors = validate($formData);
if(!empty($errors)){
$response['success'] = false;
$response['errors'] = $errors;
}else {//it's ok
//send it
try{
sendMail($formData);
//Print Success Message
$response['success'] = true;
$response['message'] = 'Message was Sent!';
}
catch(Exception $e) {
// Print phpMailer Error Message
$response['success'] = false;
$response['message'] = 'There has been an issue sending your message';
}
}
echo json_encode($response);
exit;
How I can achieve where the PHP script checks for a successful response from Google ReCaptcha and either permits the script to go on further in the event of a success or print an error message?
EDITED JS:
document.querySelector("#form").addEventListener("submit", function(e){
//create variable for contact form url
var formURL = 'mangoForm.php';
//prevent default submission
event.preventDefault();
//define form fields
var mangoForm = {
'firstName' : document.querySelector('input[name=firstName]').value,
'lastName' : document.querySelector('input[name=lastName]').value,
'companyName' : document.querySelector('input[name=companyName]').value,
'companyAddress' : document.querySelector('input[name=companyAddress]').value,
'city' : document.querySelector('input[name=city]').value,
'state' : document.querySelector('select[name=state]').value,
'zipcode' : document.querySelector('input[name=zipcode]').value,
'emailAddress' : document.querySelector('input[name=emailAddress]').value,
'phoneNumber' : document.querySelector('input[name=phoneNumber]').value,
'message' : document.querySelector('input[name=message]').value,
}
//define request variable
var formRequest = new Request(formURL, {
method: 'POST',
body: JSON.stringify(mangoForm),
headers: {
"content-type":"application/json; charset=utf-8"
}
});
//fetch
fetch(formRequest)
//console.log(formRequest)
.then(function(formResponse) {
return formResponse.json();
})
.then(function(data) {
//handle server responses
if ( ! data.success) {
//handle error messages
//handle error message for firstName
//console.log(data);
if (data.errors.firstName && !document.querySelector('#firstName-group .help-block')) {
document.getElementById("firstName-group").classList.add("has-error");
let helpBlock = document.createElement('div');
helpBlock.classList.add('help-block');
helpBlock.innerHTML = data.errors.firstName;
document.getElementById("firstName-group").append(helpBlock);
}
//handle errors for lastName
if (data.errors.lastName && !document.querySelector('#lastName-group .help-block')) {
document.getElementById("lastName-group").classList.add("has-error");
let helpBlock = document.createElement('div');
helpBlock.classList.add('help-block');
helpBlock.innerHTML = data.errors.lastName;
document.getElementById("lastName-group").appendChild(helpBlock);
}
//handle errors for companyName
if (data.errors.companyName && !document.querySelector('#companyName-group .help-block')) {
document.getElementById("companyName-group").classList.add("has-error");
let helpBlock = document.createElement('div');
helpBlock.classList.add('help-block');
helpBlock.innerHTML = data.errors.companyName;
document.getElementById("companyName-group").appendChild(helpBlock);
}
//handle errors for companyAddress
if (data.errors.companyAddress && !document.querySelector('#companyAddress-group .help-block')) {
document.getElementById("companyAddress-group").classList.add("has-error");
let helpBlock = document.createElement('div');
helpBlock.classList.add('help-block');
helpBlock.innerHTML = data.errors.companyAddress;
document.getElementById("companyAddress-group").appendChild(helpBlock);
}
//handle errors for city
if (data.errors.city && !document.querySelector('#city-group .help-block')) {
document.getElementById("city-group").classList.add("has-error");
let helpBlock = document.createElement('div');
helpBlock.classList.add('help-block');
helpBlock.innerHTML = data.errors.city;
document.getElementById("city-group").appendChild(helpBlock);
}
//handle errors for state
if (data.errors.state && !document.querySelector('#state-group .help-block')) {
document.getElementById("state-group").classList.add("has-error");
let helpBlock = document.createElement('div');
helpBlock.classList.add('help-block');
helpBlock.innerHTML = data.errors.state;
document.getElementById("state-group").appendChild(helpBlock);
}
//handle errors for zipcode
if (data.errors.zipcode && !document.querySelector('#zipcode-group .help-block')) {
document.getElementById("zipcode-group").classList.add("has-error");
let helpBlock = document.createElement('div');
helpBlock.classList.add('help-block');
helpBlock.innerHTML = data.errors.zipcode;
document.getElementById("zipcode-group").appendChild(helpBlock);
}
//handle errors for emailAddress
if (data.errors.emailAddress && !document.querySelector('#emailAddress-group .help-block')) {
document.getElementById("emailAddress-group").classList.add("has-error");
let helpBlock = document.createElement('div');
helpBlock.classList.add('help-block');
helpBlock.innerHTML = data.errors.emailAddress;
document.getElementById("emailAddress-group").appendChild(helpBlock);
}
//handle errors for phoneNumber
if (data.errors.phoneNumber && !document.querySelector('#phoneNumber-group .help-block')) {
document.getElementById("phoneNumber-group").classList.add("has-error");
let helpBlock = document.createElement('div');
helpBlock.classList.add('help-block');
helpBlock.innerHTML = data.errors.phoneNumber;
document.getElementById("phoneNumber-group").appendChild(helpBlock);
}
//handle errors for message
if (data.errors.message && !document.querySelector('#message-group .help-block')) {
document.getElementById("message-group").classList.add("has-error");
let helpBlock = document.createElement('div');
helpBlock.classList.add('help-block');
helpBlock.innerHTML = data.errors.message;
document.getElementById("message-group").appendChild(helpBlock);
}
// handle errors for captcha ---------------
if (data.errors.captcha) {
swal({
title: "Error!",
text: data.errors.captcha,
icon: "error",
});
}
// handle errors for phpmailer ---------------
if (data.message) {
swal({
title: "Error!",
text: data.message,
icon: "error",
});
}
if (data.success) {
swal({
title: "Success!",
text: data.message,
icon: "success",
});
//document.getElementById("form").reset();
}
}
});
})
As mentioned by #marv255 there actually is no captcha data in your request apparently.
So try adding this:
'g-recaptcha-response' : grecaptcha.getResponse()
Just below
'message' : document.query ...
In your js file.
I want to clear the input values when the form is submitted correctly, But there is a problem, if not inserted, the inputs are erased.
I will be grateful for help me.
This is my code:
$(document).ready(function(){
$("#Insert").click(function(){
var email = $("#email").val();
var title = $("title").val();
var text = $("text").val();
var cSend = true;
$.post("ajax.php",{email:email,title:title,text:text,cSend:cSend},function(data){
$("#contactResualt").html(data);
});
});
});
//ajax.php
if(isset($_POST['cSend'])){
if (empty($_POST['email']) || empty($_POST['title']) || empty($_POST['text'])){
echo '<div class="alert alert-warning">Fill empty fields</div>';
}
else{
$email = $_POST['email'];
$title = $_POST['title'];
$text = $_POST['text'];
$Contactus = new Contactus();
$resualt = $Contactus->SendPM($email,$title,$text);
if($resualt){
echo '<div class="alert alert-success">Insertion was successful</div>';
}
else{
echo '<div class="alert alert-warning">Insertion failed</div>';
}
}
}
So, I just want the information to be correctly inserted, Inputs will be cleared.
If you only want to erase the fields when the insert was successful, you can put an indicator attribute into the response HTML:
if($resualt) {
echo '<div class="alert alert-success" data-success="true">Insertion was successful</div>';
}
else {
echo '<div class="alert alert-warning" data-success="false">Insertion failed</div>';
}
Then use the indicator in the AJAX callback to determine whether you should reset the form:
$.post("ajax.php", {
email: email,
title: title,
text: text,
cSend: cSend
}, function(data) {
$("#contactResualt").html(data);
if($("#contactResualt [data-success]").attr("data-success") === "true") {
$("#email, #title, #text").val("");
}
});
You can clear the input field by using $('input').val('');
$(document).ready(function(){
$("#Insert").click(function(){
var email = $("#email").val();
var title = $("title").val();
var text = $("text").val();
var cSend = true;
$.post("ajax.php",
{email:email,title:title,text:text,cSend:cSend},function(data){
var json_obj = $.parseJSON(data);//parse JSON
$("#contactResualt").html(json_obj.msg);
if(json_obj.status){
$('input').val('');
}
});
});
});
Ajax.php
if(isset($_POST['cSend'])){
if (empty($_POST['email']) || empty($_POST['title']) ||
empty($_POST['text'])){
$result['status'] = false;
$result['msg'] = '<div class="alert alert-warning">Fill empty
fields</div>';
}
else{
$email = $_POST['email'];
$title = $_POST['title'];
$text = $_POST['text'];
$Contactus = new Contactus();
$resualt = $Contactus->SendPM($email,$title,$text);
if($resualt){
$result['status'] = true;
$result['msg'] = '<div class="alert alert-success">Insertion was successful</div>';
}
else{
$result['status'] = false;
$result['msg'] = '<div class="alert alert-warning">Insertion failed</div>';
}
}
echo json_encode($result);
}
After send my form data to php file its return if any error found. But its also return success before ajax redirect page. I want display error message only and if success, redirect another page.
ajax:
$("#msform").submit(function(){
$.ajax({
type:"post",
url:"pagesubmit.php",
data: $("#msform").serialize(),
dataType : 'json',
success: function(data){
if ( ! data.success) {
$(".help-block").fadeIn().html(data.error);
} else {
$(".help-block").fadeOut();
$("#msform")[0].reset();
window.location = 'http://dbsvawdez.com/' + data.success;
}
}
});
});
php:
include_once ("db.php");
global $dbh;
function check($name){
if(!$name || strlen($name = trim($name)) == 0){
$error ="* Username not entered";
}
else{
$name = stripslashes($name);
if(strlen($name) < 5){
$error ="* Name below 5 characters";
}
else if(!preg_match("/^([0-9a-z])+$/i", $name)){
$error ="* Name not alphanumeric";
}
else {
return 1;
}
}
}
$name = mysqli_real_escape_string($dbh, $_POST['name']);
$thisname = strtolower($name);
$retval = check($thisname);
if($retval ==1){ // if no error found
$success ='upage/userpage?user='.$_SESSION['username'].'';
}
$data = array();
$data['error'] = $error;
$data['success'] = $success;
if (!empty($data)) {
echo json_encode($data);
}
Solved the problem, in this way:
Ajax:
$("#msform").submit(function(){
// collect input name
ver name = var catag=$('#name').val();
$.ajax({
type:"post",
url:"pagesubmit.php",
data: $("#msform").serialize(),
success: function(data){
if ( data != 'success') {
$(".help-block").fadeIn().html(data);
} else {
$(".help-block").fadeOut();
$("#msform")[0].reset();
window.location = 'http://dbsvawdez.com/' + name;
}
}
});
});
php:
function check($name){
if(!$name || strlen($name = trim($name)) == 0){
echo "* Username not entered";
}
else{
$name = stripslashes($name);
if(strlen($name) < 5){
echo "* Name below 5 characters";
}
else if(!preg_match("/^([0-9a-z])+$/i", $name)){
echo "* Name not alphanumeric";
}
else {
return 1;
}
}
}
$name = mysqli_real_escape_string($dbh, $_POST['name']);
$thisname = strtolower($name);
$retval = check($thisname);
if($retval ==1){ // if no error found
echo 'success';
}
EDIT
Set your variables $success and $error
$success = "";
$error= "";
If you doesn't init them, you cannot use them and the .=operator is for concatenation not for set.
Then you should encode the response in php in JSON.
Something like
$response = json_encode(
array(
'success'=> true,
'route' => "mypage/info?user=$_SESSION['username']"
)
);
And return this, then access your response like you already do :
var success = response.success;
UPDATE
change this code to add an else statement :
if($retval ==1){ // if no error found
$success ='upage/userpage?user='.$_SESSION['username'].'';
}else{
$success = 'error';
}
and this line :
else {
return 1;
}
to :
else {
$error = 'none';
}
and in your javascript :
$("#msform").submit(function(){
$.ajax({
type :"post",
url :"pagesubmit.php",
data : $("#msform").serialize(),
dataType : 'json',
success : function(data){
if(data.success == 'error') {
$(".help-block").fadeIn().html(data.error);
}else{
$(".help-block").fadeOut();
$("#msform")[0].reset();
window.location = 'http://dbsvawdez.com/' + data.success;
}
}
});
});
After submitting a form with ajax the returned result appears on a new page. The chrome console returns me an error in almost every element: it is not a function validates, but php insert them and shows the result displayed in this new page.
$(document).ready(function () {
$('#newsletter').submit(function(e){
var $this = $(this);
e.preventDefault();
$response = $('#response'),
$mail = $('#email'),
testmail = /^[^0-9][A-z0-9._%+-]+([.][A-z0-9_]+)*[#][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}$/,
hasError = false;
$response.find('p').remove();
if (!testmail.test($mail.val())) {
$response.html('<p class="error">Please enter a valid email</p>');
hasError = true;
}
if (hasError === false) {
$response.find('p').remove();
$response.addClass('loading');
$.ajax({
type: "POST",
dataType: 'json',
cache: false,
url: $this.attr('action'),
data: $this.serialize()
}).done(function (data) {
console.log(data);
$response.removeClass('loading');
$response.html('<p>'+data.message+'</p>');
}).fail(function() {
$response.removeClass('loading');
$response.html('<p>An error occurred, please try again</p>');
})
}
return false;
});
});
php code
<?php
$host = "";
$dbname = "";
$user = "";
$pass = "";
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$datetime = date('Y-m-d H:i:s');
try {
$db = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
if (empty($email)) {
$status = "error";
$message = "The email address field must not be blank";
} else if (!preg_match('/^[^0-9][A-z0-9._%+-]+([.][A-z0-9_]+)*[#][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}$/', $email)) {
$status = "error";
$message = "You must fill the field with a valid email address";
} else {
$existingSignup = $db->prepare("SELECT COUNT(*) FROM signups WHERE signup_email_address='$email'");
$existingSignup->execute();
$data_exists = ($existingSignup->fetchColumn() > 0) ? true : false;
if (!$data_exists) {
$sql = "INSERT INTO signups (signup_email_address, signup_date) VALUES (:email, :datetime)";
$q = $db->prepare($sql);
$q->execute(
array(
':email' => $email,
':datetime' => $datetime
));
if ($q) {
$status = "success";
$message = "You have been successfully subscribed";
} else {
$status = "error";
$message = "An error occurred, please try again";
}
} else {
$status = "error";
$message = "This email is already subscribed";
}
}
$data = array(
'status' => $status,
'message' => $message
);
echo json_encode($data);
$db = null;
}
catch(PDOException $e) {
echo $e->getMessage();
}
The error displayed: undefinied is not a function in
$response = $('#response'),
$mail = $('#email'),
var $this = $(this);
Message displayed in blank page:
{"status":"success","message":"You have been successfully subscribed"}
Solved. Now works fine in another way, but I would like to know the mistake.
This works
(function ($, window, document, undefined) {
'use strict';
var $form = $('#newsletter');
var $response = $('#response');
$form.submit(function (e) {
var formData = {
'news' : $('input[name="news"]').val(),
'email' : $('input[name="email"]').val(),
};
$.ajax({
type : 'POST',
url : 'news.php',
data : formData,
dataType : 'json',
encode : true
}).done(function (data) {
if (!data.success) {
$('#response').html(data);
$response.html('<div class="alert alert"><button class="close" data-dismiss="alert">x</button>' + data.message + '</div>');
} else {
$('#response').html(data);
$response.html('<div class="alert alert"><button class="close" data-dismiss="alert">x</button>' + data.message + '</div>');
}
}).fail(function (data) {
response.html('<div class="alert alert-error"><button class="close" data-dismiss="alert">x</button>' + data.message + '</div>');
// for debug
console.log(data)
});
e.preventDefault();
});
}(jQuery, window, document));
i try to create a contact form in jquery php 4 phonegap, my problem how can i have response success from php? or if i can try other solutions but havent ideas 4 for the moment ^^
thx a lot
p.s. the form works (if i delete response success form js)
index.js
$(document).on('pageinit', function() {
$('#send').click(function() {
var url = 'send02.php';
var error = 0;
var $contactpage = $(this).closest('.ui-page');
var $contactform = $(this).closest('.contact-form02');
$('.required', $contactform).each(function(i) {
if($(this).val() === '') {
error++;
}
});
// each
if(error > 0) {
alert('Inserisci tutti i campi obbligatori segnati con asterisco*.');
} else {
var email = $contactform.find('input[name="email"]').val();
var datetime = $contactform.find('input[name="datetime"]').val();
var mobilephone = $contactform.find('input[name="mobilephone"]').val();
var selectnative4 = $contactform.find('select[name="selectnative4"]').val();
var message = $contactform.find('textarea[name="message"]').val();
//submit the form
$.ajax({
type : "POST",
url : url,
data : {
email : email,
datetime : datetime,
mobilephone : mobilephone,
selectnative4 : selectnative4,
message : message
},
success : function(data) {
if(data == 'success') {
// show thank you
$contactpage.find('.contact-thankyou').show();
$contactpage.find('.contact-form').hide();
} else {
alert('Impossibile inviare il messaggio. Per piacere riprova.');
}
}
});
//$.ajax
}
return false;
});
});
and send.php
<?php
header('content-type: application/json; charset=utf-8');
if (isset($_GET["email"])) {
$email = strip_tags($_GET['email']);
$datetime = strip_tags($_GET['datetime']);
$mobilephone = strip_tags($_GET['mobilephone']);
$selectnative4 = strip_tags($_GET['selectnative4']);
$message = strip_tags($_GET['message']);
$header = "From: ". $firstname . " <" . $email . ">rn";
$ip = $_SERVER['REMOTE_ADDR'];
$httpref = $_SERVER['HTTP_REFERER'];
$httpagent = $_SERVER['HTTP_USER_AGENT'];
$today = date("F j, Y, g:i a");
$recipient = 'mark#facebook.com';
$subject = 'Prenotazione Online';
$mailbody = "
Nominativo: $email
Telefono: $mobilephone
data prenotazione: $datetime
Scelta dal Menù: $selectnative4
Messaggio: $message
in data: $today
";
$result = 'success';
if (mail($recipient, $subject, $mailbody, $header)) {
echo json_encode($result);
}
}
?>