Click here to Skip to main content
14,577,261 members
Rate this:
Please Sign up or sign in to vote.
See more:
I am making an email app. In which first fill the from and to fields and then when they click send that link via Ajax to a php script which then sends the e-mail and returns true and the app interprets this as a successful send. Before sending the mail it validates the form, whether all the fields are given and if it's correct.

Everything is working except the subject and message field. Event if it's showing the error message, still, it's sending the mail.

This is my code:

indexx.html

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
	<link rel="stylesheet" href="app.min.css">
	
	<style>
		
		.bgtrans{
			background: transparent;
			border: 0;
			padding: 0;
		}
		
		.success{
			color: #155724;
			padding: 8px;
			background-color: #d4edda;
            border-color: #c3e6cb;
		}
		
		.danger{
			padding: 8px;
			color: #721c24;
			background-color: #f8d7da;
			border-color: #f5c6cb;
		}
		
		@-webkit-keyframes pulse {
				0% {
					background-color: #CCC;
				}
				25% {
					background-color: #EEE;
				}
				50% {
					background-color: #CCC;
				}
				75% {
					background-color: #EEE;
				}
				100% {
					background-color: #CCC;
				}
			}
		
	</style>
	
</head>

<body>
	
	<div class="app-page" data-page="home">
		<div class="app-topbar blue">
			<div class="app-title">App Email</div>
		</div>
		
		<div class="app-content">
			<p class="app-section">Click below to send an email</p>
			
			<div class="app-section" id="contactList">
				
				
			</div>
		
		<div class="app-section">
			<div class="app-button green" id="newUser">Send to new user</div>
		</div>
			
		</div>
		
		
	</div>
	
	
	<div class="app-page" data-page="sendEmail">
		<div class="app-topbar blue">
			<div class="app-button right" data-back data-autotitle>Done</div>
			<div class="app-title">New User</div>
		</div>
		
		<div class="app-content">
			
			<div class="app-section" id="message">
			
			</div>
			
			<form name="myform" method="get"><!-- onSubmit="return validateForm();"-->
			<div class="app-section">
				<input type="text" name="from" id="from" class="app-input" placeholder="From">
			</div>
			
			<div class="app-section">
				<input type="text" name="to" id="to" class="app-input" placeholder="To">
			</div>
			
			<div class="app-section">
				<input type="text" name="subject" id="subject" class="app-input" placeholder="Subject">
				<textarea name="content" id="content" class="app-input" placeholder="Message"></textarea>
				<div class="app-button green app-submit" id="send">Send</div>
			</div>
			</form>
			
		</div>
	</div>
	
	
	<script src="zepto.js"></script>
	<script src="app.min.js"></script>
	
	
	<script type="text/javascript">
	    App.controller('home', function (page) {
    
          if (typeof localStorage !== 'undefined') {
              
              $(page).find("#newUser")
                .clickable()
                .click(function () {
                  
                  if (localStorage.getItem("to") !== null) {
                  
                      localStorage.removeItem("to");
                      
                      
                  }
                  
                  App.load("sendEmail");
                  
              })
              
              if (localStorage.getItem("recipient-list") !== null) {
                  
                  var recipientList = JSON.parse(localStorage.getItem("recipient-list"));
                  
                  $.each(recipientList, function( index, value ) {
                    
                      $(page).find("#contactList").append('<div class="app-button redirect">' + value + '</div>');
                
                  });
                  
                  $(page).find("#contactList").show();
                  
                  $(page).find(".redirect")
                      .clickable()
                      .on("click", function() {
                      
                      localStorage.setItem("to", $(this).html());
                      
                      App.load('sendEmail');
                      
                      
                      
                  });
                  
                  
              } else {
                  
                  $(page).find("#contactList").hide();
                  
              }
              
              
          }
          
      });
        
        App.controller('sendEmail', function (page) {
            
            $(page).find("#message").hide();
            
            if (typeof localStorage !== 'undefined') {
                
                if (localStorage.getItem("from") !== null) {
                    
                    
                    $(page).find("#from").val(localStorage.getItem("from"));
                    
                }
                
                if (localStorage.getItem("to") !== null) {
                    
                    $(page).find("#to").val(localStorage.getItem("to"));
                    
                }
                
            }
            
            
            
          $(page).find('#send')
					.clickable()
					.on('click', function (event) {
			
		event.preventDefault();
              
                 $.ajax({
  type: 'GET',
  url: 'http://apsecoglobalwarming-com.stackstaging.com/EmailClientApp/sendEmail.php?callback=response',
  // data to be added to query string:
  data: { to: $("#to").val(), from: $("#from").val(), subject: $("#subject").val(), content: $("#content").val()},
  // type of data we are expecting in return:
  dataType: 'jsonp',
  timeout: 300,
  context: $('body'),
  success: function(data){
    
      if (data.success == true) {
		      $(page).find("#message").removeClass("danger");
			  $(page).find("#message").addClass("success").text("Your email was sent successfully!").show();
		
          
		  
          
      } else {
          
          $(page).find("#message").addClass("danger").text("Your email could not be sent - please try again later.");
          
      }
      
      
  },
  error: function(xhr, type){
   
        $(page).find("#message").addClass("danger").text("Your email could not be sent - please try again later.");  
      
  }
})
    
          validateForm();
			  
			
			  
              
          });
			
			
			
		function validateForm(){
			
			
              if (typeof localStorage !== 'undefined') {
				  
				 
				
				  var re = /^\w+([-+.'][^\s]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;

				  var emailFormat = re.test($("#to").val());
				  var emailFormatB = re.test($("#from").val());
				  
				  
				  if($('#from').val() == 0 || $('#to').val() == 0 /*|| $('#subject').val() == 0 || $('#content').val() == 0*/){
						            $(page).find("#message").addClass("danger").text("All the fields are required").show();
					                return false;
						  }
						  else if(!emailFormatB) {
									$(page).find("#message").addClass("danger").text("Invalid Email").show();
                                    return false;

						  }
				          else if(!emailFormat){
							  		$(page).find("#message").addClass("danger").text("Invalid Email").show();
                                    return false;
						  }
				  else if($('#subject').val() == 0){
					  $(page).find("#message").addClass("danger").text("Subject field is required").show();
					                return false;
				  }
				  
				   else if($('#content').val() == 0){
					  $(page).find("#message").addClass("danger").text("content field is required").show();
					                return false;
				  }
				         
						  
				
				  else{
					  
					  $(page).find("#message").text("").hide();
					  localStorage.setItem("from",$("#from").val());	 
					  
						 var recipientList = new Array();

						  if (localStorage.getItem("recipient-list") !== null) {

							  recipientList = JSON.parse(localStorage.getItem("recipient-list"));

						  }

						  if ($.inArray($("#to").val(), recipientList) == -1) {

							  if($("#to").val() == 0){
								  
								  //var recipientList = new Array();
									var removeItem = $("#to").val();

									var i = $.inArray(removeItem,recipientList)

									if (i){
										recipientList.splice(i, 1);
									}

								 }
							 else{
								 	recipientList.push($("#to").val());

								  recipientList.sort();

								  localStorage.setItem("recipient-list", JSON.stringify(recipientList));

								  console.log(recipientList);
							 }

						  }
					  
				  }
				  
				  
				
			
                  
              } else {
                  
                  // alert user that we couldn't save data
                  
              }
			 }
		
			
			
      });
        
       

      try {
        App.restore();
      } catch (err) {
        App.load('home');
      }
	
	
	</script>
</body>
</html>




sendEmail.php

<?php
$to = $_GET["to"];
$subject = $_GET["subject"];
$content = $_GET["content"];
$headers = "From: " .$_GET["from"]. "\r\n" .
"Reply-To: ".$_GET["from"]. "\r\n".
    'X-Mailer: PHP/' . phpversion();


$result = array();
$result['success'] = mail($to, $subject, $content, $headers);
$result2 = json_encode($result);

if(array_key_exists('callback', $_GET)){

    header('Content-Type: text/javascript; charset=utf8');
    header('Access-Control-Allow-Origin: http://www.example.com/');
    header('Access-Control-Max-Age: 3628800');
    header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');

    $callback = $_GET['callback'];
    echo $callback.'('.$result2.');';

}else{
    // normal JSON string
    header('Content-Type: application/json; charset=utf8');

   // echo $result2;
}



?>


What I have tried:

Even I tried to validate it in php in sendEmail.php. But it's not showing the error messages. Like this:

function sanitize_my_email($field) {
$field = filter_var($field, FILTER_SANITIZE_EMAIL);
if (filter_var($field, FILTER_VALIDATE_EMAIL)) {
return true;
} else {
return false;
}
}
$to = $_GET["to"];
$subject = $_GET["subject"];
$content = $_GET["content"];
$headers = "From: " .$_GET["from"]. "\r\n" .
"Reply-To: ".$_GET["from"]. "\r\n".
'X-Mailer: PHP/' . phpversion();
//check if the email address is invalid $secure_check
$secure_check = sanitize_my_email($to);
if ($secure_check == false) {
echo "Invalid input";
}
else if($subject == ""){
echo "Enter the subject";
}
else if($content == ""){
echo "Enter the content";
}
else {

$result = array();
$result['success'] = mail($to, $subject, $content, $headers);
$result2 = json_encode($result);


if(array_key_exists('callback', $_GET)){

header('Content-Type: text/javascript; charset=utf8');
header('Access-Control-Allow-Origin: http://www.example.com/');
header('Access-Control-Max-Age: 3628800');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');

$callback = $_GET['callback'];
$callback.'('.$result2.');';

}else{
// normal JSON string
header('Content-Type: application/json; charset=utf8');

echo $result2;
}


}

But nothing is working. Any help would be appreciated.

Thanks
Posted
Updated 30-Jun-20 1:05am
Rate this:
Please Sign up or sign in to vote.

Solution 1

if($('#from').val() == 0 || $('#to').val() == 0 /*|| $('#subject').val() == 0 || $('#content').val() == 0*/){

The checks on subject and content have been commented out.
   
v2
Rate this:
Please Sign up or sign in to vote.

Solution 2

Thanks for the reply.
Yes, I have commented because it was not working and instead written it down. Like this:

else if($('#subject').val() == 0){
$(page).find("#message").addClass("danger").text("Subject field is required").show();
return false;
}

else if($('#content').val() == 0){
$(page).find("#message").addClass("danger").text("content field is required").show();
return false;
}

But still it's not working. It's showing the error messages, but it's still sending the mail. The event.preventDefault() is not working properly.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month



CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100