MEAN stack ajax POST Error: TypeError: Cannot read property 'userName' of undefined - ajax

So, here's some background: I am working on a MEAN stack app for my school where we can read and post our Galaga and Dig Dig highscores to a mongo database.
I am getting an error:
POST http://url.com/api/scores 500 (Internal Server Error)
TypeError: Cannot read property 'userName' of undefined at /app/server.js:37:22
server.js:37 is:
app.post("/api/scores", function(req, res){
Score.create({
name:res.body.userName,
game:res.body.game,
points:res.body.userPoints
});
});
The index.html that the res.body.* is coming from is:
<!DOCTYPE html>
<html ng-app="nameOfApp">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap-theme.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js"></script>
<script src="core.js"></script>
</head>
<body ng-controller="mainController">
<div class="container">
<div class="jumbotron text-center">
<div class="container">
<h1>HelpDesk Gaming Leaderboard</h1>
</div>
</div>
<div class="container">
<table>
<tr>
<td><b>Name</b></td>
<td><b>Score</b></td>
</tr>
<tr ng-repeat="score in scores">
<td>{{score.name}}</td>
<td>{{score.points}}</td>
</tr>
</table>
</div>
<br/>
<h2>Score?</h2>
<form>
<input name="userName" type="String" class="form-control" id="userName" ng-model="formData.userName" placeholder="Your Name">
<input name="game" type="String" class="form-control" id="game" ng-model="formData.game" placeholder="The game?">
<input name="userPoint" type="Number" class="form-control" id="userPoint" ng-model="formData.userPoint" placeholder="Points?">
<button type="submit" class="btn btn-default" ng-click="createScore()">Submit</button>
</form>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js">
</script>
</body>
</html>
and the core.js, which is the angular piece is:
var nameOfApp= angular.module('nameOfApp', []);
nameOfApp.controller("mainController", ["$scope", "$http", function($scope, $http) {
$scope.formData = {};
// when landing on the page, get all scores and show them
$http.get('/api/scores')
.success(function(data) {
$scope.scores = data;
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
$scope.createScore = function() {
$http.post('/api/scores', $scope.formData)
.success(function(data) {
$scope.formData = {};
$scope.scores = data;
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
};
}]);
Thanks for your input, and if there are any stylistic things that I have wrong, I would love to hear them. I am trying to get better at MEAN stack development.

It's not res.body.* you want to use in your Score.create method, you want to be using req.body.*. 'req' is what has all the data from your http request.
Should be:
app.post("/api/scores", function(req, res){
Score.create({
name:req.body.userName,
game:req.body.game,
points:req.body.userPoints
});
});

Related

Failed to load resource: net::ERR_BLOCKED_BY_RESPONSE when load https://www.google.com/recaptcha/enterprise/webworker.js

Sometimes when render reCAPTCHA widget, it will report an error Failed to load resource: net::ERR_BLOCKED_BY_RESPONSE from https://www.google.com/recaptcha/enterprise/anchor when load https://www.google.com/recaptcha/enterprise/webworker.js
image
And we can reproduce this by refresh the page again and again (use document demo code):
<html>
<head>
<title>reCAPTCHA demo: Explicit render after an onload callback</title>
<script type="text/javascript">
var onloadCallback = function() {
grecaptcha.enterprise.render('html_element', {
'sitekey' : ' site_key',
});
};
</script>
</head>
<body>
<form action="?" method="POST">
<div id="html_element"></div>
<br>
<input type="submit" value="Submit">
</form>
<script src="https://www.google.com/recaptcha/enterprise.js?onload=onloadCallback&render=explicit"
async defer>
</script>
</body>
</html>

access items in a nested list in angularJS

I am new to AngularJS and i need your help. I have created a JSON file which consists of a list of items inside another list. I want to access the items in the second list but I don't know how. I have searched all day in the Internet but I hardly found anything useful. Please help me. Below is my code:
categoryItems.json
[
{
"$id":"1",
"name":"Business",
"cat":[
{
"cname":"CyberSecurity",
"img":"img3_1.jpg",
"cat_kurs":"7-course specialization",
"txt":"Rice University"
},
{
"cname":"Google Cloud Platform for Systems Operations",
"img":"img3_2.jpg",
"cat_kurs":"6-course specialization",
"txt":"University of California"
},
{
"cname":"Data Security",
"img":"img3_1.jpg",
"cat_kurs":"7-course specialization",
"txt":"Rice University"
}
]
},
{
"$id":"2",
"name":"Foreign Language",
"cat":[
{
"cname":"Data Security",
"img":"img3_1.jpg",
"cat_kurs":"7-course specialization",
"txt":"Rice University"
},
{
"cname":"Google Cloud",
"img":"img3_2.jpg",
"cat_kurs":"3-course specialization",
"txt":"University of California"
}
]
}
]
script.js
var myItemsApp = angular.module('myItemsApp', []);
myItemsApp.factory('itemsFactory', ['$http', function($http){
var itemsFactory ={
itemDetails: function() {
return $http(
{
url: "categoryItems.json",
method: "GET",
})
.then(function (response) {
return response.data;
angular.forEach(data.itemDetails, function(item) {
});
});
}
};
return itemsFactory;
}]);
myItemsApp.controller('ItemsController', ['$scope', 'itemsFactory', function($scope, itemsFactory){
var promise = itemsFactory.itemDetails();
promise.then(function (data) {
$scope.itemDetails = data;
console.log(data);
});
$scope.select = function(item) {
$scope.selected = item;
};
$scope.selected = {};
}]);
index.html
<!DOCTYPE html>
<html ng-app="myItemsApp">
<head>
<meta charset="utf-8" />
<title>Test</title>
<!-- <link data-require="bootstrap-css" data-semver="3.1.1" rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" />-->
<link href="css/bootstrap.min.css" rel="stylesheet" media="screen" />
<link href="css/bootstrap-theme.min.css" rel="stylesheet" media="screen"/>
<script src="js/angular.min.js"></script>
<script src="js/angular.js"></script>
<script src="script.js"></script>
<style>
span.el{
background-color:#85929E;
font-size: xx-small;
font-color: #FDFEFE;
width: 60px;
}
span.txt{
font-size:xx-small;
}
div.cat{
background-color:#F2F3F4 ;
}
</style>
</head>
<body>
<div ng-controller="ItemsController">
<div class="row">
<div class="col-md-4">
<div class="panel panel-default">
<ul class="list-group">
<a class="list-group-item" ng-click="select(item)" ng-repeat="item in itemDetails">{{item.name}}</a>
</ul>
</div>
</div>
<div class="col-md-8">
<div class="panel panel-default" style="width: 70%">
<div class="panel-heading">{{selected.name}}</div>
<div class="panel-body">
<div ng-repeat="subcat in item.cat ">
{{subcat.cname}}
</div>
</div>
</div>
</div>
</div>
</body>
</html>
Please HELP ME.
Looks like you need todo another ng-repeat on the sub categories.
<div class="col-md-8" ng-show="selected.name.length">
<div class="panel panel-default" style="width: 70%">
<div class="panel-heading">{{selected.name}}</div>
<div class="panel-body">
<div ng-repeat="subcat in itemDetails | filter:{name:selected.name}">
<div ng-repeat="cat in subcat.cat">
{{cat.cname}}
</div>
</div>
</div>
</div>
Have a look at this example ive mocked up for you
You need to deserialize the response using angular.fromJson
more reference: https://docs.angularjs.org/api/ng/function/angular.fromJson

ajax form does not submit

I can't get this form to submit via Ajax to a PHP script and cannot figure out why. Please help. I am planning to use this in phone gap after development and was under the impression this ajax format would work better than xmlhttprequest method - is this really the case?
<html>
<head>
<title></title>
</head>
<body>
<h1>Welcome</h1>
<hr>
<form id="idForm" name="idForm">
<input type="text" size="8" id="date" name="date"><br>
<input type="hidden" size="8" id="reversedate" name="reversedate"><br>
<input type="hidden" size="1" id="dow" name="dow"><br>
<input type="submit" id="submitbutton" name="submitbutton">
</form>
<br><br><br>
<br>
<br>
<p id="p1">x</p>
<br>
log out
<script>
$('#submitbutton').click(function(){
$("#idForm").submit(function() {
var url = "fetchsimple.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#idForm").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery-ui.js"></script>
<script type="text/javascript" src="js/ui.js"></script>
</body>
</html>

Ajax call fail when I can trying to pass the special characters as data

This is the code I am using to add a comment using Ajax call.
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.0-rc.1/jquery.mobile- 1.1.0-rc.1.min.css" />
<script type="text/javascript" charset="utf-8" src="js/cordova-1.5.0.js">
</script>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.1.0-rc.1/jquery.mobile-1.1.0-rc.1.min.js"></script>
<script src="js/global.js" type="text/javascript"></script>
</head>
<script>
var msgId = window.localStorage.getItem("clickedId");
processLogInData = function(){
var comment = ($("#comment").val());
temp = 'messageId=' + msgId +'&';
temp += 'uniqueId=' + device.uuid + '&';
temp += 'comments=' + comment;
var s= global1 +"rest/Comment/createCommentBO?"+temp;
$.ajax({
url:global1 +"rest/Comment/createCommentBO?",
data: temp,
dataType: 'xml',
timeout: 10000,
async: false,
cache: false,
type: 'POST',
success: function(data){
if($(data).find("isException").text() == "false")
{
//alert('No Exceptions found');
onTrue();
}
else
{
onFalse();
}
},
error:function(XMLHttpRequest,textStatus, errorThrown) {
// alert("Error status :"+textStatus);
// alert("Error type :"+errorThrown);
alert("Error message :"+XMLHttpRequest.responseXML);
$("#messagelist").append( XMLHttpRequest.responseXML);
}
});
}
function onTrue(){
location.replace("comments.html");
}
function onFalse()
{
console.log("onFalse Method");
alert("Unable to create Comment!");
}
function cancel(){
location.replace("comments.html");
}
</script>
<body>
<div data-role="page" data-theme="a">
<div data-theme="a" data-role="header">
<img src="images/logo_header.png" alt="Orange"/>
</div>
<div data-role="content">
<form method="post" name="login" data-ajax="false">
<label for="textarea"><h3><u>Add Comment</u> : </h3></label>
<textarea cols="15" rows="15" name="textarea" id="comment"></textarea>
</form>
<div>
<div class="ui-block-a"><button type="submit" data-theme="d" onclick="cancel();" data-mini="true" data-icon="delete">Cancel</button></div>
<div class="ui-block-b"><button type="submit" data-theme="a" onclick="processLogInData();" data-mini="true" data-icon="check" >Submit</button></div>
</div>
</div>
</div>
</body>
When I enter special character as content as pass it to Ajax call I am getting an error :( Ajax call works fine with out any special characters...
Is there any way to encode the data before passing it to ajax call???Please help me on this...
Thanks in advance.
(1.)Either you should put your data into a form and serialize it and then send to the server
(2.)Second way is you can use the js inbuilt function encodeURIComponent().

Demo jquery ui map Is Blank in ios5

I was testing out this demo on query-ui-maps:
http://jquery-ui-map.googlecode.com/svn/trunk/demos/jquery-google-maps-mobile.html#directions_map
Everything is the same except for the head section of my index.html file:
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<link rel="stylesheet" href="jquery-mobile/jquery.mobile.css" />
<link href="css/jquery.mobile-swatch.css" rel="stylesheet" type="text/css"/>
<link href="css/custom-icons.css" rel="stylesheet" type="text/css"/>
<link href="css/mapapp.css" rel="stylesheet" type="text/css"/>
<script src="http://maps.google.com/maps/api/js?sensor=false&libraries=places" type="text/javascript"></script>
<script src="js/jquery.js"></script>
<script src="jquery-mobile/jquery.mobile.js"></script>
<script type="text/javascript" src="ui/jquery.ui.map.js"></script>
<script type="text/javascript" src="ui/jquery.ui.map.extensions.js"></script>
<script type="text/javascript" charset="utf-8" src="js/cordova-iphone.js"></script>
<script type="text/javascript" src="ui/jquery.ui.map.services.js"></script>
<script type="text/javascript" src="js/jquery-ui-autocomplete-1-8-15.js"></script>
<script type="text/javascript" src="js/modernizr.js"></script>
<script type="text/javascript" src="js/demo.js"></script>
The demo works in safari on my desktop but loads the screen attached whether I test in an ios5 simulator or an ios5 phone. No errors are logged to the console. I am testing in Xcode and using phone gap.
Please help.
This is the code:
var mobileDemo = { 'center': '57.7973333,12.0502107', 'zoom': 10 };
$('#directions_map').live('pageinit', function() {
demo.add('directions_map', function() {
$('#map_canvas_1').gmap({'center': mobileDemo.center, 'zoom': mobileDemo.zoom, 'disableDefaultUI':true, 'callback': function() {
var self = this;
self.set('getCurrentPosition', function() {
self.refresh();
self.getCurrentPosition( function(position, status) {
if ( status === 'OK' ) {
var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude)
self.get('map').panTo(latlng);
self.search({ 'location': latlng }, function(results, status) {
if ( status === 'OK' ) {
$('#from').val(results[0].formatted_address);
}
});
} else {
alert('Unable to get current position');
}
});
});
$('#submit').click(function() {
self.displayDirections({ 'origin': $('#from').val(), 'destination': $('#to').val(), 'travelMode': google.maps.DirectionsTravelMode.DRIVING }, { 'panel': document.getElementById('directions')}, function(response, status) {
( status === 'OK' ) ? $('#results').show() : $('#results').hide();
});
return false;
});
}});
}).load('directions_map');
});
$('#directions_map').live('pageshow', function() {
demo.add('directions_map', $('#map_canvas_1').gmap('get', 'getCurrentPosition')).load('directions_map');
});
</script>
</head>
<body>
<div id="directions_map" data-role="page">
<div data-role="header">
<h1>jQuery mobile with Google maps v3</h1>
<!--<a data-rel="back">Back</a>-->
</div>
<div data-role="content">
<div class="ui-bar-f ui-corner-all ui-shadow" style="padding:1em;">
<div id="map_canvas_1" style="height:300px; width:100%;"></div>
<p>
<label for="from">From</label>
<input id="from" class="ui-bar-f" type="text" value="Göteborg, Sweden" />
</p>
<p>
<label for="to">To</label>
<input id="to" class="ui-bar-f" type="text" value="Stockholm, Sweden" />
</p>
<a id="submit" href="#" data-role="button" data-icon="search">Get directions</a>
</div>
<div id="results" class="ui-listview ui-listview-inset ui-corner-all ui-shadow" style="display:none;">
<div class="ui-li ui-li-divider ui-btn ui-bar-f ui-corner-top ui-btn-up-undefined">Results</div>
<div id="directions"></div>
<div class="ui-li ui-li-divider ui-btn ui-bar-f ui-corner-bottom ui-btn-up-undefined"></div>
</div>
</div>
</div>
</body>
After much searching, this has proved to be the best answer:
http://code.google.com/p/jquery-ui-map/wiki/Examples#Example_get_user_position

Resources