Unable to push data into JSON file AngularJS - json

i have just started learning Angular js. I find difficulty in adding the data to an existing JSON file.
This is my JSON file
{"response":[ {
"Cust_Fname":"Jack",
"Cust_Lname":"Nicolson",
"Cust_Dob":"24/09/1992",
"Cust_Mob":"0987654321",
"Cust_Email":"abc#xyz.com"
},
{
"Cust_Fname":"tom",
"Cust_Lname":"cruise",
"Cust_Dob":"19/01/1990",
"Cust_Mob":"1234567890",
"Cust_Email":"sss#gmail.com",
}
]
}
This is my AngularJS code to push data
$scope.saveContact = function(contact){
$http.post('/data/Cust_Dtls.json',contact).success(function(data, status, headers, config){
console.log(data)});
}
This is my HTML file
<ion-content class="item-noborder base-bg" overflow-scroll="true" padding="true">
<div class="row" >
<div class="col-50 pane-top-padding-20" style="padding-left:10px"><a class="button button-icon button-positive ion-arrow-left-c" href="#/tab/contacts"> Back to Contacts</a></div>
<div class="col-50 pane-top-padding-20 text-right"><a class="button button-icon button-positive ion-checkmark text-right" href="#/tab/contacts" ng-click="saveContact(contact)"> Save</a></div>
</div>
<div id="contact-div">
<label class="item">
<span class="input-label">First Name</span>
<input type="text" placeholder="First Name" ng-model="contact.Cust_Fname">
</label>
<label class="item">
<span class="input-label">Last Name</span>
<input type="text" placeholder="Last Name" ng-model="contact.Cust_Lname">
</label>
<label class="item">
<span class="input-label">Email</span>
<input type="text" placeholder="Email" ng-model="contact.Cust_Email">
</label>
<label class="item">
<span class="input-label">Phone</span>
<input type="text" placeholder="Phone" ng-model="contact.Cust_Mob">
</label>
<label class="item">
<span class="input-label">Date Of Birth</span>
<input type="text" placeholder="DOB" ng-model="contact.Cust_Dob">
</label>
</div>
</ion-content>
I am able to read the data using $http.get but i am unable to push data and i don't have any errors popping up. so i am unable to figure on what to do.
Thanks

I think you mean the post verb of http instead of push
The format is taken from angular site:
// Simple POST request example (passing data) :
$http.post('/someUrl', {msg:'hello word!'}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
So taking your code you need to push contact like this:
$http.post('/data/Cust_Dtls',{contact:contact}).success(function(data, status, headers, config){
console.log(data)});
}
You need to post to a url instead of a json flat file.

You are doing same mistake I was doing. you trying to post data into local file using $http service.You cannot do this. $http service is for server-client communication. Use either localstorage or sqlite like services.
Hope this helps

Related

How to upload a file?

