Razor pages jQuery Autocomplete doing nothing - javascript

I have implemented the JQuery Autocomplete in the following format:
AddApplication.cshtml
#page
#model AddApplicationModel
#{
}
<div>
<form>
<div>
<input type="text" name="appName" placeholder="Enter Application Name">
<select asp-items="Model.ministryItems">
<option>Select Ministry</option>
</select>
</div>
<div>
<input type="text" name="url" id="url" placeholder="Search for a URL" autocomplete="on">
</div>
</form>
</div>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/start/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script type="text/javascript">
$(function () {
$("#url").autocomplete({
source: function (request, response) {
console.log("in funct");
$.ajax({
url: "#Url.Action("GetURL","AddApplication")",
data: ({ term: request.term}),
dataType: "json",
type: "GET",
contentType: "application/json; charset=utf-8",
success: function (data) {
Console.log("success");
response($.map(data, function (item) {
Console.log("response"+item)
return item;
}))
}
});
},
select: function (e, i) {
$("#url").val(i.item.val);
},
minLength: 0
}).focus(function () {
$(this).autocomplete("search");
});
});
</script>
When i type something into my textbox nothing happens at all. After some debugging i know for a fact that the function $("url").autocomplete is being called, but the success: function()data{} is not being hit
Backend razor code:
AddApplication.cshtml
[System.Web.Mvc.HttpGet]
public System.Web.Mvc.JsonResult GetURL(string term)
{
Console.WriteLine("===============IN GETURL====================");
System.Web.Mvc.JsonResult result = new System.Web.Mvc.JsonResult();
var list = (from c in db.Url
where c.UrlName.Contains(term)
select c.UrlName).ToList();
Console.WriteLine(list.Count());
result.Data = list;
result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
Console.WriteLine("---------"+result.Data.ToString());
return result;
}
GetURL I have tested this function with calling it from OnGet just to see if it was actually working, and it is successfully querying the data, im not 100% sure if its properly returning the JSONResult. However it is not being called by autocomplete.
I am not sure if this is a path issue, i don't believe it is as i had that resolved beforehand
I have also tried using the following JQuery snippet, and it yields the same results
<script type="text/javascript">
$(function () {
console.log("function");
$("#url").autocomplete({
source: "#Url.Action("GetURL","AddApplication")",
minLength: 1,
select: function (event, ui) {
if (ui.item) {
console.log("-----"+ui.item);
$("#url").val(ui.item.value);
$("form").submit();
}
}
});
});
</script>
Response tab for textbox search
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title> - LookupTool</title>
<link rel="stylesheet" href="/lib/bootstrap/dist/css/bootstrap.css" />
<link rel="stylesheet" href="/css/site.css" />
<script src="/lib/jquery/dist/jquery.js"></script>
<script src="/lib/bootstrap/dist/js/bootstrap.js"></script>
<script src="/js/site.js?v=dLGP40S79Xnx6GqUthRF6NWvjvhQ1nOvdVSwaNcgG18"></script>
</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>
<a asp-page="/Index" class="navbar-brand">LookupTool</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li><a asp-page="/Index">Home</a></li>
<li><a asp-page="/About">About</a></li>
<li><a asp-page="/Contact">Contact</a></li>
</ul>
</div>
</div>
</nav> -->
<div class="container-fluid body-content">
<div style="margin-left: 5%; margin-right: 5%">
<div>
<form>
<div>
<input type="text" name="appName" placeholder="Enter Application Name">
<select>
<option>Select Ministry</option>
<options> - cant display this information
</select>
</div>
<div>
<input type="text" name="url" id="url" placeholder="Search for a URL" autocomplete="on">
</div>
</form>
</div>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/start/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script type="text/javascript">
$(function () {
$("#url").autocomplete({
source: function (request, response) {
console.log("in funct");
$.ajax({
url: "/AddApplication?action=GetURL&controller=AddApplication",
data: ({ term: request.term}),
dataType: "json",
type: "GET",
contentType: "application/json; charset=utf-8",
success: function (data) {
Console.log("success");
response($.map(data, function (item) {
Console.log("response"+item)
return item;
}))
}
});
},
select: function (e, i) {
$("#url").val(i.item.val);
},
minLength: 0
}).focus(function () {
$(this).autocomplete("search");
});
});
</script>
<hr />
<footer>
footer
</footer>
</div>
</div>
</body>
</html>

