Errors in console
I am using a Mailchimp Ajax Submit jQuery Plugin to submit an email using a PHP file on a contact form in a website template I imported to my Angular app. When I go to enter my details on the form and submit, the page refreshes on the POST request.
The console then throws the following two errors.
[Deprecation] Synchronous XMLHttpRequest
[Deprecation] Synchronous XMLHttpRequest
on the main thread is deprecated because of its detrimental effects to the
end user's experience. For more help, check https://xhr.spec.whatwg.org/.
(anonymous) # polyfills.c5fb4ffca9c225046d5a.js:1
polyfills.c5fb4ffca9c225046d5a.js:1
Uncaught Error: Zone already loaded.
Uncaught Error: Zone already loaded.
at polyfills.c5fb4ffca9c225046d5a.js:1
at polyfills.c5fb4ffca9c225046d5a.js:1
at Object.0TWp (polyfills.c5fb4ffca9c225046d5a.js:1)
at p (<anonymous>:1:507)
at Object.hN/g (polyfills.c5fb4ffca9c225046d5a.js:1)
at p (<anonymous>:1:507)
at Object.5 (polyfills.c5fb4ffca9c225046d5a.js:1)
at p (<anonymous>:1:507)
at n (<anonymous>:1:376)
at e (<anonymous>:1:248)
I am finding it difficult to understand the cause of the problem. I have tried to prevent the page from refreshing on submit using <button type="button">, this does not do a page refresh however it does not call a POST request as expected.
I have also tried un-commenting import 'zone.js/dist/zone'; in polyfills.ts
I wish to accomplish sending the email on the same page without a refresh in the Angular app unless there is a better alternative. (I am learning)
main.js
var clContactForm = function() {
/* local validation */
$('#contactForm').validate({
/* submit via ajax */
submitHandler: function(form) {
var sLoader = $('.submit-loader');
$.ajax({
type: "POST",
url: "inc/sendEmail.php",
data: $(form).serialize(),
beforeSend: function() {
sLoader.slideDown("slow");
},
success: function(msg) {
// Message was sent
if (msg == 'OK') {
sLoader.slideUp("slow");
$('.message-warning').fadeOut();
$('#contactForm').fadeOut();
$('.message-success').fadeIn();
}
// There was an error
else {
sLoader.slideUp("slow");
$('.message-warning').html(msg);
$('.message-warning').slideDown("slow");
}
},
error: function() {
sLoader.slideUp("slow");
$('.message-warning').html("Something went wrong. Please try again.");
$('.message-warning').slideDown("slow");
}
});
}
});
};
sendEmail.php
<?php
// Replace this with your own email address
$siteOwnersEmail = 'my-email';
if($_POST) {
$name = trim(stripslashes($_POST['contactName']));
$email = trim(stripslashes($_POST['contactEmail']));
$subject = trim(stripslashes($_POST['contactSubject']));
$contact_message = trim(stripslashes($_POST['contactMessage']));
// Check Name
if (strlen($name) < 2) {
$error['name'] = "Please enter your name.";
}
// Check Email
if (!preg_match('/^[a-z0-9&\'\.\-_\+]+#[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is', $email)) {
$error['email'] = "Please enter a valid email address.";
}
// Check Message
if (strlen($contact_message) < 15) {
$error['message'] = "Please enter your message. It should have at least 15 characters.";
}
// Subject
if ($subject == '') { $subject = "Contact Form Submission"; }
// Set Message
$message .= "Email from: " . $name . "<br />";
$message .= "Email address: " . $email . "<br />";
$message .= "Message: <br />";
$message .= $contact_message;
$message .= "<br /> ----- <br /> This email was sent from your site's contact form. <br />";
// Set From: header
$from = $name . " <" . $email . ">";
// Email Headers
$headers = "From: " . $from . "\r\n";
$headers .= "Reply-To: ". $email . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
if (!$error) {
ini_set("sendmail_from", $siteOwnersEmail); // for windows server
$mail = mail($siteOwnersEmail, $subject, $message, $headers);
if ($mail) { echo "OK"; }
else { echo "Something went wrong. Please try again."; }
} # end if - no validation error
else {
$response = (isset($error['name'])) ? $error['name'] . "<br /> \n" : null;
$response .= (isset($error['email'])) ? $error['email'] . "<br /> \n" : null;
$response .= (isset($error['message'])) ? $error['message'] . "<br />" :
null;
echo $response;
} # end if - there was a validation error
}
?>
Related
I want to redirect the user to another page only after displaying a success message. The code below redirects to the another page even if the page is refreshed without submitting any data.
Code Snippet
<?php
// We will store our status message later
$message = '';
// Let's check form submitted
if( isset( $_POST['action'] ) && $_POST['action'] == 'submit' ) {
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['number'];
$message_text = $_POST['address'];
if (isset($_POST['action']))
{
// Validate required fields
if( $name == '' || $email == '' || $message_text == '' ){
$message = "<p class=\"error\">Please fill out all required fields.</p>";
}
// send email after validation
else {
// Email will be sent at this email
$mailto = 'nepstarditsolutions#gmail.com';
// Let's create html email format
// (You can use html in this email format)
// Email headers
$headers = "From: " . strip_tags( $email ) . "\r\n";
$headers .= "Reply-To: ". strip_tags( $email ) . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
// Email body
$message = "<html><body>";
$message .= "<h3>Contact Info: </h3>";
$message .= "<p><strong>Name: </strong> ". strip_tags( $name ) . "</p>\r\n";
$message .= "<p><strong>Email: </strong> ". strip_tags( $email ) . "</p>\r\n";
$message .= "<p><strong>Contact Number: </strong> ". strip_tags( $phone ) . "</p>\r\n";
$message .= "<p><strong>Alternate Email: </strong> ". strip_tags( $_POST['altemail'] ) . "</p>\r\n";
$message .= "<p><strong>Hosting Package: </strong> ". strip_tags( $_POST['cradio'] ) . "</p>\r\n";
$message .= "<p><strong>Address: </strong>". strip_tags( $message_text ) . "</p>\r\n";
$message .= "</body></html>";
// Email subject
$subject = "Contact Info from ".$name;
// Send email
$mail_status = #mail( $mailto, $subject, $message, $headers );
if( $mail_status ){
$message = '<div class="alert alert-success">Quotation submitted Successfully ! </div>';
}
else {
$message = '<div class="alert alert-danger">Error in sending the Quotation ! </div>';
}
}
}
}
?>
I need help in 2 things
Success message should be displayed for 2 seconds (before the redirect).
How to redirect using JS in php?
Standard "vanilla" JavaScript way to redirect a page
You can use the code below to redirect the user after form submission code.
if( $mail_status ){
echo "
<script>
setTimeout(function() {
window.location = 'http://www.example.com/newlocation';
}, 2000);
</script>
";
}
MDN web docs on how setTimeout works
Hope it helps!
i am having a problem to do a webhook with the facebook api on a lead ads form.
Last day it was working like a charm. On the 'Lead Ads Testing Tool' i received a status = success. Now i received a status = failure, error code = 102, error message = server failure
image of the error 102
Anyone know this issue ?
here my webhook.php :
if (isset($_GET['hub_verify_token'])) {
if ($_GET['hub_verify_token'] === 'your verify token') {
echo $_GET['hub_challenge'];
return;
} else {
echo 'Invalid Verify Token';
return;
}
}
$input = json_decode(file_get_contents('php://input'), true);
$emailfrom = "test#test.com";
$emailto = "my#email.com";
$subject = "You've got a new submission Test";
$headers = "From: " . $emailfrom . "\r";
$headers .= "Reply-To: ". $emailfrom . "\r";
$headers .= "MIME-Version: 1.0\r";
$headers .= "Content-Type: text/html; charset=utf-8\r";
$body = 'hello';
mail($emailto, $subject, $body, $headers);
and the callback_url is good = "success": true image graph api subscription to webhook
Thanks
On a Linux server, I have an ajax form that gets posted to a js script, which in turn posts to a php routine for sending a web site email contact form (Styleshout-Puremedia template). I know the post is occurring to js, and to the php page. I get an httpd server error on the php page that "$Error is undefined". However if I define it as NULL or '' it exists and therefore doesn't pass the test "if (!$Error)". If I create a hard-coded php script using the mail function, the e-mail works so php and sendmail are all configured properly. Can someone help as to why this php script doesn't work, or how to fix the "$Error" error?
PHP code:
<?php
// Replace this with your own email address
$siteOwnersEmail = 'info#mydomain.com';
if($_POST) {
$fname = trim(stripslashes($_POST['contactFname']));
$lname = trim(stripslashes($_POST['contactLname']));
$email = trim(stripslashes($_POST['contactEmail']));
$subject = trim(stripslashes($_POST['contactSubject']));
$contact_message = trim(stripslashes($_POST['contactMessage']));
// Check First Name
if (strlen($fname) < 2) {
$error['fname'] = "Please enter your first name.";
}
// Check Last Name
if (strlen($lname) < 2) {
$error['lname'] = "Please enter your last name.";
}
// Check Email
if (!preg_match('/^[a-z0-9&\'\.\-_\+]+#[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is', $email)) {
$error['email'] = "Please enter a valid email address.";
}
// Check Message
if (strlen($contact_message) < 15) {
$error['message'] = "Please enter your message. It should have at least 15 characters.";
}
// Subject
if ($subject == '') { $subject = "Contact Form Submission"; }
// Set Name
$name = $fname . " " . $lname;
// Set Message
$message = "Email from: " . $name . "<br />";
$message .= "Email address: " . $email . "<br />";
$message .= "Message: <br />";
$message .= $contact_message;
$message .= "<br /> ----- <br /> This email was sent from your site's contact form. <br />";
// Set From: header
$from = $name . " <" . $email . ">";
// Email Headers
$headers = "From: " . $from . "\r\n";
$headers .= "Reply-To: ". $email . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
if (!$error) {
ini_set("sendmail_from", $siteOwnersEmail); // for windows server
$mail = mail($siteOwnersEmail, $subject, $message, $headers);
if ($mail) { echo "OK"; }
else { echo "Something went wrong. Please try again."; }
} # end if - no validation error
else {
$response = (isset($error['fname'])) ? $error['fname'] . "<br /> \n" : null;
$response .= (isset($error['lname'])) ? $error['lname'] . "<br /> \n" : null;
$response .= (isset($error['email'])) ? $error['email'] . "<br /> \n" : null;
$response .= (isset($error['message'])) ? $error['message'] . "<br />" : null;
echo $response;
} # end if - there was a validation error
}
?>
Thanks for your help!!
-Rob
You can always just initialize $error as
$error = [];
and then check for errors by
if(count($errors) === 0){
//no errors
}
Or, just use if(!isset($error)){//no errors}
I am lost on why i am getting this internal error(500). My email info still go through when i click submit. The only problem i have is that the ajax success method is not being called so basically my callback function is never getting called on. Any help would be greatly appreciated. I have been pulling my hair out for hours on this problem.
My scipt-ajax call:
emailValidation: function(e){
e.preventDefault();
$('body, html').animate({scrollTop:0},"slow");
var valid = '';
var name = $("#f_name").val();
var email = $("#f_email").val();
var message = $("#f_message").val();
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if(name === '' || name.length <= 2){
valid += '<p class="error">Name must be longer than 2 char.</p>';
}
if(message === '' || message.length <= 5){
valid += '<p class="error">Message must be longer than 5 char.</p>';
}
if (!(email).match(emailReg)){
valid += '<p class="error">Invalid Email</p>';
}
if (valid !== ''){
$('#form-messages').html(''+valid+'').fadeIn();
}
else {
var formData = $("#contact").serialize();//Value for sanitized form values to be paased to email.php. Value returns an array
portfolio.submitEmail(formData);
}
},
submitEmail: function(formData){
console.log(formData);
//$('#form-messages').html("Proccessing...<img src='img/processing_bar.png' alt='Proccessing' />").fadeIn('fast');
$('body, html').animate({scrollTop:0},"fast");
$.ajax({
type: 'POST',
url: 'mailer.php',
data: formData,
dataType: 'json',
success: function(result){
console.log(result.statusText);
if(result.statusText === 'OK'){
console.log('jam');
// Make sure that the formMessages div has the 'success' class.
$('#form-messages').removeClass('error');
$('#form-messages').addClass('success');
// Set the message text.
$('#form-messages').html('<p class="success">Message has been sent succesfully! Thank you '+ $('#f_name').val() +', a response will be returned in less than one business day.</p>');
$("#contact").fadeOut('slow').remove();
$('body, html').animate({scrollTop:0},"fast");
}
},
error: function(error){
console.log(error.statusText);
if(error.statusText === 'OK'){
// Make sure that the formMessages div has the 'success' class.
$('#form-messages').removeClass('error');
$('#form-messages').addClass('success');
// Set the message text.
$('#form-messages').html('<p class="success">Message has been sent succesfully! Thank you '+ $('#f_name').val() +', a response will be returned in less than one business day.</p>');
$("#contact").fadeOut('slow').remove();
$('body, html').animate({scrollTop:0},"fast");
}
},
});
},
Here is my mail.php file:
<?php
// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$em_name = strip_tags(trim($_POST["name"]));
$em_name = str_replace(array("\r","\n"),array(" "," "),$em_name);
$em_email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$em_message = $_POST["message"];
$em_phone = $_POST['phone'];
$em_website = $_POST['website'];
$em_hear = $_POST['hear'];
$em_startdate = $_POST['startdate'];
$em_budget = $_POST['budget'];
$to = 'theller5567#gmail.com';
$subject = 'Website Change Request';
$headers = "From: " . $em_email . "\r\n";
$headers .= "Reply-To: ". $em_email . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
// Build the email content.
$message = "<h3>Name: ". $em_name. "\n</h3>";
$message .= "<h3>Message: ". $em_message. "\n</h3>";
$message .= "<p>Budget: ". $em_budget. "\n</p>";
$message .= "<p>Start Date: ". $em_startdate. "\n</p>";
$message .= "<p>How did you hear about us?: ". $em_hear. "\n</p>";
$message .= "<p>Email: ". $em_email. "\n</p>";
$message .= "<p>Phone: ". $em_phone. "\n</p>";
$message .= "<p>Website: ". $em_website. "\n</p>";
if (mail($to, $subject, $message, $headers)) {
http_response_code(200);
echo "Thank You! Your message has been sent.";
} else {
http_response_code(500);
echo "Oops! Something went wrong and we couldn't send your message.";
}
} else {
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>
I have PHP code that help me to other people can be in touch with me and send their opinion to me .
here's my PHP code :
<?php
$to = 'ticket.ritaweb#gmail.com';
$subject = 'Your decision/Opinion';
$name = htmlspecialchars($_REQUEST['name']);
$email = htmlspecialchars($_REQUEST['email']);
$site = htmlspecialchars($_REQUEST['site']);
$mobile = htmlspecialchars($_REQUEST['mobile']);
$nazar = htmlspecialchars($_REQUEST['nazar']);
$sqt = '2164854';
$sqtin = htmlspecialchars($_REQUEST['sqtin']);
if ($sqt === $sqtin) {
function clean_string($string) {
$bad = array("content-
type", "bcc:", "to:", "cc:", "href");
return str_replace($bad, "", $string);
}
$email_message .= "name : " . clean_string($name) . "\n";
$email_message .= "email : " . clean_string($email) . "\n";
$email_message .= "address : " . clean_string($site) . "\n";
$email_message .= "number : " . clean_string($mobile) . "\n";
$email_message .= "opinion : " . clean_string($nazar) . "\n";
$headers = 'From: ' . $mobile . "\r\n" . 'Reply-To: ' . $email . "\r\n" . 'X-Mailer:
PHP/' . phpversion();
mail($to, $subject, $email_message, $headers);
}
?>
and I called it with javascript ( ajax ) but I want a code in ajax that help me If my condition in PHP file was FALSE or each of the field was empty , show the message : "Your message was not send, be careful".
and here's my AJAX code :
<script type="text/javascript">
$(document).ready(function() {
$('#submit').click(function() {
$('#submit').attr('value', 'sending...');
$.post("themes/RitaWeb-v1/send.php", $(".rita_form").serialize(),
function(response) {
$('#submit').attr('value', 'sent.');
});
return false;
});
});
</script>
Use PHP to print messages on the page, like
{'status' : 'success'}
if the mail was sent and
{'status' : 'error'}
Then do something based on the output with js.
EDIT:
If you use jQuery.ajax instead of jQuery.post,you can also use the settings argument to let something happen if there ared errors during the request.
More information: http://api.jquery.com/jquery.ajax/
In your code, it would look like this.
PHP:
...
mail($to, $subject, $email_message, $headers);
print('{"status":"success"}');
}
else{
print('{"status":"error"}');
}
And your js:
$.ajax('themes/RitaWeb-v1/send.php').done(function(data){
status = $.parseJSON(data).status;
if(status == 'success'){
// do something
}
else if(ststus == 'error'){
// do something
}
else{
alert('unknown response');
}
});