I have been trying to upload a simple image using adonisjs and the request.file() keeps on returning null.
I am pretty new to adonisjs and the documentation is not clear on what to do.
I am using a SQLite database.
This is my controller.
public async update({response, request}) {
let user = request.only(["userId","fullname","avatar"]);
const coverImage = request.file('avatar')
console.log(coverImage)
console.log(user)
if (!coverImage) {
return "Please upload File"
}
const imageName = new Date().getTime().toString()+ '.' + coverImage.subtype
await coverImage.moveAll(Application.publicPath('images'),{
name: imageName
})
user.avatar = `images/${imageName}`
await user.save()
return response.redirect(`/users/${user.userId}`)
}
This is my form that I am submitting the image with.
<form class="uk-grid-small" uk-grid method="post" action="{{ route('profiles.update', {id: user.id}) }}?_method=PUT">
<div class="uk-width-1-2#s">
<input class="uk-input" type="text" placeholder="Fullname" name="fullname">
</div>
<div class="uk-width-3-4#s">
<label>Upload user avatar</label>
<input type="file" multiple name="avatar" class="form-control">
</div>
<div class="uk-width-1-2#s">
<button class="uk-button uk-button-primary">Submit</button>
</div>
</form>
This is the route I am using
Route.resource('profiles', 'ProfilesController')
AdonisJS provides you a robust and performant API for dealing with file uploads. Not only can you process and store uploaded files locally, but you can also stream them directly to the cloud services like S3, Cloudinary, or Google cloud storage.
Accessing uploaded files
The bodyparser middleware registered inside the start/kernel.ts file automatically processes all the files for multipart/form-data requests.
You can access the files using the request.file method. The method accepts the field name and returns an instance of the File class, or null if no file was uploaded.
try this code
<form action="{{ route('posts.store') }}" method="POST" enctype="multipart/form-data">
<div class="row">
<div class="col">
<div class="custom-file">
<input type="file" class="custom-file-input" name="image_url" id="validatedCustomFile" required>
<label class="custom-file-label" for="validatedCustomFile">Choose file...</label>
<div class="invalid-feedback">Example invalid custom file feedback</div>
</div>
</div>
</div>
<button type="submit" class="btn btn-success mt-2">Submit</button>
</form>
controller
const postImage = request.file('image_url', {
size: '2mb',
extnames: ['jpg', 'png'],
})
let date_ob = new Date();
if (!postImage) {
return
}
if (!postImage.isValid) {
return postImage.errors
}
if (postImage) {
await postImage.move(Application.publicPath('postImage'), {
name: ("0" + date_ob.getDate()).slice(-2)+("0" + (date_ob.getMonth() + 1)).slice(-2)+date_ob.getFullYear()+date_ob.getHours()+date_ob.getMinutes()+date_ob.getSeconds()+date_ob.getMilliseconds()+'.'+postImage.extname,
overwrite: true, // overwrite in case of conflict
})
}

Cannot POST / With Post request from non '/' site

I am new to Node and am having trouble with the POST functionality.
I have a simple website, where I have the following lines:
app.get('/sign',(req,res)=>{
res.sendFile(path.join(__dirname, 'static', 'index.html'));
});
app.post('/sign', (req,res)=>{
res.send("Success!")
});
The get request works perfectly fine, but when I post the data in the form back, instead of getting a success message, I get Cannot POST /.
When doing the same from the '/' directory with app.get('/', etc.)
it works fine.
This is the content of the 'index.html' file:
<form action = '/' method='POST' id="form">
<div class="form-group">
<label for="emal">Email address</label>
<input type="email" class="form-control" name="email">
</div>
<div class="form-group">
<label for="pwd">Password</label>
<input type="password" class="form-control" name="password">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
The action attribute specifies the URL the form data will be posted to.
You have said to post it to /.
Your server side code provides a route for /sign but not /.
You need your URLs to match. Either change action="/" to action="/sign" to be explicit about where you are posting it to or remove the action attribute entirely so it posts to the current url (which is /sign since that is the route of the GET handler that provided the HTML document containing the form).

with a standard html form post, no body

I have this form:
<form action="/signup" method="post">
<div class="field">
<label class="label">{{ message }}</label>
</div>
<div class="field">
<label class="label">Name</label>
<div class="control">
<input class="input" type="text" placeholder="Text input" value="joe">
</div>
</div>
<div class="field is-grouped">
<div class="control">
<button class="button is-link" type="submit">Submit</button>
</div>
<div class="control">
<button class="button is-link is-light">Cancel</button>
</div>
</div>
</form>
the oak server is saying i don't have a request body.
chrome dev tools is saying i do not have any Form Data.
Can anyone see why this form would post without form data?.
Request URL: https://localhost:8000/signup
Request Method: POST
Status Code: 200 OK
Remote Address: [::1]:8000
Referrer Policy: strict-origin-when-cross-origin
Specify the name attribute for your <input> element so itself and the value associated with it can be sent as name-value pairs.
Try defining <input> element like this instead:
<input name= "text-input" class="input" type="text" placeholder="Text input" value="joe">
so the request would look like this when the input would be, for e.g "myText" (shortened for demonstration purposes):
Request URL: https://localhost:8000/signup
Request Method: POST
text-input=myText
The MDN docs provide some insight on this too, you might want to visit for clarity.

In express, is it possible to POST an array of objects without AJAX?

