I'm trying to save an array into a JSON file that's located on a webserver.
The response is successful but when I open the JSON it's completely empty.
I've tried to create a JSON object of my own manually but it yielded same results.
Here's the process:
app.controller('BookController', ['$window', '$http', function ($window, $http) {
this.contacts = [];
this.exportContacts = function(contacts){
$http({
method: "POST",
url: '/data/contacts.json',
headers: { 'Content-Type': 'application/json' },
data: contacts
}).then(function goodCall(){
$window.alert("Save done!");
}, function badCall(){
$window.alert("Failed to save error! error: " + $http.status);
});
};
}]);
I fill the array with inputs via form:
<form name="addCont" ng-show="showForm" ng-controller="ContactController as contactCtrl" ng-submit="contactCtrl.addContact(addCont, bookCtrl.contacts)" novalidate>
<label>
First Name:
<input name="fname" type="text" required ng-pattern="/^(\D)+$/" ng-model="contactCtrl.contact.firstName"></input>
<span style="color:red" ng-show="addCont.fname.$dirty && addCont.fname.$invalid">
<span ng-show="addCont.fname.$error.required">First Name is required.</span>
<span ng-show="addCont.fname.$error.pattern">First name must contain letters only!</span>
</span>
</label>
<label>
Last Name:
<input name="lname" type="text" ng-pattern="/^(\D)+$/" ng-model="contactCtrl.contact.lastName"></input>
<span style="color:red" ng-show="addCont.lname.$dirty && addCont.lname.$invalid">
<span ng-show="addCont.lname.$error.pattern">Last name must contain letters only!</span>
</span>
</label>
<label>
Phone Number:
<input name="phone" type="tel" required ng-model="contactCtrl.contact.phone" ng-minlength="9" ng-maxlength="10" ng-pattern="/^(\d)+$/"></input>
<span style="color:red" ng-show="addCont.phone.$dirty && addCont.phone.$invalid">
<span ng-show="addCont.phone.$error.minlength">Phone number is too short!</span>
<span ng-show="addCont.phone.$error.maxlength">Phone number is too long!</span>
<span ng-show="addCont.phone.$error.required">Phone number is required!</span>
<span ng-show="addCont.phone.$error.pattern">Must not contain letters!</span>
</span>
</label>
<label>
Notes:
<input name="notes" type="text" ng-model="contactCtrl.contact.notes"></input>
</label>
<input type="submit" value="Submit" ng-disabled="addCont.fname.$invalid || addCont.lname.$invalid || addCont.phone.$invalid" />
</form>
So the array should look somethings like this:
[{
firstName: "Tim",
lastName: "asdxc",
notes: "asdasd",
phone: "0532753940"
},{
firstName: "Timz",
lastName: "asdasd",
notes: "asdasd",
phone: "123123123"
}]
Do I somehow need to parse the array before sending it?
As far as I understand your code, you are missing an important peace. You need some RESTful like service on your server. Otherwise your not able to save/write to files on your server.
I recommend you to get familiar with node and may be express for the start.
The url you give to $http should be a web service.
It will not work with a file.
You have to create a webservice who create the file on server side ( php / node.js / java ... ) and call it from $http
I think url property must be 'api/contacts':
Given that you must have a web service or web api controller: ContactsController
$http({
method: "POST",
url: 'api/contacts',
headers: { 'Content-Type': 'application/json' },
data: contacts
}).then(function goodCall(){
$window.alert("Save done!");
}, function badCall(){
$window.alert("Failed to save error! error: " + $http.status);
});
Related
Any help appreciated. I've got an app that pulls data from google books api. From each book page, the user is able to leave a review. The path to the review is /review/${isbn Number}. Each page has a path based on the isbn. The review routes work and I'm able to make the post request through insomnia/postman with no issues, I'm just having trouble with the front-end js in pulling the data from the input boxes to make the post request. I'm not sure if the issue is because the isbn being in the path. Below is my front-end javascript that I am unable to fix.
const newFormHandler = async (event) => {
event.preventDefault();
console.log("testing")
const description = document.querySelector('#description').value;
const reviewTitle = document.querySelector('#reviewTitle').value;
const isbn = window.location.search
if (description) {
const response = await fetch(`api/review/${isbn}`, {
method: 'POST',
body: JSON.stringify({ description, reviewTitle }),
headers: {
'Content-Type': 'application/json',
},
});
if (response.ok) {
document.location.reload();
} else {
alert('Failed to create review');
}
}
};
document
.querySelector('.form-group')
.addEventListener('submit', newFormHandler);
My form is below:
<div class="col form-group">
<div class ="card reviewCard" style = "background-color:#fcf8f3; color: #65625e;">
<form id="blog-form">
<div>
<label for="reviewTitle">Review Title</label>
<input
value="{{title}}"
id="reviewTitle"
name="reviewtitle"
placeholder="Enter Review Title"
type="text"
required="required"
class="form-control"
data-bv-notempty="true"
data-bv-notempty-message="The title cannot be empty"
/>
</div>
<div>
<label for="review">Review</label>
<textarea
id="description"
name="review"
cols="40"
rows="10"
required="required"
class="form-control"
>{{description}}</textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</div>
</div>
And here is my route that works fine with insomnia, no issues.
router.get('/review/:id', async (req, res) => {
try {
const isbn13 = req.params['id'];
const reviewData = await Review.findAll({ where: {
isbn:isbn13
},
include: [
{
model: User,
attributes: ['name'],
}
]
})
const reviews = reviewData.map((review) => review.get({ plain:true}));
// console.log(isbn13);
res.render('review', {
isbn: isbn13, reviews:reviews
});
} catch (err) {
console.log(err)
}
});
Any help appreciated. I tried to pull in the isbn number from the path, but with no success. I think I have it formatted wrong somehow.
First console log your req
You should see the body containing some data.
In a get request the they are arguments in the URL.
In a Psot request they are in the body of the request.
I am new to working with databases. I've been trying to create a login/register webpage using only HTML, Js and MongoDB in my codes in order to practice. I have successfully made a function for login, yet I've been struggling to create a function for registering using the Fetch API.
I am aware that my register code is used rather for a login function, but I used it as a template for the sign up one.
I'd appreciate it if anyone can help me fix the register function using Fetch() in order to not give me 401 and to be able to add the new user's email and password to my database. Thank you.
const btnAccount = document.querySelector('.account .submit')
btnAccount.addEventListener('click', event => {
event.preventDefault()
const email = emailAccount.value
const pass = passAccount.value
const pass2 = pass2Account.value
if (email && pass && pass2) {
if (pass === pass2) {
// The data i wish to add to my mongoDB users database:
const account = {
strategy: "local",
email : emailAccount.value,
password: passAccount.value
}
fetch('http://localhost:3030/authentication', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(account)
}).then(response => {
return response.json()
}).then(result => {
console.log(result)
document.forms[1].reset();
})
.catch(err => {
// If I got some errors regardings the DB or in the code itself:
console.log('eroare:', err)
alert(`Something's wrong. I can feel it!`)
})
}
else {
// Passwords not the same:
alert('Parolele nu coincid!')
}
}
else {
// Not all fields written:
alert('Completeaza bah campurile...')
}
})
<main>
<form class="account">
<div>
<label for="email">Email:</label>
<input required type="email">
</div>
<div>
<label for="password">Password:</label>
<input required type="password" class="password">
</div>
<div>
<label for="password2">Verify Password:</label>
<input type="password" class="password2">
</div>
<div>
<button class="submit">Create new account</button>
</div>
<div>
I already have an account
</div>
</form>
<button class="fetchItems">Load ITEMS</button>
<div class="output"></div>
</main>
I am trying to use the ng-template directive in my code to be able to show a div after a button click event but I cannot get it to work since I need to have the angular/common library. I tried to reference it by adding a script tag
<script src="https://cdn.jsdelivr.net/npm/#angular/common#11.0.2/bundles/common.umd.min.js" integrity="sha256-+HBVhNZwWCgkN0Z0tvWyjqjm+yI9F/szNt3Yz4/0/ws=" crossorigin="anonymous"></script>
But every time I test my app, the following error appears in the console.
common.umd.min.js:35 Uncaught TypeError: Cannot read property 'InjectionToken' of undefined
I am stuck and don't know how can I be able to use the ng-template directive
HTML (index.html):
<ng-template>
<div class="container">
<h2>Edit or Delete an Evangelist</h2>
<form name="userEditForm">
<p>person id: <input type="text" id="name" ng-model="userEdit.personid" disabled /></p>
<p>name: <input type="text" id="name" ng-model="userEdit.name" /></p>
<p>location: <input type="text" id="location" ng-model="userEdit.location" /></p>
<button id="btn-edit-evangelist" class="btn btn-primary" ng-click="editName(userEdit)">Save</button>
<button id="btn-canceledit-evangelist" class="btn btn-default btn" ng-click="delName(userEdit);">Delete User</button>
</form>
</div>
<div *ngIf="isEdit">
</div>
</ng-template>
Angular (main-app.js):
"use strict";
angular.module('MainApp', [
])
.controller("MainController", function ($scope, $http) {
//initialize scope variables
$scope.user = {
name: function (theName) {
if (angular.isDefined(theName)) {
$scope._name = theName;
}
return $scope._name;
}(),
location: function (theLocation) {
if (angular.isDefined(theLocation)) {
$scope._location = theLocation;
}
return $scope._location;
}()
};
function redirectToEdit(user) {
this.isEdit = !this.isEdit;
var id = user.personid;
$http.get('https://webapimongodb.herokuapp.com/api/name/' + id, {
params: { personid: user.personid, name: user.name, location: user.location },
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
})
.success(function (res) {
console.log(res);
$scope.userEdit.personid = res.personid;
$scope.userEdit.name = res.Name;
$scope.userEdit.location = res.Location;
});
}
})
Will it be possible to have the #angular/common module referenced via a script tag or do I need to have it referenced via NPM?
I think the issue here is the version being used.
The code you provided is written in Angular.js code and #angular/common is an Angular module
To get your code working you need this instead
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js"></script>
Here you can find the Angular.js docs, which, by the way, is deprecated.
And this article explains the difference among Angular and Angular.js
I am trying to create simple web app to receive dog adoption applications.
I succesfully run migrations and seeds and by doing so created these two tables:
The problem is that when I try to create new application using GUI, I get the below error:
{"response":"Error in database ForeignKeyViolationError: insert into applications (doggo_name, email, name, phone) values ('Coco', 'sam.do#gmail.com', 'Sam Do', '+12345667') - ER_NO_REFERENCED_ROW_2: Cannot add or update a child row: a foreign key constraint fails (dog_adoption.applications, CONSTRAINT applications_doggo_id_foreign FOREIGN KEY (doggo_id) REFERENCES doggos (id))"}
This is second day I am trying to figure out what is wrong. Please see my code:
MIGRATION FILE:
exports.up = function(knex) {
return knex.schema
.createTable('doggos', (table) => {
table.increments('id').notNullable();
table.string('doggo').notNullable();
table.integer('age').notNullable();
table.string('breed').notNullable();
table.string('picture').notNullable();
})
.createTable('applications', (table) => {
table.increments('id').notNullable();
table.string('name').notNullable();
table.string('email').notNullable();
table.integer('phone').notNullable();
table.string('doggo_name').notNullable();
table.integer('doggo_id').unsigned().notNullable();
table.foreign('doggo_id').references('doggos.id');
table.dateTime('updated_at').defaultTo(knex.raw('NULL ON UPDATE CURRENT_TIMESTAMP'));
table.dateTime('created_at').notNullable().defaultTo(knex.raw('CURRENT_TIMESTAMP'));
});
};
APPLICATION seed:
exports.seed = function(knex) {
return knex('doggos').select().then(doggos => {
return knex('applications').insert([
{ name: "xxxxxxxxx", email: "peggy33#gmail.com", phone: 79187877, doggo_name: 'Coco', doggo_id: doggos.find(doggo => doggo.doggo === 'Coco').id},
{ name: "xxxxxxxxxxxxx", email: "watson.dddk#gmail.com", phone: 51393129, doggo_name: 'Tyson', doggo_id: doggos.find(doggo => doggo.doggo === 'Tyson').id},
{ name: "xxxxxxxxxxxxx", email: "ravsp33#gmail.com", phone: 12345678, doggo_name: 'Nicky', doggo_id: doggos.find(doggo => doggo.doggo === 'Nicky').id}
]);
});
};
HTML FORM:
<form action="/apply" method="POST">
<div class="application-container">
<label for="name">What is your name?</label>
<input type="text" placeholder="Your name" name="name" required>
<label for="email">E-mail address</label>
<input type="text" placeholder="e-mail" name="email" required>
<label for="phone">Phone number</label>
<input type="text" placeholder="phone" name="phone" required>
<label for="doggo_name">Name of dog you are interested with</label>
<input type="text" placeholder="Name of dog you are interested with" name="doggo_name" required>
<button class="btn btn-primary" type="submit">Submit</button>
<button class="btn btn-primary" onclick="window.location.href='/'">Cancel</button>
</div>
</form>
</body>
ROUTE:
router.post('/apply', async (req,res) => {
const { name, email, phone, doggo_name } = req.body;
console.log(name, email, phone, doggo_name);
try {
const submittedApplication = await Application.query().insert({
name,
email,
phone,
doggo_name,
// how to pass doggo_id to the database?
});
return res.send({ response: `Succesfully applied for adoption. Please wait patiently for our response!`});
} catch (error) {
return res.send({ response: "Error in database " + error });
}
});
I would really appreciate if somebody could look at it with a fresh eye nd give me a hand with data persistence to my 'applications' table.
You make the doggo_id not nullable, so it will get 0 as default for all existing rows instead of NULL.
But then you also set it as foreign key to doggos.id. The foreign key constraint immediately fails on all rows since they would now all reference the doggo with ID 0 which presumably doesn't exist.
You can solve that problem by making it nullable (remove notNullable() from doggo_id), which works because NULL means "not referencing anything at the moment" (as opposed to "referencing the doggo with ID zero"), or by setting a default of an ID that belongs to an actually existing doggo and not zero, if that makes sense in your use case.
I am new using Angularjs and I am having an issue parsing a JSON response. I am doing client side authentication , I know it's bad practice, but I want it to learn.
HTML Code :
<form ng-submit="loginform(logcred)" class="ng-scope ng-pristine ng-valid center" name="logform"><br/><br>
<tr ng-repeat="logcred in serverinfo"></tr>
<div>
<label form="emailinput"><b>Email</b></label>
<input type="email" class="form-control" name="uname" id="emailinput" placeholder="you#example.com" ng-model="logcred.username" >
</div>
<div>
<label form="pwdinput"><b>Password</b></label>
<input type="password" class="form-control" name="pwd" id="pwdinput" placeholder="*******" ng-model="logcred.password">
</div>
<div>
<button type="cancel" class="btn" ng-click="toggle_cancel()">Cancel</button>
<button class="btn btn-primary" ng-click="submit()">Login</button>
</div>
<br/>
</form>
AngularJS :
var myApp = angular.module('myApp', []);
myApp.controller('credientials', function($scope, $http) {
/* server side response*/
$http.get('http://localhost:3000/loginfo')
.then(
function successCallback(response){
$scope.serverinfo = response.data;
});
/* client-side response*/
$scope.loginform = function(userData){
$http({
url: 'http://localhost:3000/loginfo',
method: 'POST',
data: userData
})
.then(
function successCallback(response){
if (userData.username === response.data.username && userData.password === response.data.password) {
$scope.signinfo = response.data;
}else{
console.log("Error: " + response)
}
});
}
});
Response data:
Object { username: "admin#evol.io", password: "admin" }
In the Above code I am execute a POST request on the server, specifying username and password inserted by the user. The server should check the if condition from server, to check if there are any rows with that name and password. If yes return true, if false return false. then the client should parse this response. I already fetch the response from server , but I don't know why the if condition is failing to give the response.
What am I doing wrong?
Any help / advice would be greatly appreciated.