Modify the ajax request to correctly include the query string parameters:
$.ajax({
url: "AddApplication/GetURL",
data: ({ term: request.term}),
dataType: "json",
type: "GET",
success: function (data) {
response($.map(data, function (item) {
return item;
Console.log("response"+item)
}))
}
});

I was able to finally get it working after more searches. Adding the anti forgery token may have been the underlying issue as i did not have it added before. Notice the URL, according to multiple sources this is the correct way to reference a URL in razor.
Although its working for some reason only the completed function is called, it never goes into success. This isnt causing issues at the moment.
AddApplication.cshtml
<script>
$(document).ready(function(){
$("#UrlQueBtn").click(function(e)
{
e.preventDefault();
var url = $('#urlSelect').val();
console.log(url);
$.ajax({
url: "AddApplication?handler=AddUrlToQue",
type: "POST",
dataType: "json",
data: { urlSelect: url },
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
success: function () {
alert("success");
},
complete: function () {
alert("complete")
},
failure: function () {
alert("failure");
}
})
});
});
</script>
Need to add the anti forgery token to startup class
startup.cs
under ConfigureServices
services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");

Related

Html page loading causing Javascript to not function properly in redirected page

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);
},
.....
});

spPageContextInfo is not defined

I am trying to add userName use AngularJs into Sharepoint. Also, i should have a feature that I should view all the userName from SharePoint list. But i keeping getting error says '_spPageContextInfo is not defined'.
I am start learning SharePoint and AngularJs. Can someone help me with it? Thank you.
Here is the code:
index.html
<!DOCTYPE html>
<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" type="text/css" media="screen" href="main.css" />
<script type="text/javascript" src="jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="angular.min.js"></script>
<!-- modules -->
<script src="app.js"></script>
<!-- controllers -->
<script src="view.js"></script>
<script src="add.js"></script>
</head>
<body ng-app="myApp">
<h3>view</h3>
<div class="view" ng-controller="viewItemsController" ng-repeat="user in users">
<!-- {{user.ID}}: -->
{{user.Title}}, {{user.FirstName}},{{user.LastName}}
<br />
</div>
<hr>
<h3>add</h3>
<div class="add" ng-controller="addItemsController">
<div class="Table">
<div class="Row">
<div class="Cell">Title :</div>
<div class="Cell">
<input type="text" id="title" ng-model="title" />
</div>
</div>
<div class="Row">
<div class="Cell">First Name :</div>
<div class="Cell">
<input type="text" id="firstName" ng-model="firstName" />
</div>
</div>
<div class="Row">
<div class="Cell">Last Name :</div>
<div class="Cell">
<input type="text" id="lastName" ng-model="lastName" />
</div>
</div>
<div class="Row">
<div class="Cell"></div>
<div class="Cell">
<input type="button" id="btnAddContact" value="Add Name" ng-click="addContact()" />
</div>
</div>
</div>
</div>
</body>
</html>
app.js //this is module
var spApp = angular.module('myApp',[]);
view.js // first controller
spApp.controller("viewItemsController", function ($scope, $http) {
var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('Users')/items?$select=Title,First_Name,Last_Name";
$http(
{
method: "GET",
url: url,
headers: { "accept": "application/json;odata=verbose" }
}
).success(function (data, status, headers, config) {
console.log(data);
$scope.users = data.d.results;
}).error(function (data, status, headers, config) {
});
});
add.js // second controller
spApp.controller("addItemsController",function($scope,$http){
var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('Users')/items";
var vm = $scope;
vm.addContact = function () {
return $http({
headers: { "Accept": "application/json; odata=verbose", "X-RequestDigest": jQuery("#__REQUESTDIGEST").val() },
method: "POST",
url: url,
data: {
'Title': vm.title,
'First_Name': vm.firstName,
'Last_Name':vm.lastName
}
})
.then(saveContact)
.catch(function (message) {
console.log("addContact() error: " + message);
});
function saveContact(data, status, headers, config) {
alert("User Added Successfully");
return data.data.d;
}
}
});
I go through your code, you have made spelling mistake with the script tag
If you see your Html code which you have added into your question
<!-- controllers -->
<sript src="view.js"></script>
<sript src="add.js"></script>
I have test your code on my system by correcting the spelling mistake as bellow and its working.
<!-- controllers -->
<script src="view.js"></script>
<script src="add.js"></script>
Hope so this will help you.

