AJAX POST XHR Failure - Why is this not working? - javascript

I am pulling my hair out here. I have checked several other posts that were related to issues with POST and AJAX, but none I found were helpful. I cannot figure out why this is not working.
I keep getting the error:
Uncaught TypeError: Cannot read property 'value' of null
at loginRequest (loginRequest.js:3)
at HTMLButtonElement.onclick (main.html:325)
Here is the form on the ".html" page (minus my class calls):
<form id="loginform">
<div>
<label for="login_userid"><b>Username</b></label>
<input id="login_userid" type="text" placeholder="Enter Username" name=login_userid"
autocomplete="username" required>
<label for="login_psw"><b>Password</b></label>
<input id="login_psw" type="password" placeholder="Enter Password" name="login_psw"
autocomplete="current-password" required>
<button onclick="loginRequest()">Login</button>
</div>
Then here is the ".js: file, which I am declaring in the head of the ".html" file:
function loginRequest() {
{
var login_userId = document.getElementById('login_userId').value;
var login_ps = document.getElementById('login_psw').value;
const bcrypt = dcodeIO.bcrypt;
var login_psw = bcrypt.hashSync(login_psw, 12);
var xhr;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 8 and older
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var data = "login_userId=" + login_userId + "&login_psw=" + login_psw;
xhr.open("POST", "https://dfs-coach.com/assets/php/login.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(data);
xhr.onreadystatechange = display_data;
function display_data() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
//alert(xhr.responseText);
document.getElementById("login_result").innerHTML = xhr.responseText;
} else {
alert('There was a problem with the request.');
}
}
}
}
}
Note: bcrypt.js is also declared in head, after loginrequest.js.
The '#login_result' element is at the top of the html page (login form opens in a modal)
I cannot figure out where my screw up is with this one.. I know it is going to be something I did, i.e., a syntax error, scope issue,. etc... but I cannot find it.
The error returns that the username is null, which is difficult to believe since A: I type it in before hitting the button to trigger the function, and B: it is a required field, so I cannot hit the button if it is not filled.
However, I get that TypeError from above and then the browser tacks the correct info onto the end of the current URL in plain text and it appears in my address bar. This happens both locally and from an active web server.
The Dev Panel shows this as an "Info" entry:
Navigated to
https://www.dfs-coach.com/main.html?login_userid=MyUsernm&login_psw=PwformyUser
(Info typed into form: 'MyUsern' and 'PwformyUser')
Feel free to see the live demo of this error: https://dfs-coach.com/main.html
I would appreciate any help at all on this one.
Thanks
P.S.: I have also tried using both '.innerHTML' and innerText' instead of 'value' on the Dom elements, and also sending the form data as FormData and json. All to no avail.

There two issues which can easily be fixed I found in the code snippet in the question:
1.
In the 1st line of the function you tried to find an element by the id: login_userId, however the element is named login_userid in the HTML code, Make sure that the capitalization is the same otherwise document.getElementById won't find the correct element
2.
Another small mistake in the 4th line of the code where you try to hash login_psw bcrypt.hashSync(login_psw, 12); however that variable does not exist yet. I believe what you are trying to do is hash the login_ps variable made a couple lines earlier
I also suggest you to put the function immediately after the xhr.onreadystatechange
Code that should work:
<body>
<script src="https://cdn.jsdelivr.net/npm/bcryptjs#2.4.3/dist/bcrypt.min.js"></script>
<div id="loginform">
<div>
<label for="login_userid"><b>Username</b></label>
<input id="login_userid" type="text" placeholder="Enter Username" name=login_userid"
autocomplete="username" required>
<label for="login_psw"><b>Password</b></label>
<input id="login_psw" type="password" placeholder="Enter Password" name="login_psw"
autocomplete="current-password" required>
<button onclick="loginRequest()">Login</button>
</div>
</div>
</body>
<script>
function loginRequest() {
{
var login_userId = document.getElementById('login_userid').value;
var login_ps = document.getElementById('login_psw').value;
const bcrypt = dcodeIO.bcrypt;
var login_psw = bcrypt.hashSync(login_ps, 12);
var xhr;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 8 and older
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var data = "login_userId=" + login_userId + "&login_psw=" + login_psw;
xhr.open("POST", "https://dfs-coach.com/assets/php/login.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(data);
xhr.onreadystatechange = function display_data() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
alert(xhr.responseText);
} else {
alert('There was a problem with the request.');
}
}
}
}
}
</script>

Related

Why does not the Ajax response shown in innerHTML and changes back to the original text?

