I have encountered an issue while attempting to send a GET request from a form using the form's onsubmit='function();' and AJAX.
<html>
<head>
<script type='text/javascript'>
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
window.alert("readystate change: " + xmlhttp.readyState + " , " + xmlhttp.status);
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById('adminPanel').innerHTML = xmlhttp.responseText;
}
}
function submit_password(){
xmlhttp.open("GET","./src/admin_pass.php");
xmlhttp.send();
}
</script>
</head>
<body>
<form onsubmit='submit_password();'>
<input type='password' placeholder='PASSWORD'>
</form>
<div id='adminPanel'>
</div>
</body>
</html>
<?php
echo "test text";
?>
Upon investigation, I noticed that when I make calls from within the function using form submit, I receive a status=0 error. However, if I remove the function and let everything run at once, it executes smoothly. This has left me puzzled as to why this is happening. While searching online for solutions, I could not find any examples similar to what I am trying to achieve. Despite thinking about resorting to jQuery's ajax function in the end, I prefer not to include it just for this purpose.
EDIT: After further analysis, I discovered that the XMLhttprequest status=0 implies a HTTP connection error. Could it be due to an issue with my URL structure? The directory layout appears as follows:
root
src
admin_pass.php
Should I specify http:// localhost/src/admin_pass.php? In previous test scenarios, utilizing relative URLs worked without any problems.
EDIT: Updated with a comprehensive example
FIXED:
To my surprise, removing the unnecessary form resolved the problem. Though unsure of the exact reason behind this solution, responses suggesting issues with the form prompted me to take this action.
<html>
<head>
<title>Admin Page</title>
<script type='text/javascript'>
function submit_password(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
window.alert("readystate change: " + xmlhttp.readyState + " , " + xmlhttp.status);
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById('adminPanel').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","./src/admin_pass.php",true);
xmlhttp.send();
}
function check_enter(e){
if(e.keyCode == 13){
submit_password();
}
}
</script>
</head>
<body>
<input id='password' type='password' placeholder='PASSWORD PLEASE' onkeyup='check_enter(event);'>
<div id='adminPanel'>
</div>
</body>
</html>