400 Error POST Method to DynamoDB - AJAX - json

I am currently trying to update a DynamoDB table with information that I add into a HTML form. Every time that I run my program and submit my information, I get this error:
POST https://quovje1gi8.execute-api.us-east-2.amazonaws.com/production/accounts 400 ()
I can run my Lambda function on AWS, and add data to my table just fine. I have checked again and again to make sure that my permissions are established correctly and they are. I just can't seem to figure this out.
My front-end:
<form>
<label for="username">Add Username:</label>
<textarea id="username"></textarea>
<button id='submitButton'>Submit</button>
</form>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js">
</script>
<script type="text/javascript">
var API_URL = 'https://quovje1gi8.execute-api.us-east-2.amazonaws.com/production/accounts';
$(document).ready(function(){
$.ajax({
type:'GET',
url: API_URL,
success: function(data){
$('#accounts').html('');
data.Items.forEach(function(accountsItem){
$('#accounts').append('<p>' + accountsItem.username + '</p>');
})
}
});
});
$('#submitButton').on('click', function(){
$.ajax({
type:'POST',
url: API_URL,
data: JSON.stringify({"username": $('#username').val()}),
contentType: "application/json",
success: function(data){
location.reload();
}
});
return false;
});
Lambda function:
'use strict';
console.log('Starting Function');
const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient({region:'us-east-2'});
exports.handler = function(e, ctx, callback) {
var params = {
Item: {
user_id: ,
date: Date.now(),
username: "",
password: "",
name: "",
location: "",
field: "",
company: ""
},
TableName: 'accounts'
};
docClient.put(params, function(err, data){
if(err){
callback(err, null);
}
else{
callback(null, data);
}
});
}

Related

Ajax post data from form to send to express js body parser