I am trying to get a response from a local file and display it. However, the response text changes back to the original text. Any help would be appreciated.
<script>
function getMsg(text) {
if (text.length == 0) {
document.getElementById("msg").innerHTML = "";
return;
} else {
document.getElementById("msg").innerHTML = "sending request";
var xhttp = new XMLHttpRequest();
var filepath = "";
if (inputText == "File1") {
filepath = "file1.txt";
} else if (inputText == "File2") {
filepath = "file2.txt";
}
xhttp.open("GET", filepath, true);
xhttp.send();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.response);
document.getElementById("msg").innerHTML = this.responseText;
} else {
document.getElementById("msg").innerHTML = "failed";
}
};
}
}
</script>
<body>
<form onsubmit="getMsg(this.file.value)">
<label for="file">File:</label>
<input type="text" name="file" id="file">
<button type="submit">Get</button>
</form>
</body>
This is because you form submits normally along with your ajax and reload the page. You can prevent the form from submitting by returning false from your onsubmit handler.
<form onsubmit="getMsg(this.file.value); return false">
Welcome to Stackoverflow, by reading your code I noticed you got two main issues.
Avoid using innerHTML, it's a bad practice.
When you use innerHTML, even if your string variable is only text (no HTML tags, etc), the content is parsed by JavaScript which takes time, it might not be significant in a small app like this, but in bigger apps this has a big impact in performance.
Use innerText.
You are not preventing the default behavior of your form.
When using AJAX request, the best approach for this is to set an event listener to the form like this:
Your HTML:
<form id="file_select"><!-- Add an id to identify the form -->
<label for="file">File:</label>
<input type="text" name="file" id="file">
<button type="submit">Get</button>
</form>
<div id="msg"></div>
You can add an event listener in JavaScript like this:
document.querySelector("#file_select").addEventListener("submit",(event)=>{
event.preventDefault();
//Your code
});
The preventDefault() function prevents the window redirection to the action attribute of your form. (Default behavior)
Keeping code clean, reusable and simple.
This is the same function with cleaner code, you should try keeping your code easy to read so when you come back to it you understand everything perfectly.
const message = (text) =>{
document.querySelector("#msg").innerText = text; //The message div
};
document.querySelector("#file_select").addEventListener("submit",(event)=>{
event.preventDefault();
let fileValue = event.target.file.value; //The value of the file
if (fileValue != "") { //If value not empty
var xhttp = new XMLHttpRequest();
var filepath = (fileValue === "File1" ? "file1.txt" : (fileValue === "File2") ? "file2.txt" : "");
message("Filepath is: "+filepath);
xhttp.open("GET", filepath, true);
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
message.innerText = this.responseText;
} else {
message.innerText = "failed";
}
xhttp.send();
}
} else { //If input is empty
message("Invalid file.");
}
});
<form id="file_select">
<label for="file">File:</label>
<input type="text" name="file" id="file">
<button type="submit">Get</button>
</form>
<div id="msg"></div>
Note: You can use message("text") to output the result of your AJAX request. It's up to you how to fit this to your expected behavior. Hope this helps you.

function works but don't alert and reload

I wrote a small form to log-in into my website :
<form id="log_form" onsubmit='return loginjs()' method="post">
<input type='text' placeholder="login" size='30' name='login' class='test'/>
<input type='password' placeholder="password" name='password' size='30'/>
<input type='submit' value='Connect' id='signin' />
</form>
and I wrote this Javascript function to send the form's data to a php page which going to check if everything is ok and make the session up.
function loginjs() {
'use strict';
var form = document.getElementById('log_form');
var btn = document.getElementById('signin');
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if(request.readyState === XMLHttpRequest.DONE) {
if(request.status === 200) {
if (request.responseText != 'ok')
alert(request.responseText);
}
}
}
var post = "login=" + form.login.value + "&password=" + form.password.value;
request.open('POST', 'functions/func_login.php');
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(post);
location.reload();
};
My function is perfectly called each time I press ENTER or click on Submit, but sometimes the alert doesn't show up and the location.reload(); aren't called.
I don't have any error in my console... and if I manually reload the page, i'm logged so my ajax was sent.
I'm looking for 2 days to find the bug, and doesn't succeed to find. Could someone help me?
I can't use jQuery or another library I've to use JS Vanilla :)
Thank you
Try moving the location.reload(); code in the success block of the ajax, i.e. reload the page after the ajax response is received (if no error is received).

ReferenceError Cannot find variable createXMLHTTPRequestObject

