So after I start my server, go to my local host, and either click the sign up or login button, I get an error popping up in my console saying
"Uncaught ReferenceError: Handlebars is not defined" I don't know what exactly the issue is. I tried re- npm installing it because maybe I didn't have it installed. The error that immediately pops up in the console before I actually click the buttons is this:
http://s23.postimg.org/bgbykf3qh/Screen_Shot_2015_12_16_at_10_02_14_AM.png
I also thought maybe it was because I put the script in the wrong section of my HTML file. However, I keep getting the same error.
Here is what my index.html file looks like.
<html>
<head>
<title>Wishes Project</title>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.css">
<link rel="stylesheet" type="text/css" href="style.css">
<link href='https://fonts.googleapis.com/css?family=Anton' rel='stylesheet' type='text/css'>
</head>
<body>
<h1>Wish List</h1>
<button id="sign-up">Sign Up</button><br>
<button id="login">Log In</button><br>
<template id="status-template">
<h3 id="status"></h3>
</template>
<div id="form-container"></div>
<!-- LOGIN ===================== -->
<template id="login-template">
<div id="login-container" data-id="{{_id}}">
<input type="text" id="username" placeholder="username"/><br>
<input type="text" id="password" placeholder="password"/><br>
<button id="login-button" data-id="{{_id}}">Log In!</button>
</div>
</template>
<!-- NEW USER ===================== -->
<template id="signup-template">
<div id="signup-container" data-id="{{_id}}">
<input type-"text" id="username" placeholder="username"/></br>
<input type="text" id="password" placeholder="password"/></br>
<input type="text" data-id="{{_id}}">Register!</button>
</div>
</template>
<!-- NEW WISH ======================= -->
<template id="new-wish-template">
<div id="new_wish-container" data-id="{{_id}}">
<input type="text" id="wish" placeholder="make a wish"/><br>
<button id="make-wish" data-id="{{_id}}">Create Wish!</button>
</div>
</template>
<button id="logout">Logout</button>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0 4/handlebars.js"></script>
<script src="app.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-cookie/2.0.4/js.cookie.js"></script>
</body>
</html>
Here is what my app.js file looks like.
console.log('app.js');
$(function() {
$('#sign-up').click(signUpForm);
$('#login').click(loginForm);
$('#logout').click(delCookie).hide();
if( Cookies.get('loggedinId') != undefined ) {
wishForm();
};
});
var formContainer = $('#form-container');
//LOGIN ==============================
var loginForm = function() {
console.log('showing login form');
$('#sign-up').hide();
$('#login').hide();
var template = Handlebars.compile($('#login-template').html());
formContainer.append(template);
$('#login-button').click(function() {
console.log('clicked');
loginPost()
});
};
var loginPost = function() {
user = {
username: $('#username').val(),
password: $('#password').val(),
};
$.ajax({
url: 'http://localhost:3000/login',
method: "POST",
dataType: 'json',
data: user
}).done(function(data) {
console.log(data.username+"login successful");
user = Cookies.get("loggedinId");
wishForm()
});
};
//LOG OUT =========================
var delCookie = function() {
Cookies.remove('loggedinId');
loginForm();
};
//NEW USER =========================
var signUpForm = function() {
console.log('showing sign up form');
$('#sign-up').hide();
var template = Handlebars.compile($('#signup-template').html());
formContainer.append(template);
$('#register').click(function(){
console.log('clicked register');
newUser();
});
};
var newUser = function() {
user = {
username: $('#username').val(),
password: $('#password').val(),
};
console.log(user);
$.ajax({
url: "http://localhost:3000/users",
method: "POST",
data: user
}).done(function(data){
wishForm();
});
user = Cookies.get(user.username);
};
var wishForm = function() {
console.log('showing wish form');
$('#sign-up').hide();
$('#login').hide();
$('#logout').show();
formContainer.empty();
var template = Handlebars.compile($('#new-wish-template').html());
formContainer.append(template);
$('#make-wish').click(function() {
console.log('clicked make wish');
newWish();
});
};
var newWish = function() {
console.log('showing wish form');
var wish = {
content: $('#wish').
Can anybody help? Thank you.
Typo.
Try:
https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.4/handlebars.js
Instead of:
https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0 4/handlebars.js
You are loading .js which path is error 404. Do:
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.5/handlebars.min.js"></script>
<script src="app.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-cookie/2.0.4/js.cookie.js"></script>
More information about Handlebars CDN
Related
I am having this issue with my home button not adding headers in a get request. I have stored a token inside of the localStorage and I send it in the headers when I make a get request to Controller: Home Action: Index. From what I see, it doesn't use my jquery and goes straight to the Account/Index.
Initially, I though it was a problem with the javascript not binding to a button click. After further investigation, I found that the Console.log() I have in _Layout.cshtml do not work and neither does the button. This leads me to believe there is a problem with $("html").html(response); in the Login.js file.
The correct flow is LoginPage -> Login.js (grabs data and uses Ajax for a post request.) -> Returns a html page composing of _Layout.cshtml and /Views/Home/Index.cshtml
Below is my code for the file "Views/Shared/_Layout.cshtml":
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>#ViewData["Title"] - Chat </title>
<environment include="Development">
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
<link rel="stylesheet" href="~/css/site.css" />
</environment>
<environment exclude="Development">
<link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/css/bootstrap.min.css"
asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"
asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute" />
<link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" />
</environment>
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li id="li_btnHome"><a asp-area="" asp-controller="" asp-action="">Home</a></li>
</ul>
</div>
</div>
</nav>
<div class="container body-content">
#RenderBody()
<hr />
<footer>
<p>© 2018 - Chat</p>
</footer>
</div>
<environment include="Development">
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
<script type="text/javascript">
console.log("Development");
</script>
</environment>
<environment exclude="Development">
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.3.1.min.js"
asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
asp-fallback-test="window.jQuery"
crossorigin="anonymous"
integrity="sha384-tsQFqpEReu7ZLhBV2VZlAu7zcOV+rXbYlF2cqB8txI/8aZajjp4Bqd+V6D5IgvKT">
</script>
<script src="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/bootstrap.min.js"
asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.min.js"
asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal"
crossorigin="anonymous"
integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa">
</script>
<script src="~/js/site.min.js" asp-append-version="true"></script>
<script type="text/javascript">
console.log("Not Development");
</script>
</environment>
<script type="text/javascript">
console.log("Hello World");
</script>
<!--<script src="~/js/NavBarFunction.js"></script>-->
#RenderSection("Scripts", required: false)
</body>
</html>
Here's the javascript file "wwwroot/js/NavBarFunctions.js":
$("#li_btnHome a")[0].onclick = function (event) {
event.preventDefault();
alert("called click");
var tokenObj = localStorage.getItem("token");
var tokenStr = tokenObj == null ? "what_about_tokenObj_is_null?" : tokenObj.toString();
$.ajax({
type: 'GET',
contentType: 'application/json; charset=utf-8;',
url: '#Url.Action("Index", "Home")',
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", tokenStr);
},
success: function (response) {
alert(1);
$("html").html(response);
}
});
return false;
};
Here's the HomeController, located in "Controllers/HomeController":
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Chat.Enums;
using Chat.Identity;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
namespace _Chat.Controllers
{
public class HomeController : Controller
{
private AuthenticateUser authenticateUser = new AuthenticateUser();
public async Task<IActionResult> Index()
{
var request = Request;
var headers = request.Headers;
StringValues token;
if (headers.TryGetValue("Authorization", out token))
{
var result = await this.authenticateUser.ValidateToken(token);
if (result.Result == AuthenticateResult.Success)
{
return View();
}
else
{
return RedirectToAction("Index", "Account");
}
}
return RedirectToAction("Index", "Account");
}
}
}
For some odd reason, it looks like after my page is redirected from log in to home, all scripts/javascript stop working.
Here's the code authenticating login. Located in "Controllers/AccountController":
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Chat.Models;
using Chat.DatabaseAccessObject;
using Chat.Identity;
using Chat.DatabaseAccessObject.CommandObjects;
using System.Linq.Expressions;
using System.Net.Mime;
using System.Security.Claims;
using System.Text;
using Microsoft.AspNetCore.Authentication;
using Microsoft.IdentityModel.Tokens;
namespace Chat.Controllers
{
public class AccountController : Controller
{
private const string SECRET_KEY = "CHATSECRETKEY";
public static SymmetricSecurityKey SIGNING_KEY = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(SECRET_KEY));
private ServerToStorageFacade serverToStorageFacade = new ServerToStorageFacade();
private AuthenticateUser authenticateUser = new AuthenticateUser();
public IActionResult Index()
{
return View();
}
// Post: /login/
[HttpPost]
public async Task<IActionResult> Login([FromBody]LoginModel loginModel)
{
if (ModelState.IsValid)
{
var mapLoginModelToUser = new MapLoginModelToUser();
var user = await mapLoginModelToUser.MapObject(loginModel);
// If login user with those credentials does not exist
if(user == null)
{
return BadRequest();
}
else
{
var result = await this.authenticateUser.Authenticate(user);
if(result.Result == Chat.Enums.AuthenticateResult.Success)
{
// SUCCESSFUL LOGIN
// Creating and storing cookies
var token = Json(new
{
data = this.GenerateToken(user.Email, user.PantherID),
redirectUrl = Url.Action("Index","Home"),
success = true
});
return Ok(token);
}
else
{
// Unsuccessful login
return Unauthorized();
}
}
}
return BadRequest();
}
private string GenerateToken(string email, string pantherId)
{
var claimsData = new[] { new Claim(ClaimTypes.Email, email), new Claim(ClaimTypes.Actor, pantherId) };
var signInCredentials = new SigningCredentials(SIGNING_KEY, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: "localhost",
audience: "localhost",
expires: DateTime.Now.AddDays(7),
claims: claimsData,
signingCredentials: signInCredentials
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public async Task<IActionResult> Error() => View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
public class MapLoginModelToUser
{
private ServerToStorageFacade serverToStorageFacade;
public MapLoginModelToUser()
{
serverToStorageFacade = new ServerToStorageFacade();
}
public async Task<User> MapObject(LoginModel loginModel)
{
Expression<Func<User, bool>> expression = x => x.Email == loginModel.inputEmail;
var user = await this.serverToStorageFacade.ReadObjectByExpression(new User(Guid.NewGuid()), expression);
if(user == default(Command))
{
return null;
}
return new User(user.ID)
{
Email = loginModel.inputEmail,
Password = loginModel.inputPassword,
FirstName = user.FirstName,
LastName = user.LastName,
PantherID = user.PantherID,
ClassDictionary = user.ClassDictionary,
UserEntitlement = user.UserEntitlement
};
}
}
}
Also the code that renders the page. Located in "wwwroot/js/Login.js":
$(document).ready(function () {
$("#formSubmit").submit(function (event) {
event.preventDefault();
var email = $("#inputEmail").val();
var password = $("#inputPassword").val();
var remember = $("#rememberMe").val();
var loginModel = {
inputEmail: email,
inputPassword: password,
rememberMe: remember
};
$.ajax({
type: 'POST',
url: 'Account/Login',
data: JSON.stringify(loginModel),
contentType: 'application/json; charset=utf-8;',
success: function (response) {
var token = response.value.data;
localStorage.setItem("token", token);
alert("You have successfully logged in.");
setHeader();
redirect(response.value.redirectUrl);
}
});
});
function setHeader() {
$.ajaxSetup({
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', localStorage.getItem("token"));
}
});
}
function redirect(redirectUrl) {
$.ajax({
type: 'GET',
contentType: 'application/json; charset=utf-8;',
url: redirectUrl,
success: function (response) {
$("html").html(response);
}
});
}
});
This is the error received after loading the new html page:
EDIT: This is what's sent in the response after the Home button is clicked.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Login - Chat FIU</title>
<link rel="stylesheet" href="/lib/bootstrap/dist/css/bootstrap.css" />
<link rel="stylesheet" href="/css/site.css" />
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li><a id="btnHome" href="/">Home</a></li>
</ul>
</div>
</div>
</nav>
<div class="container body-content">
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<link href="/css/signin.css" rel="stylesheet">
<script src="/lib/jquery/dist/jquery.js"></script>
<script src="/lib/bootstrap/dist/js/bootstrap.js"></script>
<script src="/js/Login.js"></script>
</head>
<body class="text-center">
<form id="formSubmit" method="post" class="form-signin">
<img class="mb-4" src="/images/FIU-Chat-Curved.png" alt="" width="150" height="150">
<h1 class="h3 mb-3 font-weight-normal">Please sign in</h1>
<label for="inputEmail" class="sr-only">Email address</label>
<input autofocus="" class="form-control" data-val="true" data-val-required="The Email field is required." id="inputEmail" name="inputEmail" placeholder="Email address" required="required" type="email" value="" />
<label for="inputPassword" class="sr-only">Password</label>
<input class="form-control" data-val="true" data-val-required="The Password field is required." id="inputPassword" name="inputPassword" placeholder="Password" required="required" type="password" />
<div class="checkbox mb-3">
<label>
<input data-val="true" data-val-required="The Remember field is required." id="rememberMe" name="rememberMe" type="checkbox" value="true" /> Remember me
</label>
</div>
<button id="btnLogin" class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
<p class="mt-5 mb-3 text-muted">© 2017-2018</p>
<input name="__RequestVerificationToken" type="hidden" value="CfDJ8Ah5tOyN_3lPrH0DgSEU8vD7Q7JItdizW-mYDc5uamCO3oRTBN-pdo9ZyPgRaHRyovwEGfT5Qhw0UD-rfbIHUJPt4FgUOhM1OkAWC9AtAfPEKkxz7TBfwKfz0EpfxF4DX2DAczujogr__xnIr3vDq3o" /><input name="rememberMe" type="hidden" value="false" /></form>
</body>
</html>
<hr />
<footer>
<p>© 2018 - Chat FIU</p>
</footer>
</div>
<script src="/lib/jquery/dist/jquery.js"></script>
<script src="/lib/bootstrap/dist/js/bootstrap.js"></script>
<script src="/js/site.js?v=BxFAw9RUJ1E4NycpKEjCNDeoSvr4RPHixdBq5wDnkeY"></script>
<script type="text/javascript">
</script>
<script type="text/javascript">
</script>
<script src="/js/NavBarFunction.js"></script>
</body>
The key to solve the problem is in your flow described here:
The correct flow is LoginPage -> Login.js (grabs data and uses Ajax
for a post request.) -> Returns a html page composing of
_Layout.cshtml and /Views/Home/Index.cshtml
This kind of flow implies that you want to redirect into index page (proved by usage of return RedirectToAction("Index", "Account"); in controller action), which AJAX usage in redirection with GET method makes no sense (because AJAX call intended to stay in the same page).
Instead of replacing entire HTML page content using $("html").html(response);, use window.location.href to redirect with specified URL like this:
NavBarFunctions.js
$("#li_btnHome a")[0].click(function (event) {
event.preventDefault();
alert("called click");
var tokenObj = localStorage.getItem("token");
var tokenStr = tokenObj == null ? "what_about_tokenObj_is_null?" : tokenObj.toString();
$.ajax({
type: 'GET',
url: '#Url.Action("Index", "Home")',
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", tokenStr);
},
success: function (response) {
// this is just an example, replace action & controller name as you wish
window.location.href = '#Url.Action("ActionName", "ControllerName")';
}
});
});
Login.js
function redirect(redirectUrl) {
$.ajax({
type: 'GET',
contentType: 'application/json; charset=utf-8;',
url: redirectUrl,
success: function (response) {
window.location.href = redirectUrl;
}
});
}
However if you want to render certain portion of the page using partial view, you may use jQuery.html() targeting a placeholder, e.g. <div> tag:
<!-- partial view placeholder -->
<div id="content">...</div>
// ajax callback
$.ajax({
// other settings
.....
success: function (response) {
$('#content').html(response);
},
.....
});
I am trying to create a backbone application having login page and one dashboard page called home so for that I have created router having two routes.
After login, I am redirecting to the dashboard page
But I am not seeing anything at all when I run index file.
In the console also, no error is being shown.
var AppRoute = Backbone.Router.extend({
routes: {
"": "login", // #search/kiwis
"home": "home"
},
login: function(){
var loginTemplate = _.template($('#loginPage_template').html());
$('#htmlBodyContent').html(loginTemplate({}));
$('#somlogin').click(function(e) {
var loginData= {};
loginData.userName=document.getElementById('userName').value;
loginData.password=document.getElementById('password').value;
console.log(loginData);
if(loginData.userName==='admin' && loginData.password==='admin' ){
console.log("login successfull")
window.location.hash="#home";
}else{
console.log("do not match")
}
})
}
home: function() {
console.log("welcom to home")
}
});
var router = new Router();
Backbone.history.start();
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="htmlBodyContent">
</div>
<script type="text/template" id="loginPage_template">
<div class="container">
<form class="login">
<h6>dawai<h6>
<input type="userName" class="form-control" id="userName" name="userName">
<input type="password" class="form-control" id="password" name="password">
<br>
<button type="button" class="btn-sm" id="loginBtn" >login</button>
</form>
</div>
</script>
<script src="bower_components/jquery/dist/jquery.js"></script>
<script src="bower_components/underscore/underscore.js"></script>
<script src="bower_components/backbone/backbone.js"></script>
<script src="scripts/main.js"</script>
</body>
</html>
I see you use window.location to navigate your application, that is the problem. You need to use Backbone router api to navigate:
login: function() {
//...
this.navigate('home', {trigger: true});
//...
}
I have to make a work with the trello API, but I'm getting error 400 (invalid token) and I have no idea why.
This is my code (I have replaced my actual key with mykey)
<html>
<head>
<title>A Trello Dashboard</title>
<link rel="stylesheet" media="screen" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h1>Trello Dashboard</h1>
</div>
</body>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="https://trello.com/1/client.js?key=mykey"></script>
<script type="text/javascript">
Trello.authorize({
type: 'popup',
name: 'A Trello Dashboard',
scope: {
read: 'true',
write: 'true'
},
expiration: 'never',
success: function() { console.log("Successful authentication"); },
error: function() { console.log("Failed authentication"); }
});
</script>
</html>
You should put all your code logic inside document.ready, so the entire document will be ready and then only you will get the popup for authentication / authorization. you can get a valid app key here : https://trello.com/app-key See the code example :
<html>
<head>
<title>A Trello Dashboard</title>
<link rel="stylesheet" media="screen" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h1>Trello Dashboard</h1>
</div>
<div id="loggedin">
<div id="header">
Logged in to as <span id="fullName"></span>
</div>
<div id="output"></div>
</div>
</body>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="https://api.trello.com/1/client.js?key=[appKeygoeshere]"></script>
<script type="text/javascript">
$(window).load(function(){
Trello.authorize({
type: 'popup',
name: 'A Trello Dashboard',
scope: {
read: 'true',
write: 'true'
},
expiration: 'never',
success: function() { console.log("Successful authentication");
Trello.members.get("me", function(member){
$("#fullName").text(member.fullName);
var $cards = $("<div>")
.text("Loading Cards...")
.appendTo("#output");
// Output a list of all of the cards that the member
// is assigned to
Trello.get("members/senthil192/cards/all", function(cards) {
$cards.empty();
$.each(cards, function(ix, card) {
//alert(card.name);
$("<a>")
.attr({href: card.url, target: "trello"})
.addClass("card")
.text(card.name)
.appendTo($cards);
});
});
});
},
error: function() { console.log("Failed authentication"); }
});
});
</script>
</html>
code ref url : http://jsfiddle.net/danlec/nNesx/
I'm using Jquery with Spring MVC.
I have an index.jsp:
<html>
<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7"
crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css"
integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r"
crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"
integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS"
crossorigin="anonymous">
</script>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js">
<script type="text/javascript">
</script>
<script>
$(document).ready(function() {
$("input").keyup(function() {
$.ajax({
url : "myController",
type: "POST",
data: $("#name").val(),
success : function(result) {
alert(result);
}
});
});
});
</script>
</head>
<body>
<form>
<div class="row">
<div class="col-sm-12">
<label for="name">Name:</label>
</div>
<div class="col-sm-1">
<input type="text" class="form-name" id="name" placeholder="Paolo">
</div>
</div>
</form>
</body>
</html>
As you can see when one inserts a letter in the input box I run $ajax with jQuery.
My HTTP POST request is correclty sent but I have a 400 error.
This is my simple Controller class:
#Controller
public class MyController {
#RequestMapping(value="/myController", method = RequestMethod.POST)
#ResponseBody
public String getData(#RequestParam(value="name") String name) {
return name;
}
}
My DispatcherServlet for Spring MVC is correclty setted.
How can I solve?
A 400 means that the request was malformed. In other words, the data stream sent by the client to the server didn't follow the rules.
Your ajax call would be
$.ajax({
url : "myController",
type: "POST",
data:{"name": $("#name").val()},
success : function(result) {
alert(result);
}
});
I try to access login service from some web service for user validation directly to html page using jquery, but it seems not working, even when I access the web service with browser the web service work perfectly. Here is the html code:
<html>
<head>
<link rel="stylesheet" type="text/css" href="http://code.ionicframework.com/1.2.4/css/ionic.css">
<link rel="stylesheet" type="text/css" href="http://code.ionicframework.com/1.2.4/css/ionic.min.css">
<script type="text/javascript" src="http://code.jquery.com/jquery-2.2.2.min.js"></script>
<script type="text/javascript">
$("#login").click(function(){
var username=$("#username").val();
var password=$("#password").val();
var dataString="username="+username+"&password="+password+"&login=";
if($.trim(email).length>0 & $.trim(password).length>0)
{
$.ajax({
type: "POST",
url: "some url here",
data: dataString,
crossDomain: true,
cache: false,
beforeSend: function(){ $("#login").html('Connecting...');},
success: function(data){
if(data.success=="true")
{
localStorage.login="true";
localStorage.username=username;
window.location.href = "index.html";
}
else if(data.success="false")
{
alert("Login error");
$("#login").html('Login');
}
}
});
} return false;
});
</script>
</head>
<body>
<div class="bar bar-header bar-positive" style="margin-bottom:80px;">
Home
<h1 class="title">Login</h1>
</div>
<br/><br/>
<input id="username" type="text" placeholder="username" />
<input id="password" type="password" placeholder="password" />
<button id="login">Login</button>
</body>
Even the "beforeSend" code is not working, I mean when I click on Login button the text on it doesn't change to Connecting. How can I make it work?
Replace
$.trim(email).length
To
$.trim(username).length
One more problem in code in success function;
/* Now */
}else if(data.success="false"){
/* should be == because here we are comparing not assigning */
}else if(data.success=="false"){
/* OR we can remove if part completely because we don't need any comparison if not success */
}else{
One more thing if we are getting the response as true or false i don't thing it would be string value, it would be Boolean so update code for success function like following:
success: function(data){
if(data.success){
localStorage.login = "true";
localStorage.username = username;
window.location.href = "index.html";
}else{
alert("Login error");
$("#login").html('Login');
}
}
And one more problem your code won't execute because here you are trying to reference element that not loaded that is login button;
Use following code with all fixes;
<html>
<head>
<link rel="stylesheet" type="text/css" href="http://code.ionicframework.com/1.2.4/css/ionic.css">
<link rel="stylesheet" type="text/css" href="http://code.ionicframework.com/1.2.4/css/ionic.min.css">
<script type="text/javascript" src="http://code.jquery.com/jquery-2.2.2.min.js"></script>
<script type="text/javascript">
/* code wrapped in $(function(){ to make sure the all elemtents loaded before we make use them */
$(function(){
$("#login").click(function(){
var username = $("#username").val();
var password = $("#password").val();
var dataString = "username=" + username + "&password=" + password + "&login=";
if($.trim(password).length > 0 & $.trim(password).length > 0){
$.ajax({
type: "POST",
url: "some url here",
data: dataString,
crossDomain: true,
cache: false,
beforeSend: function(){
$("#login").html('Connecting...');
},
success: function(data){
if(data.success){
localStorage.login = "true";
localStorage.username = username;
window.location.href = "index.html";
}else{
alert("Login error");
$("#login").html('Login');
}
}
});
}
return false;
});
});
</script>
</head>
<body>
<div class="bar bar-header bar-positive" style="margin-bottom:80px;">
Home
<h1 class="title">Login</h1>
</div>
<br/><br/>
<input id="username" type="text" placeholder="username" />
<input id="password" type="password" placeholder="password" />
<button id="login">Login</button>
</body>
</html>
email is not defined before
$.trim(email)
Change it to and the connecting... will appear
$.trim(username)
change $.trim(email).length
To
$.trim(username).length