ASP .net doesn't fire submit event

I try to do a submit ajax with ASP .net and jquery but he never fire d«the event, I already try with this two examples and he never fire the event alert.
<form id="form">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
#Html.TextBoxFor(m => m.VatNumber,new { #class = "form-control", #id="VatNumber"})
#Html.ValidationMessage("VatNumber")
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Check VAT" />
</div>
</div>
</div>
</form>
<script type="text/javascript">
$(document).ready(function () {
$('#form').submit(function () {
alert("cheguei");
$.ajax({
url: '#Url.Action("CheckVat")',
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({
VatNumber: $('#VatNumber').val(),
}),
success: function (result) {
alert("success");
},
error: function (result) {
alert("error");
}
});
return false;
});
});
$(function () {
$('#form').submit(function (event) {
alert("cheguei");
event.preventDefault(); // Prevent the form from submitting via the browser
var form = $(this);
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize()
}).done(function (data) {
// Optionally alert the user of success here...
}).fail(function (data) {
// Optionally alert the user of an error here...
});
});
});
</script>
I figure out : I have to include the scripts in the Head section and the problem is fixed.
<head>
<meta charset="utf-8" />
<title>#ViewBag.Title - My ASP.NET MVC Application</title>
<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<meta name="viewport" content="width=device-width" />
#Styles.Render("~/Content/bootstrap.min.css")
#*#Styles.Render("~/Content/css")*#
#Scripts.Render("~/bundles/modernizr")
<script src="~/Scripts/jquery-3.1.0.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
</head>

Can't Get Data for Simple Login with HTML to PHP Web Service

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

Service variable not updating directive in Angular JS

