I have problems :
My code for emailing is working, but I don't think its the right way to do so. Is it possible to use the $http service inside an AngularJS foreach loop? Will it overheat the process, if each loop is destined to PhpMailer to send one mail each time? Should I use the $q service? The code works to send a low amount of emails but will it overheat the php script if more emails are sent?
AngularJS code
$scope.submit = function(contactform) {
$scope.submitted = true;
$scope.submitButtonDisabled = true;
angular.forEach($scope.intervenants,function(data){
var x = angular.copy($scope.formData);
x.destinataire = data.email;
$http({
method : 'POST',
url : 'contact-form.php',
data : $.param(x), //param method from jQuery
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } //set the headers so angular passing info as form data (not request payload)
}).success(function(data){
console.log(data);
if (data.success) { //success comes from the return json object
$scope.submitButtonDisabled = true;
$scope.resultMessage = data.message;
$scope.result='bg-success';
} else {
$scope.submitButtonDisabled = false;
$scope.resultMessage = data.message;
$scope.result='bg-danger';
}
});
});
}
PhpMail code
//check if any of the inputs are empty
if (empty($_POST['inputName']) || empty($_POST['inputEmail']) || empty($_POST['inputSubject']) || empty($_POST['inputMessage'])) {
$data = array('success' => false, 'message' => 'Please fill out the form completely.');
echo json_encode($data);
exit;
}
//create an instance of PHPMailer
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Host = "smtp.orange.fr";
$mail->From = $_POST['inputEmail'];
$mail->FromName = $_POST['inputName'];
$mail->AddAddress($_POST['destinataire']); //recipient
$mail->Subject = $_POST['inputSubject'];
$mail->Body = "Name: " . $_POST['inputName'] . "\r\n\r\nMessage: " . stripslashes($_POST['inputMessage']);
if (isset($_POST['ref'])) {
$mail->Body .= "\r\n\r\nRef: " . $_POST['ref'];
}
if(!$mail->send()) {
$data = array('success' => false, 'message' => 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo);
echo json_encode($data);
exit;
}
$data = array('success' => true, 'message' => 'Thanks! We have received your message.');
echo json_encode($data);
} else {
$data = array('success' => false, 'message' => 'Please fill out the form completely.');
echo json_encode($data);
}
Related
Here is my php script for the registration page, the data is still being entered into the correct table but this problem is persistent.
Edit: I've seen comments asking for the javascript code, I've included it below the php code now.
`<?php
session_start();
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: *");
main();
function main(){
require 'connectToDB.php';
// echo "\nreached the php file";
$response = array("code" => 0, "message" => "");
$request = file_get_contents('php://input');
$jsonRequest = json_decode($request);
var_dump($jsonRequest);
if (checkForExistingUser($conn, $jsonRequest) != 0){
$response["code"] = 2;
$response["message"] = "User already exists";
}
// else if($response["code"] == 1){
// // $userID = $conn->lastInsert();
// // header("Location: UniqueUserID.php");
// exit;
// }
else{
$response = addUser($conn, $jsonRequest);
// header("Location: UniqueUserID.php");
exit;
}
// printf(json_encode($response));
// var_dump($response);
$conn = null;
return json_encode($response);
}
function checkForExistingUser ($conn, $jsonRequest){
$stmt = $conn->prepare("
SELECT COUNT(Email) as noOfUsers
FROM user_main
WHERE Email = :confirmemailadd");
// $stmt -> bindParam(':confirmemailadd', $jsonRequest->confirmemailadd);
if (isset($jsonRequest->confirmemailadd)) {
$stmt->bindValue(':confirmemailadd', $jsonRequest->confirmemailadd);
} else {
$stmt->bindValue(':confirmemailadd', '');
}
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
$results = $stmt->fetchAll();
$noOfResults = $results[0]["noOfUsers"];
// echo($noOfResults);
return $noOfResults;
}
function addUser($conn, $jsonRequest){
$response = array("code"=>0, "message"=>"");
// echo ("Reached addUser \n");
$firstname = sanitise($jsonRequest->firstname);
$surname = sanitise($jsonRequest->surname);
$username = sanitise($jsonRequest->username);
$confirmemailadd = sanitise($jsonRequest->confirmemailadd);
$phonenum = sanitise($jsonRequest->phonenum);
$retypepassword = sanitise($jsonRequest->retypepassword);
function encryptPassword($retypepassword) {
$key = openssl_random_pseudo_bytes(32);
$iv = openssl_random_pseudo_bytes(16);
$encrypted = openssl_encrypt($retypepassword, 'AES-256-CBC', $key, 0, $iv);
$hash = hash_hmac('sha256', $encrypted, $key);
return $hash . ':' . base64_encode($iv) . ':' . base64_encode($encrypted);
}
$stmt = $conn->prepare("
INSERT INTO user_main (Name, Surname, Username, Email, PhoneNum, PWD)
VALUES (:firstname, :surname, :username, :confirmemailadd, :phonenum, :retypepassword) ");
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':surname', $surname);
$stmt->bindParam(':username', $username);
$stmt->bindParam(':confirmemailadd', $confirmemailadd);
$stmt->bindParam(':phonenum', $phonenum);
$stmt->bindParam(':retypepassword', $retypepassword);
try{
$stmt->execute();
$userID = $conn->lastInsertId();
$response["code"] = 1;
$response["message"] = "successfully added";
$response["user_id"] = $userID;
}
catch (PDOException $e){
$response["code"] = 0;
$response["message"] = $e->getMessage();
}
// echo json_encode($response);
return $response;
}
function sanitise($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
`
I'm still relatively new to the back-end development side of things but I cannot figure this one out, I've tried to google it and research other solutions on stack overflow but couldn't find anything useful
document.addEventListener('DOMContentLoaded', function () {
const form = document.querySelector('form');
form.addEventListener('submit', handleFormSubmit);
}, false)
function handleFormSubmit(event) {
event.preventDefault();
checkEmails();
checkPasses();
processForm();
// redirectToPage()
}
function checkEmails(){
var emailValue = document.getElementById("emailadd").value;
var retypeEmailValue = document.getElementById("confirmemailadd").value;
if (emailValue !== retypeEmailValue){
window.alert("Emails do not match.");
}
}
function checkPasses(){
var passValue = document.getElementById("password").value;
var retypeValue = document.getElementById("retypepassword").value;
if (passValue !== retypeValue){
window.alert("Passwords do not match.");
}
}
function processForm(){
var userDetails = gatherData()
console.log(userDetails);
postRequest(userDetails)
}
function gatherData(){
//gather the data from the form fields into JSON
var userDetails = {
firstname : document.getElementById("firstname").value,
surname : document.getElementById("surname").value,
username : document.getElementById("username").value,
confirmemailadd: document.getElementById("confirmemailadd").value,
phonenum: document.getElementById("phonenum").value,
retypepassword: document.getElementById("retypepassword").value,
}
return userDetails;
}
async function postRequest(userDetails){
// make an AJAX POST request to server
try{
const response = await fetch("../php/register.php",{
method: 'POST',
headers: {
'Origin' : 'http://localhost/',
'Content-Type': 'application/json', // sent request
'Accept': 'application/json' // expected data sent back
},
body: JSON.stringify(userDetails),
});
const data = await response.json();
console.log(data);
handleResponseCode(data);
}catch (error){
console.log('Error:',error);
}
}
function handleResponseCode(data){
console.log("response code: ", data.code);
console.log("response message: ", data.message);
if (data.code == 1){
alert ("Your account has been successfully created")
}
else if (data.code == 2 ){
alert (data.message );
}
}
You can try to catch the root cause of this error:
try {
$jsonResponse = json_encode($response);
} catch (Exception $e) {
// Handle JSON encoding error
die("JSON encoding error: " . $e->getMessage());
}
This will catch any exceptions thrown during the encoding process and allow you to handle them appropriately.
Edit:
function main(){
// ...
try {
$jsonResponse = json_encode($response);
} catch (Exception $e) {
// Handle JSON encoding error
die("JSON encoding error: " . $e->getMessage());
}
$conn = null;
return $jsonResponse;
}
you can put this catch error inside a function you wanna trace
Just remove the var_dump(...). Because that var_dump is already sending content back.
Uncaught SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data site:stackoverflow.com error is showing in firefox debug console.
I have a form in my website and on submit button this functions calls
$("#contact-form").on("submit",function(e)
{
var sendData = $(this).serialize();
e.preventDefault();
if ( checkSubmitInputs(this) )
{
$.ajax({
type: "POST",
url: "js/ajaxsubmit.php",
data: sendData,
success: function(data)
{
$("#loading-img").css("display","none");
// $(".response_msg").text(data);
// document.getElementById('contact-form').style.display = 'none'
// document.getElementById('success').style.display = 'block'
data = JSON.parse(data);
if(data.status){
document.getElementById('contact-form').style.display = 'none';
$("#error").text('');
$("#success").text(data.msg);
document.getElementById('success').style.display = 'block';
document.getElementById('scicon-c').style.display = 'block';
document.getElementById('error').style.display = 'none';
$("#contact-form").find("input[type=text], input[type=email], textarea").val("");
}
else {
document.getElementById('contact-form').style.display = '';
$("#success").text('');
$("#error").text(data.msg);
document.getElementById('error').style.display = 'block'
document.getElementById('success').style.display = 'none'
document.getElementById('scicon-c').style.display = 'none'
}
}
});
} else{
document.getElementsByClassName('error').style.display = 'block'
}
})
This line data = JSON.parse(data); shows above error as soon as i add include_once('mail.php'); in my ajaxsubmit.php file and without including it works perfectly.
Mail.php I am receiving mail too
<?php
error_reporting(-1);
ini_set('display_errors', 'On');
set_error_handler("var_dump");
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require_once("vendor/autoload.php");
$mail = new PHPMailer(true);
//Enable SMTP debugging.
$mail->SMTPDebug = 3;
//Set PHPMailer to use SMTP.
$mail->isSMTP();
//Set SMTP host name
$mail->Host = "email-smtp.us-west-1.amazonaws.com";
//Set this to true if SMTP host requires authentication to send email
$mail->SMTPAuth = true;
//Provide username and password
$mail->Username = "ID";
$mail->Password = "Pass";
//Set TCP port to connect to
$mail->Port = 587;
$mail->setFrom('demo#example', 'demo#example');
error_reporting(E_ALL); // Error/Exception engine, always use E_ALL
ini_set('ignore_repeated_errors', TRUE); // always use TRUE
ini_set('display_errors', true); // Error/Exception display, use FALSE only in production environment or real server. Use TRUE in development environment
ini_set('log_errors', TRUE); // Error/Exception file logging engine.
ini_set('error_log', 'zeeErrors.log'); // Logging file path
function sendEmailToUser($con, $emailMsg, $Subject)
{
global $mail;
$msg = "";
$subject = $Subject;
$tempArray = explode(',', $emailMsg);
$name = $tempArray[0];
$mobile = $tempArray[1];
$email = $tempArray[2];
$mail->Subject = "Test.";
$to = $email;
$htmlTemplate = file_get_contents('ration.html', true);
$mail->addAddress($to, $name); //Add a recipient
//$mail->addAddress('ellen#example.com'); //Name is optional
//$mail->addCC('cc#example.com');
//$mail->addBCC('varun7952#gmail.com');
$mail->isHTML(true);
$mail->Body = $msg;
//$mail->AltBody = "This is the plain text version of the email content";
try {
$mail->send();
echo "Message has been sent successfully";
return true;
} catch (Exception $e) {
echo "Mailer Error: " . $mail->ErrorInfo;
return false;
}
}
?>
AjaxSubmit.php
<?php
include_once('mail.php');
$response = array();
if((isset($_POST['name'])&& $_POST['name'] !='') && (isset($_POST['email'])&& $_POST['email'] !='') && (isset($_POST['phone'])&& $_POST['phone'] !=''))
{
//whether ip is from share internet
$ia = '';
if (!empty($_SERVER['HTTP_CLIENT_IP']))
{
$ia = $_SERVER['HTTP_CLIENT_IP'];
}
//whether ip is from proxy
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
{
$ia = $_SERVER['HTTP_X_FORWARDED_FOR'];
}
//whether ip is from remote address
else
{
$ia = $_SERVER['REMOTE_ADDR'];
}
/*Get user ip address details with geoplugin.net*/
$geopluginURL='http://www.geoplugin.net/php.gp?ip='.$ia;
$addrDetailsArr = unserialize(file_get_contents($geopluginURL));
/*Get City name by return array*/
$city = $addrDetailsArr['geoplugin_city'];
/*Get Country name by return array*/
$country = $addrDetailsArr['geoplugin_countryName'];
$region = $addrDetailsArr['geoplugin_regionName'];
if(!$city){
$city='Not Define';
}
if(!$country){
$country='Not Define';
}
if(!$region){
$region='Not Define';
}
//file_put_contents('zee1.log', print_r($addrDetailsArr, TRUE));
$yourName = $conn->real_escape_string($_POST['name']);
$yourEmail = $conn->real_escape_string($_POST['email']);
$yourPhone = $conn->real_escape_string($_POST['phone']);
$city = $conn->real_escape_string($city);
$country = $conn->real_escape_string($country);
$region = $conn->real_escape_string($region);
$checkSql = "SELECT name, email, contact from reg where email='".$yourEmail."' OR contact='".$yourPhone."'";
$resultCheck = $conn->query($checkSql);
if($resultCheck->num_rows > 0) {
$response['status'] = false;
$response['msg'] = "You have registered already with ".$yourEmail." OR ".$yourPhone."";;
}else {
$userLocation = $city.' '.$region.' '.$country;
$sql="INSERT INTO reg (name, email, contact,IP_Address,City) VALUES ('".$yourName."','".$yourEmail."', '".$yourPhone."','".$ia."','".$userLocation."')";
if(!$result = $conn->query($sql)){
$response['status'] = false;
$response['msg'] = 'There was an error running the query [' . $conn->error . ']';
}
else
{
$response['status'] = true;
$response['msg'] = "Thank you $yourName. Welcome in SAAS Application. We will connect with you soon. :)";
$msg = $yourName.','.$yourPhone.','.$yourEmail.','.$userLocation;
if(sendEmailToUser($conn,$msg,'Reg')){
//Email Sent
}
}
}
}
else
{
$response['status'] = false;
$response['msg'] = 'Please fill Name and Email';
}
echo json_encode($response);
?>
As i said everything is working if i don't add require in ajaxsubmit file. I am not good in php or JS so after reading so many answers i still can't figure out why i am not able to parse json at my form.
This is JSON Returned by AJAXsubmit
{
"status": true,
"msg": "Thank you Demo. Welcome in SAAS Application. We will connect with you soon. :)"
}
Your problem is that mail.php has this code in it:
try {
$mail->send();
echo "Message has been sent successfully";
return true;
} catch (Exception $e) {
echo "Mailer Error: " . $mail->ErrorInfo;
return false;
}
which, regardless of the result, causes text to be echo'ed. As a result, your json response will look something like:
Message has been sent successfully
{
... normal json response
}
which will not parse successfully.
I'm having problems figuring out what is wrong with my json. I used php's json_encode.So, on every page I have the some form which need be sent on each page to different email address. However, if I comment jQuery file, then the form is submitted correctly, all data inserted into database correctly, and in place of jQuery AJAX response I get valid JSON, like
{"response":"success","content":{"3":"Thanks John Doe! Your message is successfully sent to owner of property Hotel Milano!"}}
If I want to read and process this data with jQuery instead of get valid response I get just empty [] I was try a lot of options and so if I add JSON_FORCE_OBJECT instead of get empty [] I get empty {}. However if I write json data which need to encode after closing tag for if (is_array($emails) && count($emails) > 0) { just then json data it's encoded correctly and when a form is submitted I get valid response, but in this case form isn't sent and data isn't inserted into db. Bellow is my PHP code:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// define variables and set to empty values
$fname = $tel = $email_address_id = "";
$error = false;
$response = [];
//Load the config file
$dbHost = "localhost";
$dbUser = "secret";
$dbPassword = "secret";
$dbName = "booking";
$dbCharset = "utf8";
try {
$dsn = "mysql:host=" . $dbHost . ";dbName=" . $dbName . ";charset=" . $dbCharset;
$pdo = new PDO($dsn, $dbUser, $dbPassword);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
$response['response'] = 'error';
$response['errors'][] = $e->getMessage();
echo json_encode($response);
die();
}
use PHPMailer\PHPMailer\PHPMailer;
require 'PHPMailer/PHPMailer.php';
require 'PHPMailer/SMTP.php';
require 'PHPMailer/Exception.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['submit'])) {
//print_r($_POST);
$fname = $_POST['fname'];
$tel = $_POST['tel'];
if (empty($fname)) {
$response['response'] = 'error';
$error = true;
$response['errors'][] = 'Name can not be empty!';
} else {
if (!preg_match("/^[a-zšđčćžA-ZŠĐČĆŽ\s]*$/", $fname)) {
$response['response'] = 'error';
$error = true;
$response['errors'][] = 'Name can contain just letters and white space!';
}
}
if (empty($tel)) {
$response['response'] = 'error';
$error = true;
$response['errors'][] = "Phone can not be empty!";
} else {
if (!preg_match('/^[\+]?[0-9]{9,15}$/', $tel)) {
$response['response'] = 'error';
$error = true;
$response['errors'][] = "Phone can contain from 9 to 15 numbers!";
}
}
if (!$error) {
// Instantiate a NEW email
$mail = new PHPMailer(true);
$mail->CharSet = "UTF-8";
$mail->isSMTP();
$mail->Host = 'secret.com';
$mail->SMTPAuth = true;
//$mail->SMTPDebug = 2;
$mail->Username = 'booking#secret.com';
$mail->Password = 'secret';
$mail->Port = 465; // 587
$mail->SMTPSecure = 'ssl'; // tls
$mail->WordWrap = 50;
$mail->isHTML(true);
$mail->setFrom('booking#secret.com');
$mail->clearAddresses();
$mail->Subject = "New message from secret.com";
$query = "SELECT owners_email.email_address_id, email_address, owner_name, owner_property, owner_sex, owner_type FROM booking.owners_email INNER JOIN booking.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();
//var_dump($dbstmt);
$emails = $dbstmt->fetchAll(PDO::FETCH_ASSOC);
if (is_array($emails) && count($emails) > 0) {
foreach ($emails as $email) {
//var_dump($email['email_address']);
$mail->addAddress($email['email_address']);
$body = "<p>Dear {$email['owner_name']}, <br>" . "You just received a message from <a href='https://www.secret-booking.com'>secret-booking.com</a><br>The details of your message are below:</p><p><strong>From: </strong>" . ucwords($fname) . "<br><strong>Phone: </strong>" . $tel . "</p>";
$mail->Body = $body;
if ($mail->send()) {
$mail = "INSERT INTO booking.contact_owner (fname, tel, email_address_id) VALUES (:fname, :tel, :email_address_id)";
$stmt = $pdo->prepare($mail);
$stmt->execute(['fname' => $fname, 'tel' => $tel, 'email_address_id' => $email['email_address_id']]);
$response['response'] = "success";
$response['content'][$email['email_address_id']] = "Thanks " . ucwords($fname) . "! Your message is successfully sent to owner of property {$email['owner_property']}!";
}//end if mail send
else {
$response['response'] = "error";
$response['content'][$email['email_address_id']] = "Something went wrong! Try again..." . $mail->ErrorInfo;
}
}//end foreach for email addresses
} //end if for array of emails
/* If use this else for response I allways get this response. Even, if I write JSON for success hier I get it but data isn't sent and isn't inserted into db
else {
$response['response'] = 'error';
$response['error'][] = '$emails is either not an array or is empty'; // jQuery just read this
}//end if else for array of emails
*/
}//end if validation
}//end submit
echo json_encode($response);
}//end REQUEST METHOD = POST
And this is jQuery for submitHanfdler
submitHandler: function (form) {
//Your code for AJAX starts
var formData = jQuery("#contactOwner").serialize();
console.log(formData); //this work
jQuery.ajax({
url: '/classes/Form_process.class.php',
type: 'post',
data: formData,
dataType: 'json',
cache: false,
success: function (response) {
jQuery("#response").text(response['content']);
// debbuger;
console.log(response);
//console.log(response.hasOwnProperty('content'));
},
error: function (response) {
// alert("error");
jQuery("#responseOwner").text("An error occurred");
console.dir("Response: " + response);
}
}); //Code for AJAX Ends
// Clear all data after submit
var resetForm = document.getElementById('contactOwner').reset();
return false;
} //submitHandler
Thanks in advance for any kind of your help, any help will be highly appreciated!
I suspect the issue is the dataType: 'json' attribute. This is because the serialize function does not provide json data. See if this works:
jQuery.ajax({
url: '/classes/Form_process.class.php',
method: 'POST',
data: jQuery("#contactOwner").serialize()
}).done(function (response) {
console.log(response);
}).fail(function (error) {
console.log(error);
});
Alternatively, if you want to use dataType: 'json', you will need to send in json data:
jQuery.ajax({
url: '/classes/Form_process.class.php',
method: 'POST',
data: {
firstName: jQuery("#contactOwner .first-name").val(),
lastName: jQuery("#contactOwner .last-name").val(),
...
}
dataType: 'json',
cache: false,
}).done(function (response) {
console.log(response);
}).fail(function (error) {
console.log(error);
});
If you add you data using an object as shown above this should work with dataType: 'json'.
i want to send a few php variables by a trigger from javascript. The variables, databases and the script is working but i cant figure our the PHP part.
This is what I think the PHP should be like but its obviously faulit. i just want to send the few variables.
if{
$mail = new PHPMailer;
$mail->isSMTP();
//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$mail->CharSet = 'UTF-8';
$mail->SMTPDebug = 0;
$mail->Debugoutput = 'html';
$mail->Host = "host";
$mail->SMTPAuth = false;
$mail->Port = 25;
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
$mail->setFrom('noreply', 'hint');
$mail->addAddress('email.test.com');
$mail->Subject = 'hint';
$msg='Allikas: '.$_POST['source']
$mail->msgHTML('<strong>Hint.</strong>;
if (!$mail->send()) {
echo 'ERROR';
//return false;
//echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "SUCCESS";
}
}else{echo "SUCCESS";}
}
This is my javascript trigger
else if (checked === true) {
console.log("asddd")
"send the stuff (part i need help with")
}
}
You need to do an ajax request
var values = {"source":"the source...", "location":"the location..."}; // add your others variable here...
$.ajax({
url: "yourphpfile.php",
type: "post",
data: values ,
success: function (response) {
// it will return the result (SUCCESS or ERROR)
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
function registration_ajax(){
$this->load->library('form_validation');
$this->form_validation->set_rules('email','email','required|is_unique[register.email]');
if($this->form_validation->run() == FALSE){
$data = '{"status":"false","message":"Email already exists"}';
}
else
{
$email=$this->input->post('email');
$data= array(
'email'=>$email
);
$last_id = $this->model->registeration($data);
if ($last_id>0) {
$this->send_email($email);
$data = '{"status":"true","message":"Email Created successfully"}';
}
}
echo $data;
}
public function send_email($to='',$username="",$from='khadija#precisetech.com.pk')
///function send_mail()
{
$this->load->library('encrypt');
$toEmail = $this->encrypt->encode($to);
$toEmail = str_replace('/','forwardSlash',$toEmail);
$toEmail = str_replace('=','equalSign',$toEmail);
$toEmail = str_replace('+', 'plusSign', $toEmail);
$this->load->library('email');
$config['protocol'] = 'smtp';
$config['smtp_host'] = 'sadasds';//pust mail.com.pk
$config['smtp_port'] = '25334';
$config['smtp_user'] = 'example';
$config['smtp_pass'] = 'example1';
$config['charset'] = 'utf-8';
$config['mailtype'] = 'html';
$config['validation'] = FALSE; // bool whether to validate email or not
$this->email->initialize($config);
$message = '<h1 align="center">Hellow</h1>';
$message = '<html><body style="color:#000; font-weight:normal; font-size:13/14px;"><p style="color:#000;">Hi!</p>';
$message .= '<table rules="all">';
$message .= "<p>Congratulations! You have almost completed your registration on Electronic Mall.<br><br>Click on link here to confirm your email address<br> 10.10.10.44<br><br>Thank you for joining us and becoming part of world's largest local classified sites.In our website, you can enjoy simple ad posting, easy searching and endless local listing for products.We appreciate you for choosing us in online market place.<br> Wishing you alot of success on your classified journey.Get started now!<br><br></p>";
$message .= "<p>Regards,<br>The Electronic Mall Team</p>";
$message .= "</table>";
$message .= "</body></html>";
$this->email->from($from);
$this->email->to($to);
$this->email->subject('Confirmation Email');
$this->email->message($message);
if(!$this->email->send()){
echo $this->email->print_debugger();
die();
}else{
}
}
////ajx code
//////////////////
<script>
$(document).ready(function(){
$('#registration_form').on('submit',function(e){
var email = $('#email').val();
$.ajax({
url: "<?=base_url('controller/registration_ajax')?>",
// url: "<?=base_url('controller/register')?>",
type: "POST",
datatype: "JSON",
data: {email: email},
success: function(res){
var data = $.parseJSON(res);
var status = data.status;
var message = data.message;
if(status == 'true'){
/// $('#myModal').modal('hide');
$('#message_sent').html(message);
}
else{
$('#message').html(message);
}
}
});
e.preventDefault();
});
});
</script>
I want that after email is sent successfully then this message should be displayed
$data = '{"status":"true","message":"Email Created successfully"}';
When I commented the mail sending function then it display the successful message, I want that the message should be display after sending email.
have you tried returning a value from your send_email function?
if(!$this->email->send()){
return 'success';
}else{
$this->session->set_flashdata('message', 'To complete registration, click the link in email we just send you at khadija#precisetech.com.pk');
redirect('controller/login_register','refresh');
die();
}
then in your :
if ($last_id>0) {
$res = $this->send_email($email);
if($res === 'success'){
$data = '{"status":"true","message":"Email Created successfully"}';
}
}