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.
Related
I created a modal form (that pops up upon a link click, i.e trigger()). This is the HTML code:
<div class="modalbg">
<div class="modalPopup">
<form action="samepage.php" class="formContainer" method="post">
<h2>Change Desk Number</h2>
<label for="studentid">
<strong></strong>
</label>
<input type="password" placeholder="Your KEY" name="studentid" required/>
<label id="status" style="color:red;"></label>
<button type="submit" class="btn" onclick="return verify()">Upgrade</button>
<button type="button" class="btn cancel" onclick="closeForm()">Close</button>
</form>
</div>
</div>
The JavaScript that controls this modal is:
function trigger(){
document.getElementById("modalPopup").style.display = "block";
}
function closeForm() {
document.getElementById("modalPopup").style.display = "none";
}
function verify() {
var studentid = document.getElementById("studentid").value;
if (studentid != dbstudentid || !studentid){
document.getElementById("status").innerHTML="Invalid Student ID!";
function trigger(event) { event.preventDefault(); }
return false;
}
else{
document.getElementById("modalPopup").submit();
}
}
Everything works at this point (i.e it pops up whenever I click the link and whenever I knowingly try to enter a wrong studentid, it returns the "Invalid student ID" on the "status" label. (Note: I had already saved the session's student ID in the variable dbstudentid using:
var dbstudentid = <?php echo json_encode($dbstudenid);?>;
My problem however comes from when I try to execute the PHP on the same page.
Whenever I insert the PHP code into the modalbg div or modalPopup div inside it, the entire modal refuses to pop, let alone submit.
This is the PHP code I used (it should be noted that at the beginning of the page, I had already used include(configure-db.php) and session_start() ) :
<?php
if(isset($_POST['studentid'])){
$studentid = $_POST['studentid'];
$desk = 1;
$deskstatus ="";
$select = "UPDATE users SET deskNo = '$desk' WHERE name='$SESSION';
}
if (mysqli_query($MyConn, $select)) {
$deskstatus = "Desk changed successfully!";
} else {
$deskstatus = "Error";
} return $deskstatus;
?>
I have tried everything, the modal just refuses to come every time, let alone successfully make the Desk Update on my Database. to make things worse, whenever I refresh the page, the modal which I set to display:none; by default on CSS suddenly starts showing. But whenever I remove the PHP code, it returns to normal.
Do I need to make the action execute in a separate page? If yes, please how?
Else, how please?
I world highly suggest you think about using AJAX to handle this probolem.
let's clear up things.
you can write var dbstudentid = '<?= $dbstudenid ?>'; instead of var dbstudentid = <?php echo json_encode($dbstudenid);?>; this will give you freedom of JS native datatype.
you need to send this form request through ajax and recive output there.
Change the php code else part to like this
else { $deskstatus = "Error: " . mysqli_error($MyConn); }
Now when there is a actual problem on code you will know what was the problem. and it will not break you interface.
4. Create seperate file that handle this form request.
5. Here is code snippet of plaing JS AJAX implementation
let post = JSON.stringify(postObj)
const url = "https://jsonplaceholder.typicode.com/posts"
let xhr = new XMLHttpRequest()
xhr.open('POST', url, true)
xhr.setRequestHeader('Content-type', 'application/json; charset=UTF-8')
xhr.send(post);
xhr.onload = function () {
if(xhr.status === 201) {
console.log("Post successfully created!");
let AlertDiv = document.querySelector('#alert');
AlertDiv.innerHTML = xhr.response;
}
}
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>
I've ran into an weird problem. I have created a login page which send data to a PHP page which return some response code like "00000" for ok "404" for not found etc. I have tested my server with Postman tool and found server is working perfectly fine. When my html send data to server server responds with response code. If the response code comes wrong html alert's it. However if I enter correct credentials and when server respond with success , My login page reloads for no reason.
Here's my javascript
function validatelog(){
var user_email_log=document.getElementById("user_email_log").value;
var user_pass_log=document.getElementById("user_pass_log").value;
if (user_email_log&&user_pass_log!=null)
{
var hr = new XMLHttpRequest();
var url = "../logic/login.php";
var vars =
"user_email_log="+user_email_log+"&user_pass_log="+user_pass_log;
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 saman = hr.responseText.trim();
if(saman=="00000"){
alert(saman);
}else if (saman == "404"){
alert("Failed with 404");
}
else{
alert(saman);
}
}
}
hr.send(vars);
}
}
And my html looks like this
<input id="user_email_log"/>
<input id="user_pass_log"/>
<button onclick="validatelog();">Log in</button>
Add type="button" to the button:
<button type="button" onclick="validatelog();">Log in</button>
When it is not specified, it is the same as type="submit", and this will cause your page to reload.
if you use jquery you could do this.
$(document).on('click', 'button', function(e) {
e.preventDefault();
$.get('url')
})
I think the page is reloading because that is the default behavior.
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).
I have 3 files linked together index.php functions.js and compute.php
index.php has a div that calls a function in functions.js: compute() that sends an AJAX request to do something in compute.php
index.php:
<form id = "input_form">
<textarea name = "row" id = "inputform" placeholder="Input row here"></textarea>
<input type = "submit" value = "Enter" onclick="compute(inputform.value);">
</form>
<div id = "output_container">
<p id = "output"></p>
</div>
When the button is pressed, compute() is called passing in whatever was in the textarea as data.
function compute(row){
var xhttp;
if(window.XMLHttpRequest){
xhttp = new XMLHttpRequest();
}
else{
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4) {
output.innerHTML = xhttp.responseText;
}
};
xhttp.open("GET","compute.php?row="+row,true);
xhttp.send(null);
}
This passes the value into a php script which simply is suppose to output what was in the textarea into #output
<?php
$str = $_GET['row'];
echo $str;
?>
When I test my program by clicking the button, nothing happens indicating something went wrong. I tried to pinpoint the problem by adding a window.alert('something'); after the check if(xhttp.readyState == 4) but a popup box never appears, making it seem like the issue is between functions and compute.
I tested out phpinfo(); and it looks like php is working properly on my server as well
Problem: Form is getting submitted without making ajax call, because your code contains type='submit'
Solution: Change type to button:
<input type = "button" value = "Enter" onclick="compute(inputform.value);">
Also update code to fetch the output properly:
if (xhttp.readyState == 4) {
document.getElementById("output").innerHTML = xhttp.responseText;
}