PHPMailer multiple sending mail - php

Im using pop3 php mailler and ajax. There is no problem for sending mail but when I press sent mail button it incease number of mails. So whats the problem
my ajax code :
$("button").click(function(e){
$('.alert').slideUp(100);
e.preventDefault();
var dataArray = $("form").serialize();
$.ajax({
type: "POST",
url: "include/login.php",
dataType: "json",
data: dataArray,
success: function (data) {
if(data.result == "true"){
$('.alert').removeClass('alert-danger').addClass('alert-success').slideDown(200);
$('.alert strong').html("hello "+data.name);
setTimeout(function(){
window.location.replace("<?php if(isset($_SERVER['HTTP_REFERER'])) { echo "$_SERVER[HTTP_REFERER]";}else{echo "index.php";} ?>");
}, 1200);
}else if(data.result == "false"){
$('.alert').removeClass('alert-success').addClass('alert-danger').slideDown(200);
$('.alert strong').html(data.name);
}else if(data.result == "warning"){
$('.alert').removeClass('alert-warning').addClass('alert-danger').slideDown(200);
$('.alert strong').html(data.name);
/// send mail button click
$('body').on('click','#activation',function(e){
e.preventDefault();
$.ajax({
beforeSend:function(){
$('.alert strong').html("sending mail..");
},
url:"include/activation_mail.php",
type:"post",
data:{u_id:data.userid,u_pass:data.u_pass},
success:function(msj){
$('.alert').removeClass('alert-danger').addClass('alert-success').slideDown(200);
setTimeout(function(){
$('.alert strong').html(msj);
},1000);
},
});
});
}
},
});
});
mailing php :
$sql = "UPDATE users SET u_activation_code = '$activation_code' WHERE u_id = '$u_id'";
$query = mysqli_query($con,$sql);
if($query){
$sql="SELECT * FROM users WHERE u_id='$u_id'";
$query = mysqli_query($con,$sql);
$row = mysqli_fetch_row($query);
$id = $row[0];
$name = $row[1];
$surname = $row[2];
$fullname = "$row[1] $row[2]";
$username = $row[5];
$email = $row[6];
$icerik = "aktivasyon maili <a href=''>activation</a>";
$mail = new PHPMailer();
$mail->CharSet='utf-8';
$mail->setFrom('fragman#aktivasyon', 'Aktivasyon');
$mail->addReplyTo('mymail#gmail.com', 'activation');
$mail->addAddress($email,$fullname);
$mail->Subject = 'activation link';
$mail->AltBody = 'This is a plain-text message body';
$mail->Body = "click active <a href=''>clicked</a> ";
//send the message, check for errors
if (!$mail->send()) {
echo "error sending: " . $mail->ErrorInfo;
} else {
echo "send mail";
}
}else{
echo "error query";
}
where is problem ?

Because of this line:
$('body').on('click','#activation',function(e){
On every click on a button, you're binding another click event to #activation making it run multiple times on every click on that button. You should bind the click event ONCE.
You could also do:
$('body').off('click','#activation');
And then bind the click event again, to prevent it from happening.
EDIT
You're binding a click event for every BUTTON element existing in the DOM:
$("button").click(function(e){
I also suggest that you specify this event to a button with unique ID, and not for every button. Because when you click on the #activation button, it will ALSO trigger the call to the login ajax (Since it's also a button element)
What you should do is to add an ID attribute to the button that when you click on trigger the login ajax:
<button id="login-btn">Log In</button>
And then, change the above binding to:
$("#login-btn").click(function(e){ // INSTEAD OF THE CURRENT $("button").click(function(e){

Related

how to exact output in ajax

My code is working well but problem in output. I don't get exact output that i want.
$("#search_traveller_button").click(function(){
$.ajax({
url: "index.php?act=checkSessionUser",
type: "POST",
cache: false,
success: function(data){
console.log(data);
},
error:function(){
console.log("Error: Unknown Error");
}
});
});
PHP code:
<?php
if(isset($_SESSION['userId'])) {
echo "1";
} else {
echo "0";
}
?>
output in success gives also html code, why?
0 </div>
<footer class="nav navbar-inverse">
...........
</footer>
</body>
</html>
I want in my output only 0 in a variable, not html code.
The problem is with your php code here's an example php code. You need to encode as JSON this lets jQuery .success or .fail have a JSON response as a callback.
What I am doing is I have a php file and a js file.
PHP
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$msg = $_POST['message'];
$nospace_name = trim($_POST['name']);
$nospace_email = trim($_POST['email']);
$nospace_message = trim($_POST['message']);
if (empty($nospace_name))
$errors['name'] = "Name field is required.";
if (empty($nospace_email))
$errors['email'] = "Email field is required.";
if (empty($nospace_message))
$errors['message'] = "I would love to see your message.";
if (!empty($nospace_email) && !preg_match("^[a-zA-Z0-9_\-\.]+#[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$^", $nospace_email))
$errors['bad_email'] = "Please enter a valid email address";
// if there are any errors in our errors array, return a success boolean of false
if (!empty($errors)) {
// if there are items in our errors array, return those errors
$data['success'] = false;
$data['errors'] = $errors;
}
else {
// if there are no errors process our form, then return a message
// prepare message to be sent
$to = "me#example.com";
$subject = "Website Contact Form: ".$name;
// build the message
$message = "Name: ".$name."\n\n";
$message .= "Email: ".$email."\n\n";
$message .= "Message: ".$msg;
// send it
$mailSent = mail($to, $subject, $message, $headers);
// check if mail was sent successfully
if (!$mailSent) {
$errors['unknown_error'] = "Something went wrong...Please try again later";
$data['success'] = false;
$data['errors'] = $errors;
}
else {
// show a message of success and provide a true success variable
$data['success'] = true;
$data['message'] = "Thank you for contacting me, I\'ll get back to you soon!";
}
}
// return all our data to an AJAX call
echo json_encode($data);
?>
JS
$(function() {
$("#contactForm").submit(function(e) {
$.ajax({
type: 'POST',
url: 'contact.php',
data: $(this).serialize(),
dataType: "json"
})
.done(function(msg) {
if (msg.success == true) {
response = '<div class="success">' + msg.message + '</div>';
$contactform.hide();
}
else {
response = '<div class="error">' + msg.errors + '</div>';
}
// Show response message.
$("#contactForm").prepend(response);
})
e.preventDefault();
});
});
Because the php is successful in returning a result.
The error would be triggered if the php failed to return.
If you want your Ajax handler to do something different if not logged in either specify in the Ajax handler (not recommended) or do it on the server side (in the php) returning what you want if they are not authenticated.
$("#search_traveller_button").click(function(){
$.ajax({
url: "index.php?act=checkSessionUser",
type: "POST",
cache: false,
success: function(data){
if (data==1){
console.log ("yeah it worked")
}else {
console.log ("error")
}
});
});

When submiting a contact us form I wanted to stay in this cantact form

I am new in HTML and PHP, I have created a contact form for the users where they can add their messages. When they click on the send button I want the page to stay on this contact form and show a text message below that says it is succesfully sent. Here is my code some of it .
if (isset($_POST['submit']))
{
if (!isset($_POST['name'])) {
echo "please enter the name";
}else {
if (!isset($_POST["emailaddress"])) {
echo "please enter the email adresse ";
}else {
if (!isset($_POST["subject"])) {
echo " Please enter the message ";
} else {
$nom = $_POST['name'];
$email = $_POST['emailaddress'];
$msg = $_POST['subject'];
$sql = "INSERT INTO contacts (name, email, message) VALUES ('$nom', '$email', '$msg') ";
if (!mysql_query($sql)){
die ('error : ' . mysql_error());
} else {
mysql_close($link);
?>
</br></br>
<p25><center>sent succesfully! thanks</center></p25>s
<?php
echo "<script>setTimeout(\"location.href = 'no-sidebar.php'\",8000);</script>";
You need to understand each line of code.
if (!isset($_POST['name'])) {
echo "please enter the name";
}
The page will get reloaded on the first instance.
You need to do the form validation part in javascript. In this way, if some validation error happens, it can be displayed somewhere in the page without reloading it.
Then send the data to php through ajax, where you set your model and pass it to database and send a response back to javascript which can then print the message that the form has been submitted successfully.
Here's what I'm saying:
<input type="text" id="email" />
<button id="submit">Submit</button>
<div id="status"></div>
Javascript Part:
$(document).ready(function(){
$('#submit').on('click', function(){
var email = $('#email').val();
if(email.trim().length === 0){
$('#status').html('Email not provided');
}else{
$.ajax({
type : 'POST',
data : {action: 'sendData' , email : email}, // object
url : 'example.php',
cache: false,
success: function(response){
$('#status').html(response);
}
});
}
});
});
And in the php side, then you can just get the value which is already validated and return true or false based on your data insertion result to database.
example.php
<?php
if(isset($_POST['action']) && $_POST['action'] == 'sendData'){
$email = $_POST['email'];
if(dbinsertion successful){
echo "Success";
}else{
echo "Something went wrong";
}
}
?>
You have to use jquery here. Hope you understood.

Submit form using Ajax and Swiftmailer

I am using ajax to submit a form using swiftmailer. I'm getting an error when I try to submit the form. I think it has something to do with the "data" setting in the ajax call. I can get the swiftmailer mailing script to work fine when submitting a form not using ajax. You can see my work here, http://wickbuildings.com/form. I'm stuck and any help would be appreciated!
Here is my javascript:
$(document).ready(function () {
$("button#send_btn").click(function(){
$.ajax({
type: "POST",
url: "/assets/js/mailers/become-a-builder.php",
data: $('form[name=BecomeBuilderForm]').serialize(),
success: function(msg){
$("#thanks").html(msg) //hide button and show thank you
$("#form-content").modal('hide'); //hide modal
},
error: function(){
alert("failure");
}
});
});
});
and my swiftmailer mailing script:
<?php
//grab named inputs from html then post to #thanks
if (isset($_POST['name'])) {
$email_dsm = strip_tags($_POST['email_dsm']);
$name = strip_tags($_POST['name']);
$business_name = strip_tags($_POST['business_name']);
$address = strip_tags($_POST['address']);
$city = strip_tags($_POST['city']);
$state = strip_tags($_POST['state']);
$zip = strip_tags($_POST['zip']);
$phone = strip_tags($_POST['phone']);
$email = strip_tags($_POST['email']);
$comments = strip_tags($_POST['comments']);
// create message that fills #thanks container
echo "<div class=\"alert alert-success\" >Thank you for your inquiry. " . $email_dsm . " will be following up with you shortly.</div>";
// Create message of email to recipient
$body = "the contents of the email here";
require_once '../plugins/swiftmailer/swift_required.php';
// Create the mail transport configuration
$transport = Swift_SendmailTransport::newInstance('/usr/sbin/sendmail -bs');
// Create the message
$message = Swift_Message::newInstance();
$message->setTo(array(
'user#somedomain.com'
));
$message->setSubject('my email subject here');
$message->setBody($body, 'text/html');
$message->setFrom($Email);
// Send the email
$mailer = Swift_Mailer::newInstance($transport);
$mailer->send($message);
}
?>
Forms don't need names. give it an ID.
<form id="BecomeBuilderForm">
then use:
$('#BecomeBuilderForm').serialize()
or if you really want to use the name add double quotes around BecomeBuilderForm
$('form[name="BecomeBuilderForm"]').serialize()
if you really get stuck make sure your form is serializing using console.log()
$(document).ready(function () {
$("button#send_btn").click(function(){
console.log($('form[name="BecomeBuilderForm"]').serialize());
});
});

Send data from php back to Ajax

So I submit my form with Ajax like so
$("#submitform").click(function(e){
e.preventDefault();
var form_data = $("#contactfrm").serialize();
$.ajax({
type: "POST",
url: "/ltlcreation-new/wordpress/wp-content/themes/LTLCreation/includes/form-handler.php",
data: form_data,
error: function(){
alert("failed");
},
success: function(json_data){
console.log(json_data);
alert("success");
},
})
});
In my form-handler.php i catch the from errors
<?php
if(isset($_POST['submit'])) {
//include validation class
include 'validate.class.php';
//assign post data to variables
$name = #($_POST['name']);
$email = #($_POST['email']);
$message = #($_POST['message']);
$phone = #($_POST["phone"]);
//echo $name, $email, $message, $phone;
//start validating our form
$v = new validate();
$v->validateStr($name, "name", 3, 75);
$v->validateEmail($email, "email");
$v->validateStr($message, "message", 5, 1000);
$v->validateStr($phone, "phone", 11, 13);
if(!$v->hasErrors()) {
$to = "lukelangfield001#googlemail.com";
$subject = "Website contact form ";
$mailbody = $message . "\n" . "from " . $name . "\n" . $phone;
$headers = "From: $email";
mail($to, $subject, $mailbody, $headers);
echo "success";
} else {
//set the number of errors message
$message_text = $v->errorNumMessage();
//store the errors list in a variable
$errors = $v->displayErrors();
//get the individual error messages
//$nameErr = $v->getError("name");
//$emailErr = $v->getError("email");
//$messageErr = $v->getError("message");
//$phoneErr = $v->getError("phone");
echo $message_text; echo $errors;
$output = array($message_text);
echo json_encode($output);
}//end error check
}// end isset
These errors usually look like something like this
There were 4 errors sending your message!
Name must be at least 3 characters long.
Please enter an Email Address.
Message must be at least 5 characters long.
Phone must be at least 11 characters long.
["There were 4 errors sending your message!\n"]
I've tried to jSon encode the output and the in the success in ajax pull the json data out, however it just keeps returning an empty string like so
(an empty string)
My question is can you send data back from PHP to Ajax, if so I am doing this completely wrong?
You can output anything other than the json string so echo "success"; would make t. Use your debuggers Network response output tab to see that this is properly encoded.
Also don't use
$name = #($_POST['name']);
use instead
$name = isset($_POST['name']) ? $_POST['name'] : '';
If you still have a blank page make sure you have display errors set.
error_reporting(E_ALL);
ini_set('display_errors', 1);
I am an idiot I still had this in my PHP file which means the form wasn't firing or returning a response, silly me, glad i finally figured it out though
if(isset($_POST['submit'])) {
Thanks for the help guys
Here is an example of an Ajax contact form you can use:
Ajax.js
$(document).ready(function(){
$("#btn").click(function(){
var username=$("#name").val();
var email=$("#email").val();
var dis=$("#dis").val();
var process=true;
if(username=="")
process=false;
if(email=="")
process=false;
if(dis=="")
process=false;
if(process){
var dataString="name="+username + "&email="+email+ "&message="+dis;
$("#res").html('<span>Sending...</span><img src="a.gif">');
$.ajax({
url:"b.php",
type:"POST",
data:dataString,
success:function(data){
document.getElementById("name").value='';
document.getElementById("email").value='';
document.getElementById("dis").value='';
$("#res").html(data);
}
});
}else{
alert("fill all fields");
}
});
});
and b.php
<?php
mysql_connect("localhost","root","");
mysql_select_db("ajax") || die("erro");
if(isset($_POST['name'])){
mysql_real_escape_string(htmlentities($name=$_POST['name']));
mysql_real_escape_string(htmlentities($email=$_POST['email']));
mysql_real_escape_string(htmlentities($message=$_POST['message']));
if(!empty($name) && !empty($email) && !empty($message)){
if(mysql_query("INSERT INTO `users` (name,email,message) VALUES('$name','$email','$message') ")){
echo 'The massage has been send';
}else{
echo mysql_error();
}
}
}
?>
enjoy that....
You have the following:
success: function(json_data){
While json_data is simply nothing. It should be
success: function(data){

jQuery Post via Ajax to PHP Validation Script

I know I can use the form validation plugin with jQuery UI but for the sake of teaching myself some new tricks I'm taking this approach.
I have a jQuery script that posts a form to a PHP script via Ajax. The script then validates the input and sends a JSON encoded string back to the script. At this point, based on the status a validation message should be placed into a modal dialog and then opened to tell the user what happened.
Issue
It seems the script is returning a "null" status. In Chrome's JavaScript console the following line appears after clicking on the submit button of the form:
Uncaught TypeError: Cannot read property 'status' of null
Here's my validate_form.js
$(document).ready(function() {
$("#contact_submit").on("click", function(e){
e.preventDefault();
var dataString = $("#frm_contact").serialize();
console.log(dataString);
$.ajax({
type: "POST",
url: "contact.php",
data: dataString,
dataType: "json",
cache: false,
success: function(data){
console.log(data);
if(!data){
alert("null value returned");
}else if(data.status > 0){
$("#response").dialog({
autoOpen: false,
modal: true,
height: 240,
width: 320
});
$("#response").dialog("open");
};
}
});
});
});
And here is contact.php
<?php
if(isset($_POST['contact_submit'])){
$name = trim($_POST['contact_name']);
$name = ucwords($name);
$email = trim($_POST['contact_email']);
$email = strtolower($email);
$dept = trim($_POST['contact_dept']);
$dept = ucwords($dept);
$notes = trim($_POST['contact_notes']);
// Patterns and Comparison Qualifiers
$name_pattern = "/^[a-z][a-z ]*$/i";
$email_pattern = "/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/";
$avail_depts = array("General", "Sales", "Support");
$notes_minlength = 25;
$notes_maxlength = 500;
if(!preg_match($name_pattern, $name)){
$resp = array("status"=>1, "message"=>"Names may only contain letters and spaces");
}else{
if(!preg_match($name_pattern, $name)){
$resp = array("status"=>2, "message"=>"Invalid e-mail address");
}else{
if(!in_array($dept, $avail_depts)){
$resp = array("status"=>3, "message"=>"Please select a department");
}else{
if(strlen($notes) < $notes_minlength || strlen($notes) > $notes_maxlength){
$resp = array("status"=>4, "message"=>"Comments must be between 25 and 500 characters");
}else{
// Build the message and e-mail it
$to = "info#mydomain.com";
$headers = "From: ".$name." <".$email.">";
$message .= "Contact Form Submission\n";
$message .= "==========================\n\n";
$message .= "Contact Name: ".ucwords($name)."\n\n";
$message .= "Contact E-mail: ".$email."\n\n";
$message .= "Category: ".$dept."\n\n";
$message .= "Comments: ".$notes."\n\n";
$message .= "\n";
if(mail($to, $subject, $message, $headers)){
$resp = array("status"=>5, "message"=>"Thanks! We'll be in touch soon!");
}else{
$resp = array("status"=>6, "message"=>"Something went wrong, please try again");
}
}
}
}
}
}
echo json_encode($resp);
?>
UPDATE 1
Adding console.log(dataString); yields the following in the console:
contact_name=Test&contact_email=testaccount%40mydomain.com&contact_dept=general&contact_notes=this+is+a+test+
As you can see it should've failed on the notes not being between 25 and 500 characters and returned the proper error message. Instead I still see the "cannot read property 'status' of (null)"
UPDATE 2
Here is exactly what I see in the JavaScript Console
UPDATE 3
I decided to remove the prevent default and actually post directly to the contact page through a traditional <form> statement that includes the method="post" action="contact.php" to see if the script itself was properly generating the JSON string and it is; here's what it generated on my most recent test:
{"status":4,"message":"Comments must be between 25 and 500 characters"}
So either it's not sending it back to the ajax handler or something else is missing.
UPDATE 4
I modified the script to handle a null value and alert me if no value was passed. So it's obvious now that the script isn't passing a json string back to the ajax call even though in update 3 I've verified that it's echoing one to the screen. I'm at a loss... (Update script above)
UPDATE 5
So I've made some progress. It turns out that the null was being returned because in my PHP script I was checking if the submit button was set and part of the $_POST array. But, because I'm preventing the default action of the form through jQuery it's not being passed. Only the form values that are serialized are being sent in the dataString. So now I'm getting the errors back in the console that I expect but I'm not getting the modal dialog to show up. The drama continues.
Most browsers support JSON.parse(), which is defined in ECMA-262 5th Edition (the specification that JS is based on). Its usage is simple:
var json = '{"result":true,"count":1}',
obj = JSON.parse(json);
alert(obj.count);
For the browsers that don't you can implement it using json2.js.
As noted you're already using jQuery, there is a $.parseJSON function that maps to JSON.parse if available or a form of eval in older browsers. However, this performs additional, unnecessary checks that are also performed by JSON.parse, so for the best all round performance I'd recommend using it like so:
var json = '{"result":true,"count":1}',
obj = JSON && JSON.parse(json) || $.parseJSON(json);
This will ensure you use native JSON.parse immediately, rather than having jQuery perform sanity checks on the string before passing it to the native parsing function.
Below i've mentioned some points try this to sort out your problem
1.change your method to get and try.
2.put die() after last echo and check what the exactly output.
So after more hours tweaking, testing, and pulling my hair out, here's the working script.
jQuery
$(document).ready(function() {
$("#contact_submit").on("click", function(e){
e.preventDefault();
var dataString = $("#frm_contact").serialize();
console.log(dataString);
$.ajax({
type: "POST",
url: "contact.php",
data: dataString,
dataType: "json",
cache: false,
success: function(data){
console.log(data);
if(!data){
alert("null value returned");
}else if(data.err > 0){
var $response = $("<div></div>")
.dialog({
resizable: false,
autoOpen: false,
modal: true,
height: "auto",
width: "auto",
buttons: { "ok": function() { $(this).dialog("close"); } }
});
$response.html("Error:");
$response.html(data.message);
$response.dialog("open");
$(".ui-dialog-titlebar").hide();
};
}
});
});
});
And for the PHP script I had to tweak it slightly as well to process it properly.
<?php
$name = trim(urldecode($_POST['contact_name']));
$name = ucwords($name);
$email = trim(urldecode($_POST['contact_email']));
$email = strtolower($email);
$dept = trim($_POST['contact_dept']);
$dept = ucwords($dept);
$notes = trim(urldecode($_POST['contact_notes']));
// Patterns and Comparison Qualifiers
$name_pattern = "/^[a-z][a-z ]*$/i";
$email_pattern = "/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/";
$avail_depts = array("General", "Sales", "Support");
$notes_minlength = 25;
$notes_maxlength = 500;
if(!preg_match($name_pattern, $name)){
$resp = array("err"=>1, "message"=>"Names may only contain letters and spaces");
}else{
if(!preg_match($email_pattern, $email)){
$resp = array("err"=>2, "message"=>"Invalid e-mail address");
}else{
if(!in_array($dept, $avail_depts)){
$resp = array("err"=>3, "message"=>"Please select a department");
}else{
if(strlen($notes) < $notes_minlength || strlen($notes) > $notes_maxlength){
$resp = array("err"=>4, "message"=>"Comments must be between 25 and 500 characters");
}else{
// Build the message and e-mail it
$headers = "From: ".$name." <".$email.">";
$message .= "Contact Form Submission\n";
$message .= "==========================\n\n";
$message .= "Contact Name: ".ucwords($name)."\n\n";
$message .= "Contact E-mail: ".$email."\n\n";
$message .= "Category: ".$dept."\n\n";
$message .= "Comments: ".$notes."\n\n";
$message .= "\n";
if(mail($to, $subject, $message, $headers)){
$resp = array("err"=>5, "message"=>"Thanks! We'll be in touch soon!");
}else{
$resp = array("err"=>6, "message"=>"Something went wrong, please try again");
}
}
}
}
}
echo json_encode($resp);
?>
Everything works perfectly, modal alerts and all to the user. Thanks to those who attempted to help!

Categories