I'm trying to get my app run into my if statement but it went down to else statement which is not what I want. callback data is "Pass" which is correct for my if condition but it still ran down to else. Please take a look at my code.
js file
$http.post(path, postdata
).success(function (data, status, headers, config) {
//if (data) {
// $scope.PostDataResponse = data;
if (data === "Pass"){
setCookie("Username", $scope.formdata.Username);
setCookie("cafe_id", $scope.formdata.cafe_id);
console.log(getCookie("Username"));
alert("ลงทำเบียนสำเร็จ !");
$location.url('/viewSaveCafeDetail');
//console.log(data);
//alert("สมัครสมาชิกสำเร็จ");
//$scope.insertcafe();
//$scope.sendEmail();
// $scope.reset();
// $scope.getData();
}else{ <--- ran down to else statement
alert(data); <--- callback value is "Pass" which is match with my if condition.
}
PHP file
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods : GET,POST,PUT,DELETE,OPTIONS");
header('Access-Control-Allow-Headers: Origin, Content-Type, Accept, Authorization, X-Requested-With, X-YOUR-CUSTOM-HEADER');
header("Content-Type : application/json");
header("Accept : application/json");
$serverName = "localhost";
$userName = "root";
$userPassword = "";
$dbName = "middlework";
$conn = new mysqli($serverName,$userName,$userPassword,$dbName);
mysqli_set_charset($conn,"utf8");
session_unset();
session_start();
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$strSQL = "INSERT INTO users ";
$strSQL .="(Username,Password,Firstname,Lastname,Email,Tel,AccountStat,VerifyCode,Verifystat) ";
$strSQL .="VALUES ";
$strSQL .="('".$request->Username."','".$request->Password."','".$request->Firstname."' ";
$strSQL .=",'".$request->Lastname."','".$request->Email."','".$request->Tel."','User','".session_id()."','None' ) ";
mysqli_query($conn,$strSQL) or die(mysqli_error($conn));
$insertcafe = "INSERT INTO cafe (cafe_id,Username,CafeName) VALUES ('1' , '".$request->Username."', '".$request->CafeName."')";
require_once('PHPMailer/PHPMailerAutoload.php');
$mail = new PHPMailer();
$mail->IsHTML(true);
$mail->CharSet = "utf-8";
$mail->IsSMTP();
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->SMTPSecure = "ssl"; // sets the prefix to the servier
$mail->Host = "smtp.gmail.com"; // sets GMAIL as the SMTP server
$mail->Port = 465; // set the SMTP port for the GMAIL server
$mail->Username = "kitsakorn.p55#rsu.ac.th"; // GMAIL username
$mail->Password = "1100501068349"; // GMAIL password
$mail->From = "kitsakorn.p55#rsu.ac.th"; // "name#yourdomain.com";
$mail->FromName = "ThaiCoffeeShopOnline"; // set from Name
$mail->Subject = "ยืนยันการสมัครสมาชิก ThaiCoffeeShopOnline";
$mail->Body = "ขอขอบคุณที่สมัครเป็นสมาชิกกับเรา กรุณาคลิก Url ด้านล่างเพื่อทำการ Activate บัญชีของคุณ</br>
http://localhost/activate.php?sid=".session_id()."&uid=".$request->Username."</br></br> ThaiCoffeeShop.com";
$mail->AddAddress($request->Email); // to Address
if($conn->query($insertcafe))
{
if (!$mail->send()) {
//echo "ไม่สามารถส่ง email: " . $mail->ErrorInfo;
echo "EmailFail";
} else {
echo "Pass ";
//json_decode();
}
//echo "Save Cafe Done.[".$insertcafe."]";
}
else
{
echo "";
//echo mysqli_error($conn);
//echo "ไม่สามาถบันทึกข้อมูล[".$insertcafe."]";
}
$conn->close();
?>
Your PHP file has echo "Pass "; which writes "Pass" followed by a space which you are comparing against the string "Pass" without a space.
In addition, you might also have a blank line at the end of your PHP file which will also be included in the output. This can be worked around by removing the ?> tag from the end.
Related
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've created an contact us form using PHP Mailer, however the problem is when I received the email the name before you open it is me and I can't figured out how to fix it. Also I appreciate it if someone explain to me what is the different between Username and the add Address. Thank you in advance.
Here is the me I'm referring to
<?php
use PHPMailer;
if(isset($_POST['name']) && isset($_POST['email'])){
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$body = $_POST['body'];
require_once "PHPMailer/PHPMailer.php";
require_once "PHPMailer/SMTP.php";
require_once "PHPMailer/Exception.php";
$mail = new PHPMailer();
//smtp settings
$mail->isSMTP();
$mail->Host = "smtp.gmail.com";
$mail->SMTPAuth = true;
$mail->Username = "";
$mail->Password = '';
$mail->Port = 465;
$mail->SMTPSecure = "ssl";
$mail->SetFrom("$email ", "$name");
//email settings
$mail->isHTML(true);
$mail->setFrom($_POST['email'], $_POST['email']);
$mail->addAddress("");
$mail->Subject = ("$email ($subject)");
$mail->Body = $body;
if($mail->send()){
$status = "success";
$response = "Email is sent!";
}
else
{
$status = "failed";
$response = "Something is wrong: <br>" . $mail->ErrorInfo;
}
exit(json_encode(array("status" => $status, "response" => $response)));
}
You are sending mail from the same email address to the same email address.
So, many email clients identify yourself as me.
You will have to send using another email address, and you will be idenfied with your email/name.
As Jesse said: You can also send mail to another email, and it will usually not show me.
Make a new Email address / use another Email address in script
i am having some trouble with phpmailer and ajax. Im quite new to ajax and dont fully understand it yet so this might have a quite obvious fix but here we go.
So when i just put my php mailer script in a page and visit it with set values i can send the mail. but whenever i try to send my form data to the script something doesnt work.
This is my jquery
$(document).ready(function(){
$(".contact-form").on("submit",function(e){
e.preventDefault();
function validateEmail($email) {
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
return emailReg.test( $email );
}
var valid = true;
if(!$("#name").val()) {
$("#userEmail").css('border','2px solid #FFFFDF');
valid = false;
}
if( !validateEmail($(' #email').val())) {
valid = false
}
if(!$("#subject").val()) {
$("#subject").css('border','2px solid #FFFFDF');
valid = false;
}
if(!$("#message").val()) {
$("#message").css('border','2px solid #FFFFDF');
valid = false;
}
//send data to php file
var isValid;
isValid = valid
if(isValid) {
var name = $("#name").val();
var email = $("#email").val();
var subject = $("#subject").val();
var message = $("#message").val();
jQuery.ajax({
url: "includes/sendmail.inc.php",
type : "POST",
data:{name:name,email:email,subject:subject,message:message},
success:function(data){
$(".err_msg").text("Send!");
$(".err_msg").css('background-color', 'green')
$(".err_msg").show()
},
error:function (){}
});
} else {
$(".err_msg").text("Oops! check your input.");
$(".err_msg").css('background-color', 'red')
$(".err_msg").show()
}
});
});
This is my php
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
// Load Composer's autoloader
require 'vendor/autoload.php';
$name = $_POST['name'];
$mail = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
// Instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);
try {
//Server settings
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
$mail->SMTPDebug = SMTP::DEBUG_SERVER; // Enable verbose debug output
$mail->isSMTP(); // Send using SMTP
$mail->Host = 'mail.example#example.com'; // Set the SMTP server to send through
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'example#example.com'; // SMTP username
$mail->Password = 'example123'; // SMTP password
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
$mail->Port = 587 ; // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above
//Recipients
$mail->setFrom( $email , $name);
$mail->addAddress('example#example.com', 'John Doe'); // Add a recipient
$mail->addReplyTo($email , $name);
// Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $subject;
$mail->Body = $message;
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
so this is what i have so far i hope you guys can figure out what i did wrong because i have been stuck on this for about two days now.
greetz Floris
yes i figured it out guys thanks ! so what went wrong is that for some reason it wouldnt send because the FROM email adress was a gmail account and i am using my own domain smtp that was causing it appearantly
I'm new to the world of programming. My code is shown below.
First question: how do I format the body text? For example, not having all requests in a row but one below the other, etc.
Second question: How can I insert the code to be able to load a file in my contact form, the html code is already present and it works but on the javascript side I can't understand where to insert it.
Last question: I have a news letters acceptance field how do I insert a field that tells me if the user has accepted the news letter?
Thanks a lot to everyone!
<?php
$name = $_POST["name"];
$email = $_POST["email"];
$telefono = $_POST["telefono"];
$indirizzo = $_POST["indirizzo"];
$civico = $_POST["civico"];
$citta = $_POST["citta"];
$provincia = $_POST["provincia"];
$cap = $_POST["cap"];
$newsletters = $_POST["newsletters"];
$body = "Name:" .$name . "<br>Email:" . $email .
"TelefonoLocale:" . $telefono . "Indirizzo:" . $indirizzo . "Civico:" . $civico . "Città:" . $citta. "Provincia:" . $provincia . "Cap:" . $cap . "newsletters:" . $newsletters;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'PHPMailer/src/Exception.php';
require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';
// Instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);
try {
//Server settings
$mail->isSMTP(); // Send using SMTP
$mail->Host = 'xxxxxxx'; // Set the SMTP server to send through
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'xxxxxxxx'; // SMTP username
$mail->Password = 'xxxxxxxxxx'; // SMTP password
$mail->SMTPSecure = 'ssl'; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` also accepted
$mail->Port = xxxxxx; // TCP port to connect to
//Recipients
$mail->setFrom('xxxxxx', $name);
$mail->addAddress('xxxxxxxx'); // Add a recipient
// Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body = $body;
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
$mail->send();
echo '<script>
alert("Messaggio inviato correttamente");
window.history.go(-1);
</script>';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
All I want to do is print 'win!' if they log in with their details in the Database (working correctly) and 'loss' if for some reason their info was not found in the DB.
So my issue is that for some reason my line of code 'echo $email;' doesn't work. It seems be set to NULL.
At the moment it only ever prints 'loss' regardless what i enter, but, if I add a row in the database that has a blank email and password (email = "", password="") then the php script returns 'win!'.
PHP CODE:
<?php
// echo "php test";
//server info
$servername = "localhost";
$username = "root";
$dbpassword = "root";
$dbname = "personal_data";
//Establish server connection
$conn = new mysqli($servername, $username, $dbpassword, $dbname);
//Check connection for failure
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
//Read in email & password
echo "reading in email & password...";
$email = mysqli_real_escape_string($conn, $_POST['email1']);
$password = mysqli_real_escape_string($conn, $_POST['password1']);
echo $email; //this prints blank
echo $password; //this also prints blank
$sql = "SELECT Name FROM personal_data WHERE Email='$email' AND Password='$password' LIMIT 1";
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result) > 0){
echo "win!!";
} else {
echo "loss";
}
mysqli_close($conn);
?>
JS CODE:
$(document).ready(function(){
// alert("js working");
$('#login_button').click(function(){
var email = $('#email').val(); //prints the correct value
var password = $('#password').val(); //prints the correct value
var dataString = 'email1=' + email
+ '&password1=' + password;
$.ajax({
type: "POST",
url: "http://localhost:8888/php/login.php",
data: dataString, //posts to PHP script
success: success()
});
});//eo login_button
function success(){
alert("success");
}
});//eof
Apart from the fact that that is completely, insanely useless and with no security whatsoever, you can just exchange $.ajax() for $.post() and do like this:
var loginEmail = $('#email').val();
var loginPassword = $('#password').val();
$.post('login.php',{email:loginEmail,password1:loginPassword},function(data) {
console.log(data);
})