Last active
January 10, 2018 13:36
-
-
Save flexscss/177ebac40d0ef34d371935588147be97 to your computer and use it in GitHub Desktop.
Sending json from forms
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 = "<[email protected]>"; | |
$subject = "Message subject."; | |
$message = $html; | |
$headers = "Content-type: text/html; charset=utf-8 \r\n"; | |
$headers .= "From: Mail from <[email protected]>\r\n"; | |
$headers .= "Reply-To: [email protected]\r\n"; | |
mail($to, $subject, $message, $headers); | |
echo 'Message send!'; | |
} | |
?> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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