js deleting submitted form data - javascript

The problem:
Javascript function( which was premade by template) cleans the form data sent to me by php
The php code:
<?php
header('Content-type: application/json');
$status = array(
'type'=>'success',
'message'=>'GJ '
);
$name = #trim(stripslashes($_POST['name']));
$phone = #trim(stripslashes($_POST['phone']));
$subject = #trim(stripslashes($_POST['subject']));
$message = #trim(stripslashes($_POST['message']));
$email_to = 'email#email.com';//replace with your email
$body = 'Name: ' . $name . "\n\n" . 'Телефон: ' . $phone . "\n\n" . 'Subject: ' . $subject . "\n\n" . 'Message: ' . $message;
$success = #mail($email_to, $subject, $body);
echo json_encode($status);
die;
The javascript function code:
var form = $('.contact-form');
form.submit(function () {'use strict',
$this = $(this);
$.post($(this).attr('action'), function(data) {
$this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
},'json');
return false;
});
When there's no js code php returns white screen with a line but the #mail sends normal message, but when there is this code fade in and out works good, but the data arrives empty. The message in message and name is cyrylic if that is important.
Please help me fix it(i.e. i need both data arriving and success fade-in appearing or at least data arriving with no .php white screen) or just explain what the js code does i don't get it.
Thanks

You haven't provided the data argument for $.post
Try
var form = $('.contact-form');
form.submit(function () {'use strict',
var $this = $(this);
$.post($(this).attr('action'), $this.serialize(), function(data) {
$this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
},'json');
return false;
});
References:
jQuery.post() Docs
jQuery.serialize() Docs

Related

How to mail data from HTML form after it's checked by recaptcha?

I'm working on a contact website, where I want to have contact form. I want it to send data to e-mail and I want it to be checked by Google's recaptcha v3.
This is my second try. In the past, I've done it successfully without recaptcha. Now, I used this (https://codeforgeek.com/google-recaptcha-v3-tutorial/) tutorial, with following result:
script below the form
// when form is submit
$('#myform').submit(function() {
// we stoped it
event.preventDefault();
var mail = $('#email').val();
var comment = $("#sprava").val();
// needs for recaptacha ready
grecaptcha.ready(function() {
// do request for recaptcha token
// response is promise with passed token
grecaptcha.execute('__SITE-KEY__', {action: 'create_comment'}).then(function(token) {
// add token to form
$('#myform').prepend('<input type="hidden" name="g-recaptcha-response" value="' + token + '">');
$.post("form.php",{mail: mail, comment: comment, token: token}, function(result) {
if(result.success) {
alert('Thanks for message')
} else {
alert('An error occured')
}
});
});;
});
});
</script>
the names of html form fields are "email", "vyber", "sprava"
form.php
<?php
$mail;$comment;$captcha;
$mail = filter_input(INPUT_POST, 'mail', FILTER_VALIDATE_EMAIL);
$comment = filter_input(INPUT_POST, 'comment', FILTER_SANITIZE_STRING);
$captcha = filter_input(INPUT_POST, 'token', FILTER_SANITIZE_STRING);
}
function email_sending(){
$webmaster_email = "bla#bla.com";
$sender_email= "blabla#bla.com" ;
$email_address = $_REQUEST['email'] ;
$selection = $_REQUEST['vyber'] ;
$message = $_REQUEST['sprava'];
$msg =
"E-mail: " . $email_address . "\r\n" .
"I'm interested in " . $selection . "\r\n" .
"Message: " . $message ;
mail( "$webmaster_email", "You have mail", $msg, $header);
}
if($responseKeys["success"]) {
echo json_encode(array('success' => 'true'));
email_sending();
} else {
echo json_encode(array('success' => 'false'));
}
?>
The problem isn't within recaptcha part, but then I recieve e-mail, where data is missing. (it shows only variable names, not actual values). I might think it's because of naming in script, as I'm not sure what to write in declaration of variables. I'd be glad to receive any input about this problem.
I managed to solve this problem by changing server-side code like below, thanks to this Recaptcha tutorial.
// Check if form was submitted:
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['recaptcha_response'])) {
// Build POST request:
$recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify';
$recaptcha_secret = '__SECRET-KEY___';
$recaptcha_response = $_POST['recaptcha_response'];
// Make and decode POST request:
$recaptcha = file_get_contents($recaptcha_url . '?secret=' . $recaptcha_secret . '&response=' . $recaptcha_response);
$recaptcha = json_decode($recaptcha);
// Take action based on the score returned:
if ($recaptcha->success == true) {
// Verified - send email
} else {
// Not verified - show form error
}
}

send google tag manager results to php page via ajax method GET

i got a few variables on my site that i push on GTM they work perfect, now i need to get variables results from gtm and send it via ajax to a php page where afterwards i'll use it to an email with the results.
<script>
$(document).ready( function() {
var msg = google_tag_manager["GTM-xxxxx"].dataLayer.get('pageName');
var msg1 = google_tag_manager["GTM-xx"].dataLayer.get('MembershipLvl');
var msg2 = google_tag_manager["GTM-xx"].dataLayer.get('CountryRes');
var msg3 = google_tag_manager["GTM-xxxx"].dataLayer.get('pageLanguage');
var getall = [msg, msg1, msg2, msg3,];
// var me = 'just seend'; this do work
console.log(getall);
$.ajax({
type: "GET",
url: "url.cart.php", // some php
data:{info: getall},
datatype: 'html',
success: function(data) {}
});
});
and here is my php
<?php
/*
*
*/
send_mail();
function send_mail(){
if( $_GET["info"] ) {
$mail = $_GET["info"];
$header ="From: no-reply#test.com" . "\r\n";
$for = 'end#emailadaress.com';
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$title = 'Mailing list Newsletter';
$message = '<html><body>';
$message .= '<br/> <p>tou got email from</p><br/>';
$message .= '<table rules="all" style="border-color: #666;" cellpadding="2">';
$message .= "<tr><td><strong>Email:</strong> </td><td>" . strip_tags($mail)."</td></tr>";
$message .= "</table>";
$message .= "</body></html>";
if(mail($for, $title, $message, $header)){
die();
}else{
//echo "false";
}
}else{
echo "false";
}
}
?>
the issue is that im not getting GTM variables sent, i do see them in console log, if i change variable like var = test, i do get it, but i just cant get the GTM variable sent
So the problem is that $_GET["info"] contains an array which strip_tags cannot handle. If you look at the response from your call it should have a PHP error. Somewhere along the lines of : Warning: strip_tags() expects parameter 1 to be string, array given. If you want to get the values out of the array you can either build a loop or reference the particular index.
LOOP
foreach ($mail as $gtm) {
$message .= $gtm;
}
INDEX
$message .= $mail[0] // google_tag_manager["GTM-xxxxx"].dataLayer.get('pageName');
$message .= $mail[1] // google_tag_manager["GTM-xx"].dataLayer.get('MembershipLvl');
etc...
PHP strip tags
Foreach loop
How to view a ajax call in chrome

contact form collects data not post

