I want to make two verifications to Emails.
First to verify if the email is accepted ( that it is not an incorrect mail like gimil.com homail.com ... etc) and second verification to know if email existed.
I try to do with this jQuery code
$('#signup').validate({
errorElement: 'span',
rules:{
Email: {
required: true,
email: true,
remote: {
url: '/verifiyEmail',
type: 'POST', //Or whatever
data: function(){
return $("#email").val(); // The value of the email field
},
dataType: "JSON",
dataFilter: function(responseData){
alert(responseData.message); // Or whatever
return responseData.isValid; // validation result
}
}
}
}
});
and the PHP code
if(isset($_POST['email'])){
$email = $_POST['email'];
$response = null;
$isInBlackList = Member::Accepted($email);
if($isBlackList){
// User is in the blacklist
$response = array("isValid"=>false, "message"=>"This email is blacklisted!"); // Initialize $response
}
else{
$alreadyExists = ! Member::($email); // You have to implement this.
if(!$alreadyExists){
// Email already exists
$response = array("isValid"=>false, "message"=>"This email is already in user"); // Initialize $response
}
else{
// We found a valid email
$response = array("isValid"=>true);
}
}
header('Content-Type: application/json');
echo json_encode($response);
}else{
$response = array("isValid"=>'error');
header('Content-Type: application/json');
echo json_encode($response);
}
And always the response is error, which means the Email is not being sent through the PHP code
Is there any solution?
Related
I am able to consume the php endpoint from postman. I try to do the same from angular post, I get this error - Http failure during parsing for. Even though everything looks perfect to me, the problem is surprising. Here is my snippet
php file
<?php
header('Access-Control-Allow-Origin: *');
// check for post
if ($_SERVER['REQUEST_METHOD']=='POST') {
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$conn = new db_CONNECT();
$cone=$conn->con;
//escpae the strings to be inserted to DB
$escapedname = mysqli_real_escape_string($cone, $name);
$escapedemail = mysqli_real_escape_string($cone, $email);
$escapedsubject= mysqli_real_escape_string($cone, $subject);
$escapedmessage = mysqli_real_escape_string($cone, $message);
// mysql inserting a new row
$sql = "INSERT INTO contacts(name, email, subject, message) VALUES ('$escapedname', '$escapedemail', '$escapedsubject', '$escapedmessage')";
// $result= $cone -> query($sql);
// $affected = $cone -> affected_rows;
if (mysqli_query($cone,$sql)) {
echo "Information saved successfully.";
} else {
echo "Not successful";
}
} else {
echo "Some field missing.";
}
?>
here is the angular snippet
saveContactDetails = function () {
this.proceed = true;
this.success = false;
const myheader = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
data.append('name', this.contactDeJson.name);
data.append('email', this.contactDeJson.email);
data.append('subject', this.contactDeJson.subject);
data.append('message', this.contactDeJson.message);
this.http
.post('http://localhost:80/'+'api/create_contact.php', data.toString(), {headers: myheader})
Please why am I getting this error
{"headers":{"normalizedNames":{},"lazyUpdate":null},"status":200,"statusText":"OK","url":"http://localhost/api/create_contact.php","ok":false,"name":"HttpErrorResponse","message":"Http failure during parsing for http://localhost/api/create_contact.php",
I believe the issue is that your angular script is expecting a json response (the default responseType), but not receiving the correct headers or data. In stead of just echoing out your result in php, I would make a function that can handle sending the response. Something like this:
function sendJsonResponse(data, status = 200) {
header('Content-Type: application/json', true, status);
echo json_encode($data);
exit();
}
In stead of of doing this:
echo "Not successful";
You can now do this:
sendJsonResponse("Not successful", 500);
This should give you more valuable information in the frontend. And the response should now be formatted correctly, and no longer produce the parse error in angular that you are getting now.
I believe you are trying to send some query parameters using data variable. You could actually send a JS object as the parameters. Try the following
private saveContactDetails() {
this.proceed = true;
this.success = false;
const myheader = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
const data = {
'name': this.contactDeJson.name,
'email': this.contactDeJson.email,
'subject': this.contactDeJson.subject,
'message': this.contactDeJson.message
}
this.http.post('http://localhost:80/'+'api/create_contact.php', { params: data }, { headers: myheader })
}
I have an api which sends arabic string data and needs to display in html web form using jquery $.ajax method but unfortunately ajax receives only a single character i.e 'a' in response as shown below
{code: 200, status: "error", msg: "a", msg_en: "Invalid Username!!"}
but when i execute the api in postman it shows me this
{"code":200,"status":"error","msg":"اسم المستخدم موجود بالفعل","msg_en":"Username already exists!!"}
this is my code in check_user_name.php
<?php
require_once "../admin/utils/config.php";
require_once "../admin/utils/dbClass.php";
$objDB = new MySQLCN;
require_once "../admin/utils/functions.php";
$fun = new mFunctions;
require_once "lang.confg.php";
$response = array();
if( isset($_POST['user_name']) && $_POST['user_name'] != null){
$user = $objDB->_get_user(null,$_POST['user_name'],null,null,null,null,array('visitor','lawyer','admin'));
if( !empty($user) ){
$response['code'] = 200; // successfull request
$response['status'] = 'error';
$response['msg'] = $_lang['user_name_exists'];
$response['msg_en'] = 'Username already exists!!';
}else{
$response['code'] = 200; // successfull request
$response['status'] = 'success';
$response['msg'] = $_lang['user_name_available'];
$response['msg_en'] = 'Username available!!';
}
}else{
$response['code'] = 200; // invalid paramters
$response['status'] = 'error';
$response['msg'] = $_lang['invalid_requests'];
$response['msg_en'] = 'Invalid Username!!';
}
end:
echo json_encode($response);
exit();
this is ajax request
$(document).on("change", 'input[name=user_name]', function(e) {
/* Act on the event */
var user_name = $ (this).val();
if(user_name.length >= 6 || !user_name.length <=1 ){
$.ajax({
type: 'POST',
url: HOST_URL_API+'/check_user_name.php',
dataType: "json",
contentType: "application/json; charset=utf-8",
data : { 'user_name':user_name }, // our data object
success: function(data) {
console.log(data);
if (data.status == "error") {
$('input[name=user_name]').parent().addClass('has-error');
$('input[name=user_name]').parent().find('.help-block').html(data.msg);
$('input[name=user_name]').focus();
// alert(data.msg);
}else{
$('input[name=user_name]').parent().removeClass('has-error');
$('input[name=user_name]').parent().addClass('has-success');
$('input[name=user_name]').parent().find('.help-block').html('');
}
},
error: function(jqXHR, textStatus, errorThrown, data) {
alert(errorThrown);
},
});
event.preventDefault();
}else{
// alert("Username must be at least 6 characters");
}
});
kindly please if anyone have the solution, will be great help , thanks in advance ;)
Try adding below line in php code which may solve issue while rendering unicode characters.
header("Content-Type : application/json; charset=ISO-8859-1");
Please check this solution hope this will solve your problem i simple create index.php and run this i include header("Content-type: application/json; charset=ISO-8859-1"); this solve the problem.
if (isset($_GET['dataa'])) {
$res['code'] =200;
$res['status'] = 'error';
$res['msg'] = (string) "اسم المستخدم موجود بالفعل";
$res['msg_en'] = 'Username already exists!!';
// header ("Content-Type: text/html; charset=utf-8");
header("Content-type: application/json; charset=ISO-8859-1");
echo json_encode($res);die;
}
in same page html and get req for test resonse and append text to body
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url: "index.php",
type: 'GET',
data : {dataa : 'ss'},
success: function(res) {
console.log(res);
$('body').append(res.msg);
}
});
})
</script>
</body>
</html>
cheers good luck
Problem is solved guys, thanks for your efforts , actually it was the code mistake, there is an another array with same key name was replacing the array key's value, still thanks for your all efforts.
I have this contact form but I am confused as to how I can insert PHPMailer (without Composer) into the script?
I am not sure how to properly add it so that way, once it processes and sends the form it alerts the user. I do not have the ability to utilize composer, so I would need to upload PHPMailer into the directory.
<?php
function validateRecaptcha($secret, $clientResponse, $clientIp)
{
$data = http_build_query([
"secret" => $secret,
"response" => $clientResponse,
"remoteip" => $clientIp,
]);
$options = [
"http" => [
"header" =>
"Content-Type: application/x-www-form-urlencoded\r\n".
"Content-Length: ".strlen($data)."\r\n",
"method" => "POST",
"content" => $data,
],
];
$response = file_get_contents(
"https://www.google.com/recaptcha/api/siteverify",
false,
stream_context_create($options)
);
if($response === false)
{
return false;
}
else if(($arr = json_decode($response, true)) === null)
{
return false;
}
else
{
return $arr["success"];
}
}
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
// validate the variables ======================================================
// if any of these variables don't exist, add an error to our $errors array
if (empty($_POST['firstName']))
$errors['firstName'] = 'First Name is required.';
if (empty($_POST['lastName']))
$errors['lastName'] = 'Last Name is required.';
if (empty($_POST['companyName']))
$errors['companyName'] = 'Company Name is required.';
if (empty($_POST['companyAddress']))
$errors['companyAddress'] = 'Company Address is required.';
if (empty($_POST['city']))
$errors['city'] = 'City is required.';
if (empty($_POST['state']))
$errors['state'] = 'State is required.';
if (empty($_POST['emailAddress']))
$errors['emailAddress'] = 'Email Address is required.';
if (empty($_POST['comment']))
$errors['comment'] = 'Comment is required.';
if (empty($_POST['g-recaptcha-response']))
$errors['captcha'] = 'Captcha is required.';
// return a response ===========================================================
// if there are any errors in our errors array, return a success boolean of false
if(!validateRecaptcha($secret, $_POST['g-recaptcha-response'], $_SERVER["REMOTE_ADDR"]))
{
$errors['recaptcha'] = 'Captcha is required.';
}
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
// DO ALL YOUR FORM PROCESSING HERE
// THIS CAN BE WHATEVER YOU WANT TO DO (LOGIN, SAVE, UPDATE, WHATEVER)
// show a message of success and provide a true success variable
$data['success'] = true;
$data['message'] = 'Success!';
}
// return all our data to an AJAX call
echo json_encode($data);
Without autoloader:
<?php
//You shall use the following exact namespaces no
//matter in whathever directory you upload your
//phpmailer files.
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
//Now include the following following files based
//on the correct file path. Third file is required only if you want to enable SMTP.
require 'path/to/PHPMailer/src/Exception.php';
require 'path/to/PHPMailer/src/PHPMailer.php';
require 'path/to/PHPMailer/src/SMTP.php';
?>
You shall add the following class to initiate the mailer after checking if your query or condition is executed.
<?php
$mail = new PHPMailer(true);
?>
You shall find a nice and simple example at https://github.com/PHPMailer/PHPMailer/blob/master/README.md to start with.
I hope it helps.
I have implemented Google reCaptcha on a site, for the newsletter subscription form, and it does not stop spam. I got up to 20 spam subscribers per day!
What am I not doing correct? Please have a look at the code:
HTML
<form method="post" action="databasepage.php" id="formid" >
<div id="g-recaptcha-answer"></div>
<input name="email" placeholder="Email..." type="email" required>
<button class="g-recaptcha" data-sitekey="my_key" data-callback='onReturnCallback'>Submit</button>
</form>
jQuery
<script>
var onReturnCallback = function(response) {
document.getElementById('g-recaptcha-answer').innerHTML = '';
var url='proxy.php?url=' + 'https://www.google.com/recaptcha/api/siteverify';
$.ajax({ 'url' : url,
dataType: 'json',
data: { response: response },
success: function( data ) {
var res = data.success.toString();
if (res == 'true') {
document.getElementById('g-recaptcha-answer').innerHTML = 'Please wait for a redirect.';
document.getElementById("formid").submit();
}
else {
document.getElementById('g-recaptcha-answer').innerHTML = 'Verification incorrect.';
grecaptcha.reset();
}
}
});
};
</script>
proxy.php
<?php
if (!isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
header('HTTP/1.0 403 Forbidden');
die('You are not allowed to access this file.');
}
header('Content-type: application/json');
$url=$_GET['url'];
$response=$_GET['response'];
$secret = "secret_key";
$params = array('secret'=> $secret, 'response'=> $response);
$json=file_get_contents( $url . '?secret=' . $secret . '&response=' . $response);
echo $json;
?>
I have tested this with Incognito Mode, I get the step when I have to verify pictures, if I am not logged in Gmail etc., in reCaptcha admin area I have no errors, but I STILL RECEIVE SPAM EMAILS IN MY DATABASE!!!
What is wrong in my approach?
I am trying to retrieve data from AngularJS file to PHP file, but I get the error that it's empty.
I can't find any good examples that are dealing with posting data from angularJS to php file and so I need help.
Angularjs file:
angular.module('myApp', ['ajoslin.promise-tracker'])
.controller('help', function ($scope, $http, $log, promiseTracker, $timeout) {
$scope.ph_numbr =/[0-9]+/;
// Form submit handler.
$scope.submit = function(form) {
// Trigger validation flag.
$scope.submitted = true;
// If form is invalid, return and let AngularJS show validation errors.
if (!$scope.toggle || $scope.toggle.length <= 0 || form.$invalid) {
return;
}
// Default values for the request.
$scope.progress = promiseTracker('progress');
var config = {
params : {
//'callback' : 'JSON_CALLBACK',
'name' : $scope.name,
'email' : $scope.email,
'toggle' : $scope.toggle,
'phone' : $scope.phone,
'comments' : $scope.comments
},
tracker : 'progress'
};
$http({
method : 'POST',
url : 'js/contact.php',
data: config,
headers : {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
})
.success(function(data, status, headers, config) {
if (data.success) {
$scope.name = null;
$scope.email = null;
$scope.toggle = null;
$scope.phone = null;
$scope.comments = null;
$scope.messages = 'Your form has been sent!';
$scope.submitted = false;
} else {
$scope.messages = 'Oops, we received your request, but there was an error processing it.';
$log.error(data);
}
})
.error(function(data, status, headers, config) {
$scope.progress = data;
$scope.messages = 'There was a network error. Try again later.';
$log.error(data);
});
// Hide the status message which was set above after 3 seconds.
var promise = $timeout(function() {
$scope.messages = null;
}, 3000);
$scope.progress.addPromise(promise);
};
});
php file:
<?php
/*error_reporting(E_ALL);
ini_set('display_errors', '1');
require_once 'js/PHPMailerAutoload.php';*/
ini_set('display_errors', 'On');
error_reporting(E_ALL | E_STRICT);
$data = file_get_contents("php://input");
$postData = json_decode($data);
if (isset($_POST['name']) && isset($_POST['email']) && isset($_POST['toggle']) && isset($_POST['comments'])) {
//check if any of the inputs are empty
if (empty($_POST['name']) || empty($_POST['email']) || empty($_POST['toggle']) || empty($_POST['comments'])) {
$data = array('success' => false, 'message' => 'Please fill out the form completely.');
echo json_encode($data);
exit;
}
$email = trim($_POST['email']);
$subject = trim($_POST['toggle']);
//email address settings
$my_address = "*#yahoo.com";
$headers = "From: ".$email;
$message = "Name: " . $_POST['name'] . "\r\n\r\nMessage: " . $_POST["phone"] . "\r\n\r\nMessage: " . stripslashes($_POST['comments']);
$to = $my_address;
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;
}
mail($to, $subject, $message, $headers);
$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);
}
?>
The error message that I get is: "Please fill out the form completely" - which means it doesn't get the values.
My other question is how in the AngularJS do I retrieve the data.success value from the php file?
You seem to be getting the data here:
$data = file_get_contents("php://input");
$postData = json_decode($data);
but then you're using $_POST instead. Perhaps this would work:
if (empty($postData['name']) //etc
It looks like you're accessing data.success appropriately and the value should be set to false as your code currently is.
Additional code review:
If there are errors on the server, it's best to return a status code that indicates that. As is, the server is returning 200 (default), which means everything is OK, even though the request is actually failing. That would eliminate the need for data.success. If the server sends status 200, your .success function will fire. If it returns an error status, like 404, then your .error function would fire instead.
I have doubts about your need of the Content-Type header. You might want to reconsider if that's necessary.
On your Angular form, you ought to nest those $scope properties in an object:
$scope.formData = {
name: '',
email: '',
//etc
}
Then, you can simply pass that directly to your $http call and to reset the values you can simply do $scope.formData = {}.