I am tring to send Form data to node js via ajax,
I am using express with body parser on node js
But I am getting undefined in req.body
I searched every in net and tried many things and nothing worked for me
Kindly help me with the correct way of doing this.
|*| Html Code :
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<title>Add</title>
</head>
<body>
<h1>Welcome to Website </h1>
<form id="addUserForm">
<h3> Enter the your details : </h3>
Name :<br><input type="text" name="nameView"><br><br>
Email :<br><input type="email" name="mailView"><br><br>
Mobile :<br><input type="number" name="mobileView"><br><br>
<input type="submit" value="Submit">
</form>
|*| Ajax Code :
<script>
$(document).ready( function()
{
$('#addUserForm').submit(function()
{
var formDataVar = new FormData($(this)[0]);
console.log(formDataVar);
$.ajax({
url: '/addUserFormSubmit',
type:'POST',
data: formDataVar,
dataType: 'json',
contentType: false,
processData: false,
}).done(function(ResJryVar)
{
console.log(ResJryVar);
});
})
});
</script>
</body>
</html>
|*| I also tried :
var formDataVar = new FormData();
formDataVar.append( 'nameView', input.files[0] );
formDataVar.append( 'mailView', input.files[1] );
formDataVar.append( 'mobileView', input.files[2] );
and
var formDataVar = {};
$.each($('#addUserForm').serializeArray(), function(i, field)
{
formDataVar[field.name] = field.value;
});
|*| Node Js Code :
var express = require("express");
var bodyParser = require("body-parser");
var app = express();
app.listen(8888,function()
{
console.log("Server Started and Running ...");
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.get('/',addUserFormFnc);
app.post('/addUserFormSubmit',addUserSubmitFnc);
function addUserFormFnc(req, res)
{
res.sendFile('addUser.html', {root: __dirname });
}
function addUserSubmitFnc(req, res)
{
console.log("Data Received : ");
var userObjVar =
{
nameView: req.body.nameView,
mailView: req.body.mailView,
mobileView: req.body.mobileView
};
console.log(userObjVar);
res.send(userObjVar);
}
The body-parser library does not handle data encoded with multipart/form-data. If you want to send that type of data, you should be using something like the multer middleware.
But in your case, I think you can get away without having to use the FormData interface. You can just rewrite your browser code as such:
const $form = $('#addUserForm')
$form.on('submit', submitHandler)
function submitHandler (e) {
e.preventDefault()
$.ajax({
url: '/addUserFormSubmit',
type:'POST',
data: $form.serialize()
}).done(response => {
console.log(response)
})
}
<html>
<head>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous"></script>
</head>
<body>
<form id="myForm" name="myForm">
<div>
<label for="comment">Comment:</label>
<textarea id="comment" name="comment"></textarea>
</div>
<div>
<label for="rating">Comment:</label>
<textarea id="rating" name="comment"></textarea>
</div>
<input type="submit" value="Submit!">
</form>
<script>
$(document).ready(function () {
$('form').submit(function (event) {
event.preventDefault();
//collect the form data using Id Selector what ever data you need to send to server
let comment=$('#comment').val();
let rating= $('#rating').val()
$.ajax({
url: 'replace your url',
data: JSON.stringify({"comment": comment, "rating": rating }),
processData: false,
type: 'POST',
contentType: 'application/json',
success: function (data) {
alert(data);
}
});
});
})
</script>
</html>
Find complete code:
server.js
let express = require("express"),
multer = require('multer'),
crypto = require('crypto'),
fileExtension = require('file-extension'),
app = express();
let storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './uploads')
},
filename: function (req, file, callback) {
crypto.pseudoRandomBytes(16, function (err, raw) {
callback(null, raw.toString('hex') + Date.now() + '.' + fileExtension(file.mimetype));
});
}
});
let upload = multer({ storage : storage}).single('image');
app.get('/',function(req,res){
res.sendFile(__dirname + "/index.html");
});
// method to accept request from the file
app.post('/api/form-submit',function(req,res){
upload(req,res,function(err) {
console.log(req.body,'other form data---');
if(err) {
return res.end("Error uploading file.");
}
res.end("File is uploaded");
});
});
app.listen(3000,function(){
console.log("App listening on port: 3000");
});
package.json
{
"name": "form_submit_using_ajax",
"version": "1.0.0",
"author": "Suraj Roy",
"keywords": "N/A",
"description": "N/A",
"dependencies": {
"express": "4.13.3",
"file-extension": "^4.0.5",
"multer": "1.1.0"
},
"devDependencies": {
"should": "~7.1.0",
"mocha": "~2.3.3",
"supertest": "~1.1.0"
}
}
Form section:
<form id="uploadForm" enctype="multipart/form-data" action="/api/form-submit" method="post">
<input id="file" type="file" name="image" />
<label>name :</label><input type="text" name="name" />
<input type="submit" value="Upload Image" name="submit">
<span id = "status"></span>
</form>
Script section
<script>
$(document).ready(function() {
$('#uploadForm').submit(function() {
$("#status").empty().text("File is uploading...");
$(this).ajaxSubmit({
error: function(xhr) {
status('Error: ' + xhr.status);
},
success: function(response) {
$("#status").empty().text(response);
console.log(response);
}
});
//Code to disable the page refresh.
return false;
});
});
</script>

Unknown provider: callbackProvider <- callback

I am stuck with this code for very long time and apply all the patches available on net but didn't find the effective one.It is still giving error while calling service from controller.
Here the code below
<HTML ng-app="myApp">
<body ng-controller = "myCtrl">
<div>{{me}}</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.js"></script>
<script>
var app = angular.module('myApp',[])
app.controller('myCtrl',function($scope,myService){
myService.getx(function(data){
console.log(data);
$scope.me = "data";
});
});
</script>
<script>
app.service('myService',function($http,callback){
this.getx= function(){
return $http({
method: "GET",
url: "https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.js"
}).then(function (response) {
console.log(response)
return callback(response);
}, function (error) {
throw error;
console.log("Error",error)
});
}
});
</script>
</HTML>
i'd rewrite it like this:
APP CTRL:
var app = angular.module('myApp',[])
app.controller('myCtrl',function($scope,myService){
myService.getx()
.then(
function(data){ //handle the $http promise here
console.log(data);
$scope.me = "data";
},
function(err){
console.log('error:' + err);
});
});
SERVICE:
app.service('myService',function($http){
return {
getx: function() {
return $http({ //the $http returns a promise
method: "GET",
url:"https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.js"
});
}
}
});

