I have a simple login page that sends the login information to the servlet, and in response receives one parameter which is interpreted in jQuery.
Data is sent correctly, goes to the servlet which also sets the parameter correctly (I can see that in the Firebug in the response header).
The problem is when I want to retrieve data from the returned response and assign it to a JavaScript variable. The request object is empty, while in Chrome inspect I see an alert:
Uncaught TypeError: Object has no method 'getResponseHeader'.
When I display it using console.log () does not return anything to me, no value.
<!DOCTYPE html>
<html lang="en">
<head>
<%#page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<link rel="shortcut icon" href="../../assets/ico/favicon.png">
<link
href="http://minikomi.github.io/Bootstrap-Form-Builder/assets/css/lib/bootstrap.min.css"
rel="stylesheet">
<link
href="http://minikomi.github.io/Bootstrap-Form-Builder/assets/css/lib/bootstrap-responsive.min.css"
rel="stylesheet">
<link
href="http://minikomi.github.io/Bootstrap-Form-Builder/assets/css/custom.css"
rel="stylesheet">
<script src="http://code.jquery.com/jquery-2.0.3.js"></script>
<script src="../js/jquery.validate.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Logowanie</title>
<!-- Bootstrap core CSS -->
<link href="../css/bootstrap.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="../css/signin.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="../../assets/js/html5shiv.js"></script>
<script src="../../assets/js/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<form class="form-signin" action="Login" method="post">
<h2 class="form-signin-heading">Logowanie</h2>
<input type="email" name="email" class="form-control" id="email"
placeholder="Adres email" autofocus>
<input type="password" id="password"
name="password" class="form-control" placeholder="Haslo">
</form>
<button id="zaloguj" value="zaloguj" class="btn btn-success btn-large">
<i class="icon-white icon-th-list"></i>Zaloguj
</button>
</div>
<!-- /container -->
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script type="text/javascript">
$('#zaloguj').click(function() {
var email = $("#email").val();
var password = $("#password").val();
console.log(email+password);
var data = "email=" + email + "&password=" + password;
$.ajax({
url : "Login",
type : "POST",
data : data,
success : function(request) {
console.log(request);
var log = request.getResponseHeader("log");
console.log(log);
if (log == 1) {
$( ":header" ).after("Poprawne logowanie").css({ background: "#ccc", color: "green" });
document.location.href = '/landing.html';
} else {
$( ":header" ).after("Błędne logowanie").css({ background: "#ccc", color: "red" });
}
},
});
});
</script>
</body>
</html>
Looks like your using the wrong overload for success.
success : function(request) {
console.log(request);
var log = request.getResponseHeader("log");
should be:
success : function(data, status, xhr) {
console.log(data);
var log = xhr.getResponseHeader("log");
See the docs
success Type: Function( PlainObject data, String textStatus, jqXHR
jqXHR )
Then
The jqXHR Object
The jQuery XMLHttpRequest (jqXHR) object returned by $.ajax() as of
jQuery 1.5 is a superset of the browser's native XMLHttpRequest
object. For example, it contains responseText and responseXML
properties, as well as a getResponseHeader() method.
The success function returns ( PlainObject data, String textStatus, jqXHR jqXHR ). What you are looking for is the last parameter and not the response itself.
success: function(request, status, xhr) {
console.log(xhr.getResponseHeader("log"));
}
Related
I have an html form from which I need to collect data and call a POST on a rest api. I am trying to do this using javascript and $.ajax but confused on how to setup the URL and collect data as I am very new to it. Could someone explain this fully, with an example if possible as I'm having trouble finding detailed documentation.
Try this:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<input type="text" value="3" name="id" id="GetId">
<button id="LoginBtn">login</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
<script>
$("#LoginBtn").click(function (e){
e.preventDefault();
var settings = {
"url": "http://192.168.1.3:8071/user/login",
"method": "POST",
"headers": {
"Content-Type": "application/json"
},
"data": JSON.stringify({"username":"user","password":"123456"}),
};
$.ajax({
...settings,
success: function (result) {
alert("success")
},
error : function (){
alert("error")
}
})
})
</script>
</body>
</html>
Please read this simple article
https://javascript.info/fetch
You could use axios or jquery but fetch api is really simple
This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 3 years ago.
I am completely new to JavaScript, and I can't figure out why I'm getting this error: Uncaught TypeError: Cannot read property 'addEventListener' of null.
I followed the advice posted in response to a similar question and put the file containing my JavaScript in the bottom of my body, but that didn't fix it. I also tried making the button onclick=checkValidity(), but that didn't work either.
document.getElementById("loginButton").addEventListener("click",
checkValidity);
function checkValidity() {
var usrName = document.getElementById("inputUsername").value;
var usrPswd = document.getElementById("inputPswrd").value;
if(usrName == "admin" && usrPswd == "123"){
window.open("HtmlPage2.html");
}
else {
alert("Your username and password are incorrect.");
}
}
and the HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<title>Document</title>
</head>
<body>
<div class=wrap>
<input type="text" id="inputUsername">
<p>Username</p>
<input type="password" id="inputPswrd">
<p>Password</p>
<button id="loginButton">Log in</button>
<p id="login"></p>
</div>
<script type="text/javascript" src="Script.js" async></script>
</body>
</html>
What I want the code to do is check whether the input in the inputUsername and inputPswrd match that specified in the if...else function, and if so, open a new window; otherwise alert an error message.
EDIT: If I move all the code above to the top of my JS file, it will work as intended and open a new window, but then the code for that new page won't run (but the new page code does run it's at the top of my JS file). The error message I get when the new window opens is line 1: Uncaught TypeError: Cannot read property 'value' of null at Script.js:1.
Additional code:
JS for HTML page 2:
document.getElementById("greeting").innerHTML="Welcome";
document.getElementById("productButtonOne").addEventListener("click",
addToCart);
document.getElementById("productButtonTwo").addEventListener("click",
addToCart);
document.getElementById("productButtonThree").addEventListener("click",
addToCart);
var clicks = 0;
function addToCart() {
clicks = clicks + 1;
document.getElementById("cartProductsTotal").innerHTML = "You have " +
clicks + " items in your shopping cart.";
}
Beginning of HTML for page 2:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<title>Document</title>
</head>
<body>
<div class=wrap>
<h1 id="greeting"></h1>
<div id="productOne" class="cartItem">
<button id="productButtonOne" class="cartItems">Add to cart</button>
<img src="monaLisa.jpg" id="monaLisaImage">
<h2 class="productDescriptions">Mona Lisa</h2>
<p>This painting is great.</p>
<span class=price>This item costs $10.</span>
</div>
Place the scirpt tag after body it will work
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<title>Document</title>
</head>
<body>
<div class=wrap>
<input type="text" id="inputUsername">
<p>Username</p>
<input type="password" id="inputPswrd">
<p>Password</p>
<button id="loginButton">Log in</button>
<p id="login"></p>
</div>
<script type="text/javascript" src="Script.js" async></script>
</body>
<script>
document.getElementById("loginButton").addEventListener("click", checkValidity);
function checkValidity() {
var usrName = document.getElementById("inputUsername").value;
var usrPswd = document.getElementById("inputPswrd").value;
if(usrName == "admin" && usrPswd == "123"){
window.open("HtmlPage2.html");
}
else {
alert("Your username and password are incorrect.");
}
}
</script>
</html>
remove this line <script type="text/javascript" src="Script.js" async></script>, I think your code loads the wrong script.
HTML
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://fonts.googleapis.com/css?family=Lobster" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Rokkitt" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" media="screen" href="styles1.css" />
<script src="api.js"></script>
</head>
<body background="texture.jpg" class="bg">
<div class="container">
<h1> Awesome Quotes</h1>
<p>Your daily dose of wisdom.</p>
<div class="dynamic">
<button class="btn btn-primary" id="button" type="submit">Get a New Quote</button>
</div>
<div class="quote"></div>
<a href="https://twitter.com/intent/tweet?hashtags=quotes" target="_blank">
<i class="fa fa-twitter"></i></a>
</div>
</body>
</html>
JS
$.getJSON("http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=", function(a) {
$(".quote").append(a[0].content + "<p>— " + a[0].title + "</p>")
});
these are my HTML and JS.what I'm trying to do is generate a random quote inside a div.I called an API for that.Every time I reload the page a random quote comes up.What I need to do is click the "Get a New Quote" button and get a quote without reloading the page using jquery.Plus I need to click the twitter icon to take me to twitter where i see the relevant quote already in the editor just to post.
HTML
Give your button a class so you can easily access it
<button class="btn btn-primary getnewquote" id="button" type="submit">Get a New Quote</button>
Script
var Res;
$('.getnewquote').click(function(){
//your ajax call
$.ajax({
type: "POST",
url: "Your web service url",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (json) {
Res = JSON.parse(json.d);
$(".quote").append(Res[0].content + "<p>— " + Res[0].title + "</p>")
},
failure: function (msg) {
console.log(msg);
}
});
});
I'm trying to follow this example: http://easyautocomplete.com/example/ajax-get to create an input field that will autocomplete hints from API.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Autocomplete - Remote datasource</title>
<head>
<!-- Easy Autocomplete -->
<link rel="stylesheet" href="/plugins/easy-autocomplete/dist/easy-autocomplete.min.css">
<link rel="stylesheet" href="/plugins/easy-autocomplete/dist/easy-autocomplete.themes.min.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<!-- Easy Autocomplete -->
<script src="/plugins/easy-autocomplete/dist/jquery.easy-autocomplete.min.js"></script>
<script>
var options = {
url: "http://localhost:8081/api/customers",
getValue: "name",
template: {
type: "description",
fields: {
description: "email"
}
}
};
$(document).ready(function () {
console.log("ready");
$("#example-ajax-post").easyAutocomplete(options);
});
</script>
</head>
<body>
<input id="example-ajax-post" />
</body>
</html>
In my API response, I can see all my returned values (26 in total) however my input displaying only first 6 hints, even if I try to enter some data that's in my response I can only see the first 6 loaded fields each time.
API Return
Input hint
Am I missing something?
Default value for parameter maxNumberOfElements is 6.
you can increase this by adding this to your options
list: {
maxNumberOfElements: 10,
match: {
enabled: true
}
}
Docs
http://easyautocomplete.com/guide#sec-maxsize
Right now I am just trying to get the API call to work, nothing fancy. In the end I will only want some basic info like name, runtime, rating and description... but that is all later. I can't even get the API call to work.
I have done several tutorials and I seem to be missing something.
HTML
<head>
<title>Watch a movie!</title>
<meta charset = "UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<meta name="description" content="">
<meta name="keywords" content="">
<link href="css/bootstrap.css" rel="stylesheet" type="text/css">
<link href="css/style.css" rel="stylesheet" type="text/css">
<script src="js/angular.min.js"></script>
<script src="http://code.angularjs.org/1.2.0rc1/angular-route.min.js"></script>
<script src="controllers/movies.js"></script>
</head>
<body>
<div id="wrapper">
<button type="button" class="btn btn-primary btn-lg btn-block">NOW PLAYING</button>
<button type="button" class="btn btn-default btn-lg btn-block">COMING FRIDAY</button>
<!-- PLACEHOLDER -->
<div id="movieInfoBox">
<div ng-controller = "movieController">{{movies}}</div>
</div>
</div> <!-- END WRAPPER -->
JS
var movies = angular.module("movies", []); //quotes are name of this file
movies.controller("movieController", function ($scope, $http){ //quotes are name of function called in index
$http.jsonp("http://api.rottentomatoes.com/api/public/v1.0/movies/155655062.json?apikey=wq98h8vn4nfnuc3rt2293vru")
.sucess(function(data)
{$scope.movies = data;})
.error(function(data){});
});
You have to include the JSON_CALLBACK in the URL. Otherwise the API returns JSON instead of JSONP. In the code below I use a config object instead of the parameters directly in the query string. It's just because it's easier to read, you can also use your version and add &callback=JSON_CALLBACK to the URL. See 'jsonp' in the docs
Working Fiddle: http://jsfiddle.net/pascalockert/fM7jb/
Code in the controller:
$http.jsonp('http://api.rottentomatoes.com/api/public/v1.0/movies/155655062.json', {
params: {
apikey: 'wq98h8vn4nfnuc3rt2293vru',
callback: 'JSON_CALLBACK'
}
})
.success(function (data) {
$scope.movies = data;
});