function works but don't alert and reload - javascript

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).

Related

Webpage reloading on entering correct values

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.

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

Ajax acting as GET method even though is POST method

Hello I have encountered a problem while coding in Javascript and PHP (Ajax non jquery). I am trying to upload a file over Ajax, and handle it in PHP.
This is my code:
index.html
<html>
<head>
<title>PHP AJAX Upload</title>
<script type="text/javascript">
function upload() {
// 1. Create XHR instance - Start
var dat= "bla";
document.getElementById("div2").innerHTML = "working";
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
else {
throw new Error("Ajax is not supported by this browser");
}
var rad = document.getElementById('fajl');
var filee = rad.files[0];
var formData = new FormData();
formData.append('rad',filee)
formData.append('var',dat)
xhr.open('POST', 'upload.php');
xhr.send(formData);
xhr.onload = function () {
if (xhr.readyState === 4 && xhr.status == 200) {
document.getElementById("div2").innerHTML = xhr.responseText;
//alert(xhr.readyState);
//alert(xhr.status);
}
}
}
</script>
</head>
<body>
<form id="uploadForm" enctype="multipart/form-data">
<label>Upload File:</label><br/>
<input name="rad" id="fajl" type="file" class="inputFile" />
<input type="submit" value="Submit" class="btnSubmit" onclick="upload()" />
<div id="div2">
</div>
</form>
</body>
</html>
upload.php
<?php
if(is_array($_FILES)) {
if(is_uploaded_file($_FILES['rad']['tmp_name'])) {
$sourcePath = $_FILES['rad']['tmp_name'];
$targetPath = "images/".$_FILES['rad']['name'];
if(move_uploaded_file($sourcePath,$targetPath)) {
echo ("uspjeh<br>");
}}
}
$podatak=$_POST['var'];
echo "$podatak"
?>
Problem is that I dont see PHP script response in my div2 element. Ajax behaves wierd and it puzzles me. I have put JavaScript alert command under xhr.readyState condition (now commented). When I do that then I see the output, but when I close alert dialog, the browser automaticly reloads page and makes the URL like i'm using GET method (i'm using POST) and then server output dissapears. (rad in ?rad=... is the name of my input element)
When I'm not using alert command then I don't see output at all, because page redirects really fast. What am I misiing?
It's because you are using a submit button and that's submitting the form. By default form methods are GET requests. Change to just a button instead:
<input type="button" value="Submit" class="btnSubmit" onclick="upload()" />
The default form action (submitting) is being carried out.
To stop this add return false to your click handler:
onclick="upload(); return false;"

Problems with XMLHttpRequest and PHP

I'm fairly new to both JavaScript and PHP, so I hope this problem isn't as complex as it seems to me. I'm trying to send data from a form to a PHP file using XMLHttpRequest, and then display the output of the PHP as an alert. Here's the HTML and JavaScript:
<form onSubmit="password_Check()">
<input type="password" size="40" name="password" id="pass">
<input type="submit" value="Go">
</form>
<script type="text/javascript">
function password_Check() {
var url = "test.php";
var pass = $("#pass").val();
var xhr = new XMLHttpRequest();
xhr.open("GET", url+"?pass="+pass, true);
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
}
}
</script>
And here's the PHP:
<?php
$pass = $_GET["pass"];
echo "The password is $pass! We've done it!";
?>
I've tried all sorts of ways to do this, like $.post, $.get, $.ajax, and an xhr using POST. But I can't seem to get this to work. Now it just appends "?password=(whatever I put)" onto the end of the current url, which does nothing, but it shows it's doing something.
In your code you are missing the send part where you actually trigger the request. If you are not triggering the request then there is no point of the event listeners which listen for the state changes.
do it like
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
}
xhr.send();
Also in your question you are mentioning about jquery ajax, with $.get your code could be as simple as
$("#form1").on("submit",function(e){
e.preventDefault();
var url = "test.php?pass=" + $("#pass").val();
$.get(url,function(data){
//handle data here
});
});
You forgot to execute the request. xhr.send():
Also note that since you're having an XMLHTTPRequest, you need to prevent the default behavior (which is the form is going to be submitted) by using .preventDefault();
<form id="form1">
<input type="password" size="40" name="password" id="pass">
<input type="submit" value="Go">
</form>
<script type="text/javascript">
// handle the submission event
document.getElementById('form1').addEventListener('submit', function(e){
e.preventDefault(); // prevent from submitting
var url = "test.php";
var pass = document.getElementById('pass').value; // be faithful!, just use plain javascript
var xhr = new XMLHttpRequest();
var params = '?pass='+pass;
xhr.open("GET", url+params, true);
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
}
xhr.send(); // send it
});
</script>
If you are using jQuery then better use jQuery's ajax functions instead of xhr by yourself!
Also if you are submitting the password, better not submit it using GET request as it will be visible in the URL. Instead always use POST when handling Passwords!
Client side:
<form action="/index.php" id="myform" method="post">
<input type="password" size="40" name="password" id="pass">
<input type="submit" value="Go">
</form>
<script type="text/javascript">
$('#myform').on('submit', function() {
$.ajax({
type: $(this).attr('method'), //Taking for the form attribute
url: $(this).attr('action'),
data: $(this).serialize(), //Takes care of all input fields in the form! No need to pass one by one!
success: function(response) {
if(response == 'success') {
window.location.href = '/url-to-goto'; //Set your redirect url here
}
else {
//Handle invalid password here
alert(response);
}
}
});
return false;
});
</script>
Server side:
<?php
//If you are handling password, better to put it in the post body instead of url for security reasons
if($_SERVER['REQUEST_METHOD'] == 'POST') {
//Check password here
if(isset($_POST['password']) && $_POST['password'] == '123') {
die('success'); //successful! redirect user!
}
die('Invalid password!');
}
?>
Hope that helps you better understand!

Categories