I have a simple input box with a submit button which, when clicked, makes an XHR request to a server-side PHP for some information. In its simplest form, the markup looks like this:
<input type="text" id="word" class="form-control input-lg lookup-field" placeholder="Enter a Spanish or English word" oninput="deleteicon();" required>
<button class="btn btn-lg btn-brown lookup-submit" type="submit" id="lookup">Lookup</button>
The button's onclick event triggers a function that performs the XHR request:
$('#lookup').click(function(){ testlookup($('#word').val()); return(false); });
The testlookup() function is as below:
function testlookup(lookupword){
var mean = document.getElementById('meaning');
var waittext = '<div id="loading text-center"><i class="fa fa-4x fa-spinner fa-spin"></i></div>';
var hr = createXMLHTTPRequestObject();
var url = '/assets/engines/dictengine.php';
var vars = "lookup_word=" + lookupword;
document.getElementById('word').value = lookupword;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function(){
if(hr.readyState == 4 && hr.status == 200){
var return_data = hr.responseText;
mean.innerHTML = return_data;
else if(hr.status == 500){ mean.innerHTML = "Something went wrong! Please try again later..."; }
}
hr.send(vars);
mean.innerHTML = waittext;
}
I fail to see why this should ever refuse to work and would really appreciate some help seeing the issue. Every time I enter a value in the input box and click the button, the console briefly flashes a "Can't find variable createXMLHTTPRequestObject" error before the browser proceeds to refresh the page with a "?" appended to the URL. What could be the issue here and also why is the "?" getting appended to the URL if I have duly terminated my onclick function with a return(false) statement?
The code is implemented at peppyburro.com/test-dictionary.
You are trying to call a function named createXMLHTTPRequestObject, but it doesn't exist. The JS throws an exception and never reaches the return (false) statement.

how to call External URL as getJSON when i submit Form Button

Please help I tried everything cant get this simple code running
this is my html
HTML form:
<form id="searchForm" method="GET" action="" class="hpi check">
<label for="licencePlate" title="Enter vehicle registration"> </label>
<input id="licencePlate" maxlength="9" name="licencePlate" type="text" value="mt09nks" />
<button class="btn btn-primary" type="submit" id="searchButton">Click to Check</button>
</form>
Java script:
If u put the Json code in document.ready function it works fine and return the data on page refresh. but when i try to call it on a button click it does not return anything.
var getJSON = function(url) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
resolve(xhr.response);
} else {
reject(status);
}
};
xhr.send();
});
};
$('#searchButton').click(function(event) {
getJSON('https://dvlasearch.appspot.com/DvlaSearch?licencePlate=mt09cna&apikey=DvlaSearchDemoAccount').then(function(json) {
alert('Your Json result is: ' + json.make);
result.innerText = json.make; // display
}, function(status) { //error detection....
alert('Something went wrong.');
});
});
The above javascript works fine when I run it in document.ready but when i use to call it with button click even it gives alert message - Something went wrong.
I m just using a demo from DVLA to get the details. Which i will use it display.
A user will input the vehicle registration number and search the car details.
but for example only mt09nks will work. plz guide me where I am making mistake.
Thanks in Advance.
The above code I found in Stackoverflow and it works fine when called directly but doesnt work when i call after i click a button.
Please check where I am making mistake.
$.getJSON
should be
getJSON(
I think you want to call the method that you have created right ?
You seem to be calling the method that is provided by jQuery

Javascript image upload (Non framework)

I'd like to upload image(s) via JavaScript (Non framework). Does anyone have a basic example of how to this?
I get this error message:
Warning: Missing boundary in multipart/form-data POST data in Unknown on line 0 Array ( )
Here is what I'm working with so far.
<form action="" method="" enctype="" id="uploadImage">
<input type="file" name="image1" id="image1" value="" >
<input type="button" id="submit_button" data-data_enctype="multipart/form-data" data-form_name="uploadImage" data-url="/gallery/images/upload/" data-change_div="getForm" value="Upload" onclick="image(this.id, form.id)"/>
</form>
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var datVar = document.getElementById(id);
var url = datVar.dataset.url;
var change_div = datVar.dataset.change_div;
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById(change_div).innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-type", "multipart/form-data");
xmlhttp.send('NULL');
You need to pass the data that you want to send to the xmlhttp.send() method. Currently you are passing it 'NULL' so it complains that the data is missing.
Something like
var data = document.getElementById('#uploadImage');
gets the form.
create a FormData object (FormData is only supported in modern browsers)
var formData = new FormData(data);
and then passing formData to the send method should do.

Categories