Skip to content

Instantly share code, notes, and snippets.

@flexscss
Last active January 10, 2018 13:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save flexscss/177ebac40d0ef34d371935588147be97 to your computer and use it in GitHub Desktop.
Save flexscss/177ebac40d0ef34d371935588147be97 to your computer and use it in GitHub Desktop.
Sending json from forms
<?php
$json = file_get_contents('php://input');
$data = json_decode($json, true);
$errors = array();
// Form params variables
$param1 = '';
$param2 = '';
if (isset($data['param1'])) {
$param1 = $data['param1'];
} else {
array_push($errors, 'Need param1.');
}
if (isset($data['param2'])) {
$param2 = $data['param2'];
} else {
array_push($errors, 'Need param2.');
}
if (count($errors) != 0) {
$errors_messages = '';
foreach($errors as $error) {
$errors_messages = $errors_messages.$error.' ';
}
echo $errors_messages;
} else {
$html = '
<h3>Message header.</h3>
<p>Param1: '.$param1.'</p>
<p>Param2: '.$param2.'</p>';
$to = "<mail@gmail.com>";
$subject = "Message subject.";
$message = $html;
$headers = "Content-type: text/html; charset=utf-8 \r\n";
$headers .= "From: Mail from <noreply@example.com>\r\n";
$headers .= "Reply-To: reply-to@example.com\r\n";
mail($to, $subject, $message, $headers);
echo 'Message send!';
}
?>
var data = {
param1: 1,
param2: 2
}
var xhr = new XMLHttpRequest()
xhr.open('POST', 'mail.php', true)
xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8')
xhr.send(JSON.stringify(data))
xhr.onreadystatechange = function () {
if (xhr.readyState != 4) return
if (xhr.status === 200) {
console.log(xhr.responseText )
} else {
console.log(xhr.status + ': ' + xhr.statusText )
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment