</div>
</div>
<div class="grid--cell mb0 mt4">
<a href="/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call" dir="ltr">How do I return the response from an asynchronous call?</a>
<span class="question-originals-answer-count">
(38 answers)
</span>
</div>
<div class="grid--cell mb0 mt8">Closed <span title="2018-03-27 15:11:27Z" class="relativetime">2 years ago</span>.</div>
</div>
</aside>
I'm trying to make a form to signup to my site but AJAX is not returning false for an onsubmit
. Here is my code:
var c = false;
var h = true;
function hi(g, j, k) {
if (g == j) {
h = false;
}
}
function validateForm() {
var x = document.forms["hi"]["pass1"].value, v = document.forms["hi"]["pass2"].value, b = document.forms["hi"]["user"].value;
if (x != v) {
alert("Passwords must match");
return c;
}
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var a = this.responseText.split("
")
for (var n in a) {
console.log(a);
console.log(a[n]);
console.log(b);
hi(a[n], b, this.responseText)
if (a[n] == b) {
alert("Username already exists")
return c;
};
};
};
};
xmlhttp.open("GET", "http://www.ncpcs.com/carter/user.txt", true);
xmlhttp.send();
return h;
}`
and the onsubmit
has return validateForm()
</div>
Here's a different approach
First, instead of using onsubmit
attribute on your form, use an onclick
attribute on a normal (i.e. type="button"
) button. Upon clicking on the button, it will call the validateForm()
function.
<form name="hi" action="otherPage.html">
<input type="text" name="user" value="" />
<input type="password" name="pass1" value="" />
<input type="password" name="pass2" value="" />
<button type="button" onclick="validateForm()">Submit</button>
</form>
Within function, if there is an error, it will simply alert. If all goes well, it will submit the form.
function validateForm() {
// use better variable names
var form = document.forms["hi"],
pass1 = form["pass1"].value,
pass2 = form["pass2"].value,
user = form["user"].value;
if (pass1 != pass2) {
alert("Passwords must match");
// this is only used to prevent execution of the rest of the function
return;
}
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var a = this.responseText.split("
")
for (var n in a) {
console.log(a);
console.log(a[n]);
console.log(user);
//hi(a[n], user, this.responseText)
if (a[n] == user) {
alert("Username already exists")
return;
}
};
// at this point, everything went well so submit the form
form.submit();
};
};
xmlhttp.open("GET", "http://www.ncpcs.com/carter/user.txt", true);
xmlhttp.send();
}