Good. I'm creating a contact form and I have a problem. The thing is that I do not control much of javascript and is where the mistake I can not see ........
I know this in the javascript file that if I take sends me the email correctly. But with the javascript file send email to me, but it's like not pick post data, the form, and send it to me empty. But the thing is that I need this javascript. It is what brings out a little message at the top of the form to report that has been submitted successfully. Without me redirected to a blank page with the information message.
This is the section of the HTML contact form:
<div id="contact-section">
<h3>Contacta con nosotros</h3>
<div class="status alert alert-success" style="display: none"></div>
<form id="main-contact-form" class="contact-form" name="contact-form" method="post" action="sendemail.php">
<div class="form-group">
<input type="text" name="name" class="form-control" required="required" placeholder="Nombre">
</div>
<div class="form-group">
<input type="email" name="email" class="form-control" required="required" placeholder="Email">
</div>
<div class="form-group">
<textarea name="message" id="message" required="required" class="form-control" rows="4" placeholder="Mensaje"></textarea>
</div>
<div class="form-group pull-right social-icons">
<input type="submit" class="btn btn-primary pull-right" value="Enviar"</input>
</div>
</form>
</div>
This sends it to a file called sendmail.php is this:
<?php
header('Content-type: application/json');
$status = array(
'type'=>'success',
'message'=>'Gracias por contactar con nosotros. Nos pondremos en contacto con usted lo antes posible '
);
$name = #trim(stripslashes($_POST['name']));
$email = #trim(stripslashes($_POST['email']));
$subject = #trim(stripslashes($_POST['subject']));
$message = #trim(stripslashes($_POST['message']));
$email_from = $email;
$email_to = 'jimprogrammer2015#gmail.com';//replace with your email
$body = 'Name: ' . $name . "\n\n" . 'Email: ' . $email . "\n\n" . 'Subject: ' . $subject . "\n\n" . 'Message: ' . $message;
$success = #mail($email_to, $subject, $body, 'From: <'.$email_from.'>');
echo json_encode($status);
die;
The thing is that the javascript function as I do to teach the Message in the same form that is this:
// Contact form validation
var form = $('.contact-form');
form.submit(function () {'use strict',
$this = $(this);
$.post($(this).attr('action'), function(data) {
$this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
},'json');
return false;
});
Then, the latter javascript code does me good informing about the Message that was sent, and send it to me, but the email blank.
Without this code sends me While email with all data on the post, but I go to a blank page with the Message. And it stays there ......
Thanks for the help.
You aren't actually posting your data check docs http://api.jquery.com/jquery.post/
You rewrite your js code like this
var form = $('.contact-form');
form.submit(function (event) {'use strict',
event.preventDefault();//preventDefault
var $this = $(this), data = $this.serialize();//serialize data
$.post($(this).attr('action'), {data: data}, function(data) {
$this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
},'json');//add post data as second parameter
});
In your php code
<?php
header('Content-type: application/json');
$status = array(
'type'=>'success',
'message'=>'Gracias por contactar con nosotros. Nos pondremos en contacto con usted lo antes posible '
);
$name = #trim(stripslashes($_POST['data']['name']));//get post data
$email = #trim(stripslashes($_POST['data']['email']));//get post data
$subject = #trim(stripslashes($_POST['data']['subject']));//get post data
$message = #trim(stripslashes($_POST['data']['message']));//get post data
$email_from = $email;
$email_to = 'jimprogrammer2015#gmail.com';//replace with your email
$body = 'Name: ' . $name . "\n\n" . 'Email: ' . $email . "\n\n" . 'Subject: ' . $subject . "\n\n" . 'Message: ' . $message;
$success = #mail($email_to, $subject, $body, 'From: <'.$email_from.'>');
echo json_encode($status);
die;
// Contact form validation
var form = $('.contact-form');
form.submit(function () {'use strict',
$this = $(this);
$.post($(this).attr('action'),{data : $(this).serialize()} , function(data) {
$this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
},'json');
return false;
});
Try this snippet, you have to serialize form then send.
after much testing (as I said no javascript is not my specialty) I've fixed the problem. In the post method, did not send anything, I lacked the information I send. I sent this:
$.post("sendemail.php, function(data) {
$this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
},'json');
He carried the URL and call the function I wanted to do. In my case it was right after calling the URL (sendemail.php), you send the data would be loaded in the URL, and then call the function, like this:
$.post("sendemail.php", {name: document.getElementById("name").value, email: document.getElementById("email").value, message: document.getElementById("message").value}, function(data) {
$this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
},'json');
As you see, collect the form values to send. I spent the documentation that has come to me very well.
Thanks for the help.

values not being passed onto process.php

