I am new to PHP and trying to learn how to set up an option where people can send an emai by clicking on the submit button. But I have checked all the codes several times, but could not figure out what I doing wrong.
The console says:
ajax.js:24 POST http://localhost:8081/send_email.php 405 (Method Not Allowed)
Access denied at syntax: ajax.open("POST", "send_email.php");;`
Files folder structure:
send_email.php
index.html
JS
-ajax.js //
How could I get this little tiny thing running. Need some help from you guys to get this thing running, als0 you see I am almost there.
function _(id) {
return document.getElementById(id);
}
function submitForm() {
_("button").disbaled = true;
_("status").innerHTML = "Please wait...";
var formdata = new FormData();
formdata.append( "email", _("email").value );
formdata.append( "subject", _("subject").value );
formdata.append( "message", _("message").value );
var ajax = new XMLHttpRequest();
ajax.open("POST", "send_email.php"); // parameter: method, url, boolean (optional)
ajax.onreadystatechange = function() {
if(ajax.readyState == 4 && ajax.status == 200) {
if(ajax.responseText == "success") {
_("contact-form").innerHTML = "<h2>Thanks, your email is sent successfully</h2>!";
} else {
_("status").innerHTML = ajax.responseText;
_("mybtn").disabled = false;
}
}
}
ajax.send( formdata );
}
Server side code:
<?php
if ( isset($_POST["email"]) && isset($_POST["subject"]) && isset($_POST["message"]) ) {
$email = $_POST["email"];
$subject = $_POST["subject"];
$message = nl2br($_POST["message"]);
$to = "you@hotmail.com";
$from = $email;
$subject = "Contact From Message";
$message = "<b>Email Address:</b> ".$email. " <br><b>Subject: </b> ".$subject." <br><p> ".$message." </p>";
$headers = "From: $from\n";
$headers = "MIME-version: 1.0\n";
$headers = "Content-type: text/html; charset=iso-8859-1\n";
if ( mail($to, $subject, $message, $headers)) {
echo "success";
} else {
echo "The server failed to send the message. Please try again later.";
}
}
?>
<body>
<form id="contact-form" onsubmit="submitForm(); return false;">
<label>
<span class="contact">Your Email</span>
<input id="email" class="contact_input" type="text" name="email" placeholder="name@hotmail.com">
</label>
<label>
<span class="contact">Subject</span>
<input id="subject" class="contact_input contactinfo" type="text" name="message">
</label>
<label>
<span class="contact">Message</span>
<textarea id="message" class="contact_input contactinfo" type="text"></textarea>
</label>
<label>
<input id="button" type="submit" value="SEND">
<span id="status"></span>
</label>
</form>
</body>