Passing Json from Controller to View

I have a database of movies, and I am looking to create a Json, and then access that json in my view. I have successfully created the json within the controller using the following code:
var movies = from m in db.Movies
select m;
string jsonData = JsonConvert.SerializeObject(movies);
This creates a json, which I have passed to the Console via writeline, and it generates the following JSON:
[{"ID":1,"Title":"When Harry Met Sally","ReleaseDate":"1989-01-11T00:00:00","Genre":"Romantic Comedy","Price":7.99,"Rating":"PG","Review":79.90},
{"ID":2,"Title":"Ghostbusters ","ReleaseDate":"1984-03-13T00:00:00","Genre":"Comedy","Price":8.99,"Rating":"PG","Review":94.90},
{"ID":3,"Title":"Ghostbusters 2","ReleaseDate":"1986-02-23T00:00:00","Genre":"Comedy","Price":9.99,"Rating":"15","Review":89.90},
{"ID":4,"Title":"Rio Bravo","ReleaseDate":"1959-04-15T00:00:00","Genre":"Western","Price":3.99,"Rating":"U","Review":91.90},
{"ID":5,"Title":"The Hangover","ReleaseDate":"2008-01-01T00:00:00","Genre":"Comedy","Price":9.99,"Rating":"18","Review":83.80},
{"ID":6,"Title":"Test","ReleaseDate":"2013-06-01T00:00:00","Genre":"Action","Price":10.00,"Rating":"18","Review":89.00}]
I then want to access that json in my view, and print it to my view. I have tried the following Ajax code, but I can't seem to get the json data to display.
<button id="test">Test</button>
<div class="inner"></div>
<script type="text/javascript">
$(document).ready(function () {
$('#test').on('click', function(){
$.ajax({
url: '#Url.Action("Index", "Movies")',
dataType: 'json',
context: document.body
}).done(function(serverdata) {
jsonData = serverdata;
$.each(jsonData, function(i, item) {
$(".inner").append("<p>" + jsonData + "</p>");
});
});
});
});
</script>
Any ideas? What am I doing wrong?
if we are talking about ASP.NET MVC then you can do this:
action code:
[HttpGet]
public JsonResult Index(int? PageId)
{
//other your code goes here
var movies = from m in db.Movies
select m;
return Json(new {result = movies}),JsonRequestBehavior.AllowGet);
}
client code:
$.ajax({
type: "GET",
url: '#Url.Action("Index", "Movies")',
dataType: 'json',
content: "application/json",
cache : false
}).done(function (serverdata) {
if(result.result.length > 0)
{
$.each(result.result, function(i, item) {
$(".inner").append("<p>" +"ID: "+ item.ID +", Title :" + item.Title+ "</p>");
});
}
else
{
alert("No movies in result");
}
}).fail(function (jqXHR, textStatus) {
alert("Internal server error." + "\n" + jqXHR.statusText );
});
try: -
<script type="text/javascript">
$(document).ready(function () {
$('#test').on('click', function(){
$.ajax({
url: '#Url.Action("Index", "Movies")',
method: 'GET',
dataType: 'json',
context: document.body
}).done(function(serverdata) {
var jsonData = serverdata;
$.each(jsonData, function(i, item) {
$(".inner").append("<p>" +"ID: "+ item.ID +", Title :" + item.Title+ "</p>");
});
});
});
});
</script>

why it's appending #/... in location.hash