The script below helps with processing of a form that request number and name values, and than sends it to process.php and also displays a confirmation and hides the button that would fired the modal to the form so user cannot retry to fill the form.
Script to handle pass data to process.php
$(document).ready(function () {
function successHandler(){
console.log('Success');
$("#thanks").html(msg);
$('#form-content').modal('hide');
}
function errorHandler(){
console.log('Error');
alert("Error");
}
var nameval = $('#name').val();
var numberval = $('#number').val();
$("form#contact").submit(function(){
$.ajax({
type: "POST",
url: "process.php",
data: {
name: nameval,
number: numberval,
submit: true
},
success: function(msg){
$("#thanks").html(msg);
$('#form-content').modal('hide');
return false;
},
error: function(){
alert("Error");
return false;
}
});
return false;
});
});
The whole action does generate an email with HTML from the process.php script but does not include the data that was captured from the form, I believe there is a error within this script as I cannot find anything on the form or process.php that is using PHPMail() doing anything wrong.
Could you help?
Update
<?php
if (isset($_POST['submit'])) {
$name = ($_POST['name']);
$number = ($_POST['number']);
echo "<span class=\"alert alert-success\">THANKS! SUBMITTED</span>";
$to = "EMAIL BLANKED";
$subject = "Alert!";
$message = "name: $name number: $number";
// Always set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// More headers
$headers .= 'From: <email blank>' . "\r\n";
mail($to,$subject,$message,$headers);
}
else { echo '<div class="alert alert-error">Error</div>' ; }
?>
You should put this two lines:
var nameval = $('#name').val();
var numberval = $('#number').val();
inside the submit function like this
$("form#contact").submit(function(){
var nameval = $('#name').val();
var numberval = $('#number').val();
because if you set the values of the variables before the submission of the form the inputs will most likely be empty.

WordPress form trouble

Some help needed here, I'm building a one page wordpress theme and I don't really know how to make the contact form submit without loading. Basically all my code is on index.php.
This is the form submission php code above the get_header(); It works just fine but I can't really make it submit without loading the page.
if(isset($_POST['user_submit'])) {
$parse_uri = explode( 'wp-content', $_SERVER['SCRIPT_FILENAME'] );
require_once( $parse_uri[0] . 'wp-load.php' );
$name = esc_html($_POST['user_name']);
$email = esc_html($_POST['user_email']);
$comment = esc_html($_POST['user_message']);
$website = esc_html($_POST['user_url']);
$msg = esc_attr('Name: ', 'silver') . $name . PHP_EOL;
$msg .= esc_attr('E-mail: ', 'silver') . $email . PHP_EOL;
$msg .= esc_attr('Website: ', 'silver') . $website . PHP_EOL;
$msg .= esc_attr('Message: ', 'silver') . $comment;
$to = get_option( 'admin_email' );
$sitename = get_bloginfo('name');
$subject = '[' . $sitename . ']' . ' New Message';
$headers = 'From: ' . $name . ' <' . $email . '>' . PHP_EOL;
wp_mail($to, $subject, $msg, $headers);
}
This is the jQuery post I'm using for that:
$( "#contact_form" ).submit(function( event ) {
event.preventDefault();
var $form = $( this ),
name = $form.find( "input[name='user_name']" ).val(),
email = $form.find( "input[name='user_email']" ).val(),
website = $form.find( "input[name='user_url']" ).val(),
comment = $form.find( "input[name='user_message']").val();
$.post( templateDir + "/index.php", { website : website, comment : comment, name : name, email : email, submit : "yes" } );
});
This is the site http://silviuandrei.eu/themes/bornagain/
You're checking for the user_submit POST variable:
if(isset($_POST['user_submit']))
But sending a different variable via $.post
$.post( templateDir + "/index.php", { website : website, ..... submit : "yes" } );
Change it to user_submit : "yes"
I recommend doing it at functions.php using the init action:
add_action('init','form_submits');
function form_submits() {
if( isset($_REQUEST['user_submit']) ){
require("process_post.php");
exit;//prevents the default blog output
}
}
Note that using require is just a suggestion to keep functions.php clean.

Categories