I have this form and I\'m using ajax to send data to a simple php script (just trouble shooting with simple php script) but it is not posting back data to original html form...
There is so many errors but I've got it working, you might want to look at the naming convention on your input fields. For example on name you have the id of id="inputEmail13"
. Use the browser console to see error messages as you're developing.
function validateForm(event)
{
event.preventDefault();
var message = "";
var letters = /^[A-Za-z]+$/;
//do validation
var name = document.forms["myForm"]["name"].value;
var email = document.forms["myForm"]["email"].value;
var subject = document.forms["myForm"]["subject"].value;
var text = document.forms["myForm"]["text"].value;
var outputMsg = "";
//checking for empty fields
if (name == null || name == "") {
message += "name field empty!\n";
}
if (name != "" && !name.match(letters)) {
message += "Invalid name: only letters allowed!\n";
}
if (email == null || email == "") {
message += "email field is empty!\n";
}
if (subject == null || subject == "") {
message += "Subject field is empty!\n";
}
if (text == null || text == "") {
message += "Text field is empty!\n";
}
if (message != "" ) {
alert(message);
return false;
}
//send data to php form--------------------->
// create the XMLHttpRequest object, according browser
// create the variable that will contain the instance of the XMLHttpRequest object (initially with null value)
var xmlHttp = null;
if(window.XMLHttpRequest) { // for Forefox, IE7+, Opera, Safari, ...
xmlHttp = new XMLHttpRequest();
}
else if(window.ActiveXObject) { // for Internet Explorer 5 or 6
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
// sends data to a php file, via POST, and displays the received answer
// create pairs index=value with data that must be sent to server
var parameters="name="+name+"&email="+email;
xmlHttp.open("POST", "contact.php", true); // set the request
// adds a header to tell the PHP script to recognize the data as is sent via POST
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.send(parameters); // calls the send() method with datas as parameter
// Check request status
// If the response is received completely, will be transferred to the HTML tag with tagID
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
document.getElementById("output-data").innerHTML = xmlHttp.responseText;
}
}
return false;
}
In the html you want to remove the visibility:hidden;
on the output div
Edit:
Cause of the request is undefined is because you're never creating a variable called request, yet you're calling one.
request.open("POST", "contact.php", true);
This line will throw the first error saying it's undefined, this can be fixed easily by changing request
to xmlHttp
or modifying xmlHttp = new XMLHttpRequest();
to be request = new ....
same should be done to the other xmlHttp assignment.