Issue:
After clicking the submit button on my HTML form, a JavaScript function is called with an Ajax request. The request returns successfully, but the result disappears quickly.
I'm curious if I may be overlooking something here (besides jQuery, which would make it easier, but xmlhttprequest is currently a requirement).
Below is my code - perhaps there's a small mistake I've missed (fingers crossed) as it has been some time since I worked with Ajax.
HTML Code:
<body>
<form>
<label>Name:</label>
<input type="text" id="name" value="test1" placeholder="Your name" >
<label>Email:</label>
<input type="email" id="email" value="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="83f7e6f0f7b1c3e2e0eee6ade0ecee">[email protected]</a>" placeholder="Your email" >
<label>Country:</label>
<input type="text" id="country" value="test3" placeholder="Your country" >
<input type="submit" value="Submit Form" onclick="postRequest()" >
</form>
<div id="repsonse"></div>
<script src="scripts.js"></script>
</body>
JavaScript:
function postRequest()
{
//data from the form
var name = document.getElementById('name').value;
var email = document.getElementById('email').value;
var country = document.getElementById('country').value;
var submitForm = "submitForm";
//ajax objects
var http = new XMLHttpRequest();
var url = "functions_ajax.php";
var params = JSON.stringify({ callFunction : submitForm, name : name, email : email, country : country });
//alert(params);
//Deal with ajax components
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/json; charset=utf-8");
http.send(params);
http.onreadystatechange = function() {
//alert("Checking Status "+http.status+" "+http.readyState);
if(http.readyState == 4 && http.status == 200) {
//Return the data from the ajax request
console.log(http.responseText);
document.getElementById("repsonse").innerHTML = "<h1>Success!</h1>";
}
else
{
console.log(http.responseText);
console.log(http.status);
document.getElementById("repsonse").innerHTML = "<h1>No Cigar! HTTP Status == "+http.status+" </h1>";
}
}
}