I want to show error ie. Email already exists in database. If not show Thank you message.
I'm using ajax and jquery for this. Here is my code:
Ajax jquery:
<script type="text/javascript" >
$(function() {
var val_holder;
$("#subscribe").click(function() {
val_holder = 0;
var subscribe_mail = jQuery.trim($("#subscribe_mail").val()); // email field
var email_regex = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if(subscribe_mail == "") {
$(".error_message").html("This field is empty.");
val_holder = 1;
}
if(subscribe_mail != "") {
if(!email_regex.test(subscribe_mail)){ // if invalid email
$(".error_message").html("Your email is invalid.");
val_holder = 1;
}
}
if(val_holder == 1) {
return false;
}
val_holder = 0;
var dataString = '&subscribe_mail=' + subscribe_mail;
$.ajax({
type: "POST",
url: "ajax_subscribe.php",
data: dataString,
datatype: "json",
success: function(response) {
console.log(response);
if(response!= '')
{
$('.error_message').html(subscribe_mail + ' is already Exists.');
return true;
} else {
$('.error_message').html('Thanks For subscription!');
return false;
}
}
});
$("#subscribe_form")[0].reset();
return false;
});
});
And php file code is:
<?php error_reporting('E_ALL ^ E_NOTICE'); include('config.php');if($_POST) { $subscribe_mail = $_POST['subscribe_mail'];
$date = date('Y-m-d');
$q = mysql_query("select * from signups where signup_email_address='".$subscribe_mail."' ") or die(mysql_error());
$n = mysql_fetch_row($q);
if( $n>0 )
{
echo 'Already Exists';
}
else
{
$insert = mysql_query("insert into signups(signup_email_address,signup_date) values('$subscribe_mail','$date')") or die(mysql_error());
$from = 'sunshine.kapoor270#gmail.com';
$to = $subscribe_mail;
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= "From: " . $from . "\r\n"; // Sender's E-mail
$headers .= "Reply-to: " . $from . "\r\n";
$headers .= "Return-Path: $from\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$subject = "Thanks for Subscription";
$message = "Subscription email id : ".$subscribe_mail." ";
$sentmail = mail($to,$subject,$message,$headers);
$sentmail = mail($from,$subject,$message,$headers);
} } ?>
Only
if(response!= ''){$('.error_message').html(subscribe_mail + ' is already Exists.'); return true; }
this condition is working. its not going to else part if response is blank.
It depends on what you send back in your response when the user does not exist in database.
You can change the condition to:
if (!$.trim(response)){......
if the response is null or empty.
You should maybe delete your final ?> in your PHP-files because you can omit this. Those and the lines after the closing PHP-Tag are responsible for additional empty-chars/enters which make calinaadi´s answer a good one.
And you should check your includes for the same behaviour.
I would never check on nothing or empty strings and thatwhy reverse your if:
if(str.trim(response) == 'Already Exists') {
$('.error_message').html('Thanks For subscription!');
return false;
} elseif(str.trim(response) == 'New User') {
return true;
} else {
$('.error_message').html(subscribe_mail + ' is some strange unknown Stringoutput.');
return false;
}
Related
I am trying to get data from form, write with AJAX 'Thanks for your question' and send data to php script, and then with PHP insert data into database and send an email.My problem is that it always inserts empty rows into database. Do you have any advice?
enter image description here
forma - kontakt.php
<form>
<input type="text" name="ime" id="ime" placeholder="Ime" />
<input type="text" name="prezime" id="prezime" placeholder="Prezime" />
<input type="email" name="email" id="email" placeholder="Email" />
<textarea type="text" style="width:100%; height:180px" name="poruka" id="poruka" placeholder="Poruka"></textarea>
<button class="graybtn" onclick="return formamsg1()">Pošalji</button><br><br>
<div id="placefortable">
</div><br><br>
</form>
ajax - formamsg1
function formamsg1(){
var ime = document.getElementById("ime").value;
var prezime = document.getElementById("prezime").value;
var email = document.getElementById("email").value;
var poruka = document.getElementById("poruka").value;
var dataString = "ime="+encodeURIComponent(ime)+"&prezime="+encodeURIComponent(prezime)+"&email="+encodeURIComponent(email)+"&poruka="+encodeURIComponent(poruka);
$.ajax({
type:"post",
url: "obavestenje.php",
cashe: false,
data: dataString,
success: function(data){
//window.alert(data);
document.getElementById("placefortable").innerHTML = data;
},
error: function (req, status, err) {
console.log('Something went wrong', status, err);
}
})
return false;
}
PHP - obavestenje.php
require_once 'include/db.php';
$allowed_params = allowed_post_params(['ime', 'prezime', 'email', 'poruka', 'submit']);
// niz sadrzi dozvoljene maksimalne duzine za sva polja
$fields_lengths = ['ime' => 64, 'prezime' => 256, 'email'=>256, 'poruka' => 256];
// provera da li su polja odgovoarajuce duzine
foreach ($fields_lengths as $field => $length) {
if (!has_length($_POST[$field], ['min' => 0, 'max' => $length])) {
header('Location: greska.html');
die();
}
}
try {
// Priprema upita za unos podataka u bazu
$prep = $db->prepare("INSERT INTO kontakt_forma (ime, prezime, email, poruka) VALUES(:ime, :prezime, :email, :poruka)");
$prep->bindParam(':ime', $ime);
$prep->bindParam(':prezime', $prezime);
$prep->bindParam(':email', $email);
$prep->bindParam(':poruka', $poruka);
$ime = isset($allowed_params['ime']) ? $allowed_params['ime'] : "";
$prezime = isset($allowed_params['prezime']) ? $allowed_params['prezime'] : "";
$email = isset($allowed_params['email']) ? $allowed_params['email'] : "";
$poruka = isset($allowed_params['poruka']) ? $allowed_params['poruka'] : "";
// izvrsavanja upita
$rez = $prep->execute();
} catch (PDOException $e) {
echo 'greska kod upita';
}
// Ukoliko je upis u bazu uspesan, salje se mejl korisnuku i klijentu o uspesnoj prijavi
if ($rez) {
$emailod = "$email";
$email_to = 'milicapavlovic0312#gmail.com'; // treba da bude 'organictest#organic.milica-pavlovic.com';
$subject = "samo organsko";
$headers = "From: $emailod\r\n";
$headers .= "Content-type: text/html; charset=utf-8\r\n";
$email_message = "Kontakt forma " . "<br>";
$email_message .= "Ime: $ime " . "<br>";
$email_message .= "Prezime: $prezime " . "<br>";
$email_message .= "Poruka: $poruka " . "<br>";
if (mail($email_to, $subject, $email_message, $headers)) {
$htmltable = "Hvala na postavljenom pitanju. Ocekujte odgovor u roku od 24h.";
echo $htmltable;
} else {
echo 'greska kod slanja mail f';
die();
}
} else {
echo 'greska kod emaila-dva';
die();
}
You should send your data as Object not as String. Try changing JavaScript and PHP:
JavaScript File
function formamsg1(){
var ime = document.getElementById("ime").value;
var prezime = document.getElementById("prezime").value;
var email = document.getElementById("email").value;
var poruka = document.getElementById("poruka").value;
var data = {
"ime" : ime,
"prezime" : prezime,
"email" : email,
"poruka" : poruka
}
$.ajax({
type:"post",
url: "obavestenje.php",
cashe: false,
data: data,
success: function(data){
//window.alert(data);
document.getElementById("placefortable").innerHTML = data;
},
error: function (req, status, err) {
console.log('Something went wrong', status, err);
}
})
return false;
PHP File
require_once 'include/db.php';
try {
$ime = isset($_POST['ime']) ? $_POST['ime'] : "";
$prezime = isset($_POST['prezime']) ? $_POST['prezime'] : "";
$email = isset($_POST['email']) ? $_POST['email'] : "";
$poruka = isset($_POST['poruka']) ? $_POST['poruka'] : "";
// Priprema upita za unos podataka u bazu
$prep = $db->prepare("INSERT INTO kontakt_forma (ime, prezime, email, poruka) VALUES(:ime, :prezime, :email, :poruka)");
$prep->bindParam(':ime', $ime);
$prep->bindParam(':prezime', $prezime);
$prep->bindParam(':email', $email);
$prep->bindParam(':poruka', $poruka);
// izvrsavanja upita
$rez = $prep->execute();
} catch (PDOException $e) {
echo 'greska kod upita';
}
// Ukoliko je upis u bazu uspesan, salje se mejl korisnuku i klijentu o uspesnoj prijavi
if ($rez) {
$emailod = "$email";
$email_to = 'milicapavlovic0312#gmail.com'; // treba da bude 'organictest#organic.milica-pavlovic.com';
$subject = "samo organsko";
$headers = "From: $emailod\r\n";
$headers .= "Content-type: text/html; charset=utf-8\r\n";
$email_message = "Kontakt forma " . "<br>";
$email_message .= "Ime: $ime " . "<br>";
$email_message .= "Prezime: $prezime " . "<br>";
$email_message .= "Poruka: $poruka " . "<br>";
}
You're binding the Params before actually seeing if they have been posted.
And since all the data is wrapped in ime you won't be easily able to retrieve what is sent.
data: {
inputEmail: email,
inputPoruka: poruka
},
Ect
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.
Here is my php code below. When I click "send email" button it works fine. But it doesn't appear to my Inbox. It was routed to Spam folder:
<?php
function sendmail(){
$message = $_POST['message'];
$email = $_POST['email'];
$name = $_POST['name'];
$lastname = $_POST['lastname'];
$to = 'mpylla#gmail.com';
$subject = 'From :'.$email;
$message1 = 'From: '.$name."\nEmail: ".$email."\nMessage: ".$message;
mail($to, $subject, $message1);
}
sendmail();
?>
and this ajax script is in my HTML code:
$("#submit").click(function(e) {
var name = $("#name").val();
var lastname = $("#lastname").val();
var email = $("#email").val();
var message = $("#message").text();
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if (!emailReg.test(email)) {
alert('Ju lutem shkruan nje e-mail valide');
return false;
}
if (email.length == 0) {
alert("Email duhet te shenohet");
return false;
}
if (name.length == 0) {
alert("Emri duhet te shenohet");
return false;
}
if (lastname.length == 0) {
alert("Mbiemri duhet te shenohet");
return false;
}
if (message.length == 5) {
alert("Mesazhi duhet te shenohet");
return false;
} else {
$.ajax({
type: "POST",
url: "mail.php",
data: $("#myform").serialize(),
success: function(response) {
$("#sukses").fadeIn('slow');
setTimeout(function() {
$("#sukses").fadeOut('slow');
document.getElementById('myform').reset();
}, 100);
clearInterval();
}
});
}
e.preventDefault();
e.stopPropagation();
});
This is usually down to the content of the email itself and the type of mailbox you are sending the email to.
Each have various spam filters in place to restrict malicious emails. Take a look at this for some tips to help you.
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);
}
}
?>
Okay so i got this form in my website and when i test it and try to send an email message it says that the message has been sent but i dong get it to my email...
here are the codes:
contact.php:
<?php
function ValidateEmail($email)
{
$regex = '/([a-z0-9_.-]+)'. # name
'#'. # at
'([a-z0-9.-]+){1,255}'. # domain & possibly subdomains
'.'. # period
"([a-z]+){2,10}/i"; # domain extension
if($email == '') {
return false;
}
else {
$eregi = preg_replace($regex, '', $email);
}
return empty($eregi) ? true : false;
}
include 'config.php';
error_reporting (E_ALL ^ E_NOTICE);
$post = (!empty($_POST)) ? true : false;
if($post)
{
$name = stripslashes($_POST['name']);
$email = $_POST['email'];
$subject = stripslashes($_POST['subject']);
$message = stripslashes($_POST['message']);
$error = '';
if(!$name)
{
$error .= '<p>Please enter your name.</p>';
}
if(!$email)
{
$error .= '<p>Please enter an e-mail address.</p>';
}
if($email && !ValidateEmail($email))
{
$error .= '<p>Please enter a valid e-mail address.</p>';
}
if(!$subject || strlen($subject) < 2)
{
$error .= "<p>Please enter the subject.</p>";
}
if(!$message || strlen($message) < 2)
{
$error .= "<p>Please enter your message.</p>";
}
if(!$error)
{
$mail = mail(WEBMASTER_EMAIL, $subject, $message,
"From: ".$name." <".$email.">\r\n"
."Reply-To: ".$email."\r\n"
."X-Mailer: PHP/" . phpversion());
if($mail)
{
echo 'OK';
}
}
else
{
echo '<div id="notification">'.$error.'</div>';
}
}
?>
config.php:
<?php
// Change this to your email account
define("WEBMASTER_EMAIL", 'my mail address');
?>
form.js:
$(document).ready(function(){
$("#contactForm").submit(function(){
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "contact.php",
data: str,
success: function(msg){
$("#note").ajaxComplete(function(event, request, settings){
if(msg == 'OK')
{
result = '<div id="notification"><p>Your message has been sent. Thank you!</p></div>';
$('#contactForm').each (function(){
this.reset();
});
}
else
{
result = msg;
}
$(this).html(result);
});
}
});
return false;
});
});
Thanks!!
Change var str = $(this).serialize(); to data: $("#contactForm").serialize(),