I think this is a scoping problem, but I can't get my head around this.
I have a service as below:
(function (module) {
var portalService = function ($timeout, $http, $q, alerting, $cookies, $cookieStore, STATUS_OK, STATUS_FAIL, APP_COOKIE) {
var _permissions = {};
var permissions = function ()
{
var def = $q.defer();
if (loggedIn) {
if (_.size(_permissions) > 0) {
def.resolve({ status: STATUS_OK }, _permissions);
}
else {
$http({
url: "/Auth/GetPermissionsAsync",
method: "POST",
}).success(function (data, status, headers, config) {
if (data.result.status == STATUS_OK) {
_permissions = data.permissions;
}
def.resolve(data.result, data.permissions);
}).error(function (data, status, headers, config) {
def.reject("Failed to retrieve permissions.", status);
});
}
}
else {
def.resolve({ status: STATUS_OK }, _permissions);
}
return def.promise;
}
var logOn = function (email, password) {
var def = $q.defer();
$http({
url: "/Auth/LogInAsync",
method: "POST",
data: { email: email,
password: password},
}).success(function (data, status, headers, config) {
//testing if we can even update this...
_permissions=[{parent: "Administer", items: [{name: "Users", route: "dashboard"}]}];
def.resolve(data.result);
}).error(function (data, status, headers, config) {
def.reject("Failed to contact the server to log in.",status);
});
return def.promise;
};
var register = function (data) {
var def = $q.defer();
$http({
url: "/Auth/RegisterAsync",
method: "POST",
data: data
,
}).success(function (data, status, headers, config) {
def.resolve(data.result);
}).error(function (data, status, headers, config) {
def.reject("Registration failed to contact the server",status);
});
return def.promise;
};
var logOut = function (data) {
var def = $q.defer();
$http({
url: "/Auth/SignOutAsync",
}).success(function (data, status, headers, config) {
_permissions = {};
def.resolve(data.result);
}).error(function (data, status, headers, config) {
def.reject("Signing out failed to contact the server.", status);
});
return def.promise;
};
var loggedIn = function ()
{
if ($cookies.get(APP_COOKIE))
return true;
else
return false;
}
var currentPermissions = function ()
{
return _permissions;
}
return {
logOn: logOn,
register: register,
logOut: logOut,
loggedIn: loggedIn,
permissions: permissions,
currentPermissions : _permissions
};
};
module.factory("portalService", portalService);
}(angular.module("clportal")));
I have a directive as below:
(function (module) {
var navMenu = function (portalService) {
return {
restrict: "AE",
templateUrl: "/Template/NavMenu",
scope: true,
link: function(scope, element, attributes) {
scope.permissions = portalService.currentPermissions;
}
};
};
module.directive("navmenu", navMenu);
}(angular.module("clportal")));
And, I have the inclusions as below:
<!DOCTYPE html>
<html lang="en" ng-app="clportal">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="/favicon.ico">
<title>Navbar Template for Bootstrap</title>
<!-- Bootstrap core CSS -->
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" integrity="sha512-dTfge/zgoMYpP7QbHy4gWMEGsbsdZeCXz7irItjcC3sPUFtf0kuFbDz/ixG7ArTxmDjLXDmezHubeNikyKGVyQ==" crossorigin="anonymous">
<link rel="stylesheet" href="~/lib/angular-growl-v2/build/angular-growl.min.css" />
<link rel="stylesheet" href="~/lib/angular-ui-router-anim-in-out/css/anim-in-out.css" />
<link rel="stylesheet" href="~/lib/font-awesome/css/font-awesome.min.css">
<!-- Custom styles for this template -->
<link href="~/css/site.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<!-- Static navbar -->
<div ng-controller="navController">
<nav class="navbar navbar-default" role="navigation">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" ng-init="navCollapsed = true" ng-click="navCollapsed = !navCollapsed">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Customer Center</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" ng-class="!navCollapsed && 'in'">
<navmenu></navmenu>
</div><!-- /.navbar-collapse -->
</nav>
</div>
<!-- Main component for a primary marketing message or call to action -->
<div growl inline="true" reference="global"></div>
<div class="row" >
<route-loading-indicator></route-loading-indicator>
<div ng-if="!isRouteLoading" ui-view="" class="col-lg-12 anim-in-out anim-fade" data-anim-speed="1000" ></div>
</div>
</div> <!-- /container -->
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="~/lib/angular/angular.min.js"></script>
<script src="~/lib/angular-ui-router/release/angular-ui-router.min.js"></script>
<script src="~/lib/angular-messages/angular-messages.min.js"> </script>
<script src="~/lib/angular-sanitize/angular-sanitize.min.js"></script>
<script src="~/lib/angular-animate/angular-animate.min.js"></script>
<script src="~/lib/angular-bootstrap/ui-bootstrap-tpls.min.js"></script>
<script src="~/lib/angular-cookies/angular-cookies.min.js"></script>
<script src="~/lib/angular-ui-router-anim-in-out/anim-in-out.js"></script>
<script src="~/js/app/app-clportal.js"> </script>
<script src="~/lib/angular-growl-v2/build/angular-growl.min.js"></script>
<script src="~/js/app/services/exceptionHandler.js"></script>
<script src="~/js/app/services/portalService.js"> </script>
<script src="~/js/app/services/alerting.js"></script>
<script src="~/js/app/directives/alert.js"></script>
<script src="~/js/app/directives/compareDirective.js"> </script>
<script src="~/js/app/directives/formInput.js"></script>
<script src="~/js/app/controllers/homeController.js"> </script>
<script src="~/js/app/controllers/loginController.js"> </script>
<script src="~/js/app/controllers/registerController.js"> </script>
<script src="~/js/app/directives/loadingView.js"></script>
<script src="~/js/app/controllers/dashboardController.js"></script>
<script src="~/js/app/controllers/navController.js"></script>
<script src="~/js/app/directives/navMenu.js"></script>
<script src="~/lib/underscore/underscore-min.js"></script>
</body>
</html>
Now when I call the logOn method, via the portalService, in theory it should set the _permissions local variable, which then should update the appropriate directive navMenu so that it sees the new menu option, and renders appropriately. However this does not work. I can use simple examples and its fine, but there is something fundamentally wrong with the way I'm doing it, scoping wise I would assume and I can't see it.
Any help appreciated.
Thanks
It was just a simple bug - LogOff was being called before log on, and that was setting the local variable to an empty object - this basically cut off the reference that was stored against the directive.
So I needed to set the size to zero on the array if i wanted to clear it out, to make sure that the original reference wasn't lost, and use push to push new values to the array. Working fine now.

Categories