I am trying to submit an array of objects using a regular form, without AJAX, and am finding that instead of the request body being parsed into an array of objects it just has many fields corresponding to the names of the objects.
I know that when submitting an array of primitives, you simply fill many inputs with the same name and it will populate; however, I cannot seem to wrap my head around applying this to complex objects.
My form code is fairly straightforward:
<div class="col-sm-9">
<div class="row">
<div class="col-md-6">
<div class="form">
<div class="form-group">
<label for="attachment[0].name" class="control-label">Name</label>
<input name="attachment[0].name" class="form-control" value="First Name" type="text">
</div>
<div class="form-group">
<label for="attachment[0].uri" class="control-label">URI</label>
<input name="attachment[0].uri" class="form-control" value="First URI" type="text">
</div>
<div class="form-group">
<label for="attachment[0].description" class="control-label">Description</label>
<textarea rows="4" value="First Description" name="attachment[0].description" class="form-control">First Description</textarea>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form">
<div class="form-group">
<label for="attachment[1].name" class="control-label" >Name</label>
<input name="attachment[1].name" class="form-control" value="Second Name" type="text">
</div>
<div class="form-group">
<label for="attachment[1].uri" class="control-label">URI</label>
<input name="attachment[1].uri" class="form-control" value="Second URI" type="text">
</div>
<div class="form-group">
<label for="attachment[1].description" class="control-label">Description</label>
<textarea rows="4" name="attachment[1].description" class="form-control">Second Description</textarea>
</div>
</div>
</div>
</div>
I have made a sample repository demonstrating my issue; https://github.com/xueye/express-form-issue where you can just run node server.js, navigate to http://localhost:3000 and submit the entry; the request body will show up in your console, where it should show up as:
{ name: '',
type: '',
'attachment[0].name': 'First Name',
'attachment[0].uri': 'First URI',
'attachment[0].description': 'First Description',
'attachment[1].name': 'Second Name',
'attachment[1].uri': 'Second URI',
'attachment[1].description': 'Second Description' }
Is it possible to POST data in the way I am attempting to?
When you make a POST request, with a regular form or with JavaScript, you are sending formatted text to the server.
You can't send an array, but you can send a text representation of an array.
None of the data formats supported by forms come with a standard method to represent an array of data.
A pattern (introduced by PHP) uses square brackets to describe array-like structures.
This is similar to what you are using, except you sometimes use JavaScript style dot-notation. Switch to purely using square-brackets.
name="attachment[1][uri]"
… but you need to decode that data format on the server.
To do that in Express 4 use:
var bodyParser = require("body-parser");
var phpStyleParser = bodyParser.urlencoded({ extended: true })
and
app.post('/example', phpStyleParser, function(req, res) {
console.log(req.body);
res.json(req.body);
});

How can I modify sign-in page in Meteor Accounts-Entry package

how can I find the html and css files for the Meteor Accounts-Entry, specifically the sign-in page, so I can modify the way it looks?
Thanks!
Edit: You seem to have edited the question, the answer hence further edited :) You should open the packages folder, goto meteor accounts entry, it should have a client folder there, edit it to reflect changes.
Edit 1: Further reading on topic http://blog.benmcmahen.com/post/41741539120/building-a-customized-accounts-ui-for-meteor
You should have either use the accounts ui unstyled package or remove the accounts ui views package. The following code should work,change the design via css ofcourse. I'm using materialize.css out here.
<template name="login">
<div class="container">
<img class="responsive-img logo" src="/images/logotext.png">
<form id="login-form">
<div class="input-field">
<label for="login-email">Email</label>
<input id="login-email" type="email" class="validate">
</div>
<div class="input-field">
<label for="login-password">Password</label>
<input id="login-password" type="password" class="validate">
</div>
<button type="submit" class="waves-effect wave-light btn light-blue">
Log in
<i class="mdi-content-send right"></i>
</button>
<center><p>Don't have an account? Register here</p></center>
</form>
</div>
</template>
login.js
Template.login.events({
"submit #login-form": function (e) {
e.preventDefault();
Meteor.loginWithPassword(
{ email: $(e.target).find("#login-email").val() },
$(e.target).find("#login-password").val(),
function (error) {
if (error) {
$("#login-password").val("");
$("#login-email").select();
throwError("The email or password you entered is incorrect. Please try again.");
} else {
Router.go("whereever");
}
}
);
}