My form doesn't get submitted although I see the alert "Your message was sent!". Can anyone tell me what's wrong? Here're the codes I have written. I have a table called messages in my database to insert form data entered from HTML form. Thanks!
HTML file
<form action="javascript:contactSubmit();" name="front_home_contact">
<div class="front_home_details_field">
<input type="text" placeholder="Full Name" name="home_contact_field" required pattern="[A-z ]+"/>
</div>
<div class="front_home_details_field">
<input type="text" placeholder="Phone Number" name="home_contact_field" required pattern="0[0-9]{9}" maxlength="10"/>
</div>
<div class="front_home_details_field">
<input type="email" placeholder="E-mail" name="home_contact_field" required/>
</div>
<div class="front_home_details_field">
<input type="text" placeholder="Subject" name="home_contact_field" required pattern="[A-z s]+"/>
</div>
<div class="front_home_details_field" style="height:151px;">
<textarea placeholder="Message" name="home_contact_field" aria-invalid="false" required></textarea>
</div>
<input type="submit" value="Send" name="home_contact_field"/>
</form>
Javascript .js file
function contactSubmit(){
document.front_home_contact.setAttribute("novalidate","true");
var elems = document.getElementsByName("front_home_contact"); //or
var xhrx = (window.XMLHttpRequest)? new XMLHttpRequest(): new activeXObject("Microsoft.XMLHTTP");
var data = new FormData();
data.append("func","insertMsg");
data.append("arg",elems);
alert("Your message was sent!");
/*xhrx.onreadystatechange = function(){
if(xhrx.readyState==4 && xhrx.status==200){
reportSection.innerHTML= xhrx.responseText.trim();
httpComplete +=1;
if (httpComplete == 3) elem.style.display="block";
}
}*/
xhrx.open('post','insertMessages.php',true);
xhrx.send(data);
for (i = 0; i< elems.length;i++){
elems[i].value="";
}
}
PHP file (insertMessages.php
)
<?php
include "config.php";
$function = $_POST['func'];
if ($function == "insertMsg"){
$query = "INSERT INTO `messages`(`SenderName`, `PhoneNumber`, `Email`, `Subject`, `Message`) VALUES ('".$_POST['args'][0]."');";
if(mysqli_query($con,$query)){
echo "<script type='text/javascript'>alert('OK');</script>";
}
else{
echo "<script type='text/javascript'>alert('error');</script>";
}
}
?>
Directly you can not display alert()
from ajax response.
Define onreadystatechange
and define the action you want to perform based on your response.
Directly don't pass script
in php response.
Pass success / error
(if possible just use JSON in sending response) and after receiving in response just check the value and perform action you want to perform.
like,
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if( this.responseText=="success"){
alert('OK');
}else{
alert('error');
}
}
};