I am using angular js for my app.
Here , My Angular code as :
var app = angular.module('TaskManager', ['ngCookies']);
app.controller('LoginController', function($scope, $http, $location, $cookieStore) {
$scope.login = function(str) {
console.log(".......... login called......");
$http({
method: 'POST',
url: '../TaskManager/public/user/login',
data: $.param({
email: email.value,
password: password.value
}),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.success(function(data, status) {
console.log(data);
var result = data.response;
console.log(result);
if (result == "success") {
//storing value at cookieStore
$cookieStore.put("loggedin", "true");
$cookieStore.put("loggedUserId", data.user_id);
$cookieStore.put("password", data.password);
$cookieStore.put("type", data.type);
$cookieStore.put("email", data.email);
location.href='Dashboard.html';
} else alert(data.message);
});
});
app.controller('DashboardController', function($scope, $http, $location, $cookieStore) {
$scope.users = [];
$http({
method: 'POST',
url: '../TaskManager/public/task/tasklist',
data: $.param({
logged_userid: userId,
password: password,
status: 'All',
user_id: useridToFetch
}),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.success(function(data, status) {
console.log(data);
$scope.users = data.users;
});
//location.hash="";
console.log(window.location);
});
It works fine but when it redirects to the dashboard page after logged in, the location.hash is being assigned with the #/PAGE_NAME. it becomes location.hash=#/PAGE_NAMEwhich results the URL value repetition.
Like:
http://localhost:8085/NovaTaskManager/Dashboard.html#/Dashboard.html
I tried to clear hash at DashboardController, Which clears for a while but as soon as the page is refreshed the earlier URL appears again.
Don't know:
1. why location.hash is getting assigned by default ?
2. How it can be resolved ?
Any suggestion would be appreciated.

Backbone - cannot traverse through object properties

I'm trying to traverse through the properties of a json file. You can see my code in http://jsfiddle.net/gerlstar/qRV7k/. In line 38, it should return the values of "name" and "age" in the console. Anyone know what im doing wrong?
var app = {};
app.model2 = Backbone.Model.extend({
defaults: {
age: '',
name: ''
}
});
app.collec = Backbone.Collection.extend({
model: app.model2,
url: 'http://echo.jsontest.com/name/betty/age/22',
parse: function (response) {
return response;
},
initialize: function () {
console.info("init ...");
this.fetch({
success: function (obj, s, jqxhr) {
// console.log(s);
},
error: function (funds) {
console.error("Error in fetch in collec");
}
});
}
});
app.model_with_collec = Backbone.Model.extend({
initialize: function(){
//console.info(this);
this.set({
my_kids: new app.collec()
});
var mo = this.get('my_kids').models;
console.log(mo);
console.log(mo.attributes);//undefined is returned
}
});
new app.model_with_collec();
If you run your code like this it will be executed sequentially and will reach the console.log before the server even respond to the rest call. So it's normal that it prints undefined.
Here the code that will print what you want :
<!DOCTYPE html>
<html>
<head>
<script src="jquery.js"></script>
<script src="underscore.js"></script>
<script src="backbone.js"></script>
<!-- /inladen bower_components -->
<script>
var app = {};
app.model2 = Backbone.Model.extend({
defaults: {
age: '',
name: ''
}
});
app.collec = Backbone.Collection.extend({
model: app.model2,
url: 'http://echo.jsontest.com/name/betty/age/22',
parse: function(response) {
return response;
},
initialize: function() {
console.info("init ...");
this.fetch({
success: function(obj, s, jqxhr) {
// console.log(s);
},
error: function(funds) {
console.error("Error in fetch in collec");
}
});
}
});
app.model_with_collec = Backbone.Model.extend({
initialize: function() {
//console.info(this);
this.set({
my_kids: new app.collec()
});
this.get('my_kids').bind('reset', this.logAttributes, this);
},
logAttributes: function() {
var mo = this.get('my_kids').models;
console.log(mo);
console.log(mo[0].attributes);
}
});
new app.model_with_collec();
</script>
</head>
</html>