Create JSON object from vuejs form data - javascript

I'm trying to create a JSON object from form data on submit.
I've managed to get it working with a variable. Is there a better way to create a JSON object?
Form
<form #submit.prevent="submit">
<div class="form-group">
<label class="inputa-label" for="exampleInputEmail1"
>Email address</label
>
<input
type="email"
class="form-control inputa"
id="exampleInputEmail1"
placeholder="Enter email"
required
v-model="email"
/>
</div>
<div class="form-group">
<label class="inputa-label" for="exampleInputPassword1"
>Phone number</label
>
<input
type="number"
class="form-control inputa"
id="exampleInputPassword1"
placeholder="Phone"
v-model="phone"
/>
</div>
<div class="form-group">
<label class="inputa-label" for="exampleInputPassword1"
>Information</label
>
<textarea
class="form-control inputa"
aria-label="With textarea"
v-model="information"
></textarea>
</div>
<button
type="submit"
style="font-weight:600; padding: .8125rem 1.25rem"
class="btn btn-primary"
>
Submit
</button>
</form>
Method:
data() {
return {
email:"",
phone:"",
information:"",
};
},
methods: {
submit() {
var data = '{ "Email":"' + this.email + '" , "Phone":"' + this.phone + '", "Information":"' + this.information + '" }';
},
},
I've got it working with a variable, but I want to know if there is a better way to do this.

Answering the question, I think what you're looking for is JSON.stringify():
const data = JSON.stringify({
Email: this.email,
Phone: this.phone,
Information: this.information
})

Related

Issue posting data to api in react js

I am trying to send data to my contact form api through react but I am getting this problem
I tried to get input as a value to post through api when clicked on submit button but it is not working
error = the api should call like this https://edu.orgiance.com/api/contactus?secret=xxxxx-ac40-46a0-9c81-d48a1322f4bb&fname=test&email=test#test.com&mobile=8463274946&message=test
but it is calling like this
http://localhost:3000/?name=dfdfsd&email=dsffdsf%40gmail.com&phone=937285294&website=sxascsac&message=dscdscsfgcd#
My Code
import React from 'react';
const ContactForm = (props) => {
const { submitBtnClass } = props;
function handleClick() {
// Send data to the backend via POST
fetch('https://edu.orgiance.com/api/contactus?secret=f1794e34-ac40-46a0-9c81-d48a1322f4bb&fname=test&email=test#test.com&mobile=8463274946&message=', { // Enter your IP address here
method: 'POST',
mode: 'cors',
body: JSON.stringify(jsonData) // body data type must match "Content-Type" header
})
}
var jsonData = {
"contact": [
{
"fname": props.fname,
"email": props.email,
"mobile": props.phone,
"message": props.message
}
]
}
return (
<form id="contact-form" action="#">
<div className="row">
<div className="col-md-6 mb-30">
<input className="from-control" type="text" id="name" name="name" placeholder="Name" value={props.fname} required />
</div>
<div className="col-md-6 mb-30">
<input className="from-control" type="text" id="email" name="email" placeholder="E-Mail" value={props.email} required />
</div>
<div className="col-md-6 mb-30">
<input className="from-control" type="text" id="phone" name="phone" placeholder="Phone Number" value={props.phone} required />
</div>
<div className="col-md-6 mb-30">
<input className="from-control" type="text" id="website" name="website" placeholder="Your Website" required />
</div>
<div className="col-12 mb-30">
<textarea className="from-control" id="message" name="message" placeholder="Your message Here" value={props.message}></textarea>
</div>
</div>
<div className="btn-part" >
<button onClick={handleClick} className={submitBtnClass ? submitBtnClass : 'readon learn-more submit'} type="submit">Submit Now </button>
</div>
</form>
);
}
export default ContactForm;
It looks like you are creating a functional stateless component. That means your data needs to be passed in the props object, and if you are trying to access it anywhere in the ContactForm component, you would need to use this format: props.variablename . ie:
<input className="from-control" type="text" id="name" name="name" placeholder="Name" value={props.fname}required />
All of those variables are undefined. You can't initialize that jsonData object with variables that don't exist, you also can't set <input value={undefinedVariable} ... />
Since you are using form, an easy thing to do is to change it to look something like:
<form onSubmit={this.handleClick}>
...
<input type="submit" value="Submit" />
</form>
Then you can access the form data from the mouse event.
Example:
function handleClick(event) {
event.preventDefault();
const form = event.target;
const jsonData = {
"fname": form.name,
"email": form.email,
"mobile": form.phone,
"message": form.message
};
fetch('https://edu.orgiance.com/api/contactus?secret=f1794exxxxxx',
method: 'POST',
mode: 'cors',
body: JSON.stringify(jsonData)
})
}

express-validator receives no values

I'm using express-validator in a node app. All 4 of my form fields are returning validation errors ("A name is required" and so on). When I console.log the errors variable, all values are blank:
errors: [{value: '', msg: 'A name is required.', param: 'name', location: 'body'},...
Feedback form:
<form class="feedback-form" method="POST" action="/feedback">
<div class="form-group">
<label for="feedback-form-name">Name</label>
<input
type="text"
class="form-control"
id="feedback-form-name"
name="name"
placeholder="Enter your name"
/>
</div>
<div class="form-group">
<label for="feedback-form-email">E-Mail</label>
<input
type="text"
class="form-control"
id="feedback-form-email"
name="email"
placeholder="Enter your email address"
/>
</div>
<div class="form-group">
<label for="feedback-form-title">Title</label>
<input
type="text"
class="form-control"
id="feedback-form-title"
name="title"
placeholder="Title of your feedback"
/>
</div>
<div class="form-group">
<label for="feedback-form-message">Message</label>
<textarea
type="text"
placeholder="Enter your message, then hit the submit button"
class="form-control"
name="message"
id="feedback-form-message"
rows="6"
></textarea>
</div>
<button type="submit" class="btn btn-secondary float-right">Submit</button>
</form>
And my router:
router.post(
"/",
[
check("name").trim().isLength({ min: 3 }).escape().withMessage("A name is required."),
check("email").trim().isEmail().normalizeEmail().withMessage("A valid e-mail is required."),
check("title").trim().isLength({ min: 3 }).withMessage("A valid title is required."),
check("message").trim().isLength({ min: 3 }).withMessage("A valid message is required."),
],
(request, response) => {
const errors = validationResult(request);
console.log(errors);
if (!errors.isEmpty()) {
request.session.feedback = {
errors: errors.array(),
};
return response.redirect("/feedback");
}
return response.send("Feedback form posted");
}
);
return router;
Why aren't the form values passing to the router's post method?
You need to access form fields in request.body followed by their respective name as described in THIS post.

Unable to submit form when having Login form

I have the following code and I am unable to trigger - ng-submit or ng-click on this except local onclick function on login button. Please let me knjow if you know good solution or able to identify the problem:
<form ng-submit = "login.submitLoginForm(login.user)" novalidate>
<p>
<input class="username-email" type="email" name="username" value="" placeholder="Your Email"
ng-model="login.user.userName">
</p>
<p>
<input class="password" type="password" name="password" value="" placeholder="Password"
ng-model="login.user.pwd">
</p>
<div class="checkbox">
<label>
<input type="checkbox" value="">Remember me</label>
</div>
<p>
<button class="login" type="submit" name="Login" value="Login">Login</button>
</p>
</form>
vm.submitLoginForm = submitLoginForm;
function submitLoginForm(user) {
// submitLoginForm...
console.log("UserName..form.." + user.UserName + 'pwd..' + user.pwd);
if(user.userName != '' || user.userName != 'undefined'){
vm.user.userName = user.userName;
console.log("UserName..form.." + user.userName + vm.user.userName);
ServiceFactory.setUserName(vm.user.userName);
}
if(user.pwd != '' || user.pwd != 'undefined'){
vm.user.pwd = user.pwd;
console.log("UserName..pwd.." + user.pwd + vm.user.pwd);
ServiceFactory.setPwd(vm.user.pwd);
}
initialize();
};
'use strict';
angular
.module('app', [])
.controller('LoginCtrlr', LoginCtrlr);
function LoginCtrlr() {
var vm = this;
vm.user = {
userName: '',
pwd: ''
};
vm.submitLoginForm = function submitLoginForm(user) {
// submitLoginForm...
console.log("UserName..form.." + user.userName + ' vm userName: ' + vm.userName);
if (user.userName != '' || user.userName != 'undefined') {
vm.userName = user.userName;
console.log("UserName..form.." + user.userName + ' vm. userName: ' + vm.userName);
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<section class="container" ng-controller="LoginCtrlr as login">
<div>
<p class="or">Or</p>
<p class="login">your email</p>
<form novalidate>
<p>
<input class="username-email" type="email" name="username" value="" placeholder="Your Email" ng-model="login.user.userName">
</p>
<p>
<input class="password" type="password" name="password" value="" placeholder="Password" ng-model="login.user.pwd">
</p>
<div class="checkbox">
<label>
<input type="checkbox" value="">Remember me</label>
</div>
<p>
<button class="login" type="submit" name="Login" value="Login" ng-click="login.submitLoginForm(login.user)">Login</button>
</p>
<div>{{ login.message }}</div>
</form>
</div>
<p class="note-text-center-xs">By continuing, you accept the terms of Use and Privacy Policy</p>
<div class="login-help-center-xs">
<p>Forgot your password?
</p>
</div>
<p class="no-account" onclick="#">You Don't have an account yet? Sign up</p>
</a>
</section>
</div>
I try to create the complete code snipped. the dependency module are removed since not all could access via code snipped.
What I change:
define new 'app' module use [] (square bracket)
You need to call the controller when you're assigning a object into a model, because you define all controller's method and attribute into it self rather than using $scope. for example:
<input class="username-email" type="email" name="username" value="" placeholder="Your Email" ng-model="login.user.userName">

Autocomplete multiple fields based on one field (jQuery Autocomplete)

My JSON information:
{
"RES_ID":"2622959",
"PROP_ID":"76055",
"RES_CHECK_IN":"2015-04-21",
"RES_CHECK_OUT":"2015-04-25",
"RES_N_ADULTS":"6",
"RES_GUEST_FIRSTNAME":"Nicolas",
"RES_GUEST_LASTNAME":"Prantzos"
}
I want the RES_ID as autocomplete for the following input:
<input id="reservation_id" class="ui-autocomplete-input form-control" />
And when the input reservation_id will be filled take the rest RES_CHECK_IN and RES_CHECK_OUT and autofill them in
<input type="text" class="form-control" name="start">
<span class="input-group-addon">to</span>
<input type="text" class="form-control" name="end">
I tried to mix ajax + autocomplete do achieve that without any luck.
(function autocomplete_search() {
//this function take the #res_id input
$("#reservation_id").autocomplete({
source: "/police/get_res"
});
})();
How I show RES_ID as autocomplete and how i fill the rest of the inputs based on the RES_ID?
$("#reservation_id").kendoAutoComplete( {
dataTextField: "name",
dataSource: {
transport: {
read: {
url: "JSON File name",
serverPaging:true,
type: "POST",
data: {
json: JSON.stringify([{"name": "Karan"}, {"name": "Singh"}] )
}
}
}
}
} );
and in HTMl Side
<input id="reservation_id" />
Go : Link
or :
var data = [{
"RES_ID":"2622959",
"PROP_ID":"76055",
"RES_CHECK_IN":"2015-04-21",
"RES_CHECK_OUT":"2015-04-25",
"RES_N_ADULTS":"6",
"RES_GUEST_FIRSTNAME":"Nicolas",
"RES_GUEST_LASTNAME":"Prantzos"
}];
$("#reservation_id").autocomplete({
source: function (request, response) {
response($.map(data, function(v,i){
return {
label: v.RES_ID,
value: v.RES_GUEST_LASTNAME
};
}));
}
});
Final Fiddle :-Final
So I haven't found an easy solution for this. had to code myself.
jQuery:
(function autocomplete_search() {
//this function take the #res_id input
var ac_config = {
source: "/police/get_res",
select: function(event, ui) {
$("#reservation_id").val(ui.item.RES_ID);
$("#checkin").val(ui.item.RES_CHECK_IN);
$("#checkout").val(ui.item.RES_CHECK_OUT);
$("#firstname").val(ui.item.RES_GUEST_FIRSTNAME);
$("#lastname").val(ui.item.RES_GUEST_LASTNAME);
},
minLength: 1
};
$("#reservation_id").autocomplete(ac_config);
})();
HTML:
<div class="form-group">
<label class="col-md-3 control-label" for="inputTooltip">Firstname <span class="required">*</span>
</label>
<div class="col-md-6">
<input type="text" title="" data-toggle="tooltip" data-trigger="hover" class="form-control" data-original-title="What is your name?" id="firstname" aria-describedby="tooltip332323">
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="inputTooltip">Lastname <span class="required">*</span>
</label>
<div class="col-md-6">
<input type="text" title="" data-toggle="tooltip" data-trigger="hover" class="form-control" data-original-title="What is your Last name?" id="lastname" aria-describedby="tooltip332323">
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Checkin / Checkout:</label>
<div class="col-md-6">
<div class="input-daterange input-group" data-plugin-datepicker="">
<span class="input-group-addon"><i class="fa fa-calendar"></i></span>
<input type="text" class="form-control" id="checkin" name="checkin" value="">
<span class="input-group-addon">to</span>
<input type="text" class="form-control" id="checkout" name="checkout" value="">
</div>
</div>
</div>
Codeigniter model which generates the JSON:
function get_res($q) {
$this->db->select('RES_ID, PROP_ID, RES_CHECK_IN, RES_CHECK_OUT, RES_N_ADULTS, RES_GUEST_FIRSTNAME, RES_GUEST_LASTNAME');
$this->db->like('RES_ID', $q);
$query = $this->db->get('reservations');
if($query->num_rows() > 0){
foreach ($query->result_array() as $row){
//build an array
$row['value'] = $row['RES_ID'];
$row['label'] = "{$row['RES_ID']}";
$matches[] = $row;
}
echo json_encode($matches); //format the array into json data
exit;
}
}
Controller:
function get_res(){
if (isset($_GET['term'])){
$q = strtolower($_GET['term']);
$this->Police_model->get_res($q);
}
}
Hope It will help someone!

Meteor.call method not found

I am working my way through the Microscope project in Discover Meteor and I have hit a problem. I am getting a 'Method not found' error for the following code:
HTML Template - microscope/client/templates/posts/post_submit.html
<template name="postSubmit">
<form class="main form">
<div class="form-group">
<label class="control-label" for="url">URL</label>
<div class="controls">
<input name="url" id="url" type="text" value="" placeholder="Your URL" class="form-control"/>
</div>
</div>
<div class="form-group">
<label class="control-label" for="title">Title</label>
<div class="controls">
<input name="title" id="title" type="text" value="" placeholder="Name your post" class="form-control"/>
</div>
</div>
<input type="submit" value="Submit" class="btn btn-primary"/>
</form>
JS - microscope/client/templates/posts/post_submit.js
Template.postSubmit.events({
'submit form': function(e) {
e.preventDefault();
var post = {
url: $(e.target).find('[name=url]').val(),
title: $(e.target).find('[name=title]').val()
};
Meteor.call('postInsert', post, function(error, result) {
// display the error to the user and abort
if (error)
return alert(error.reason);
Router.go('postPage', {_id: result._id});
});
}
});
I am not sure how to debug this as I am getting no errors in the console. Please can anyone suggest where I am going wrong?
Very likely that you need to add the method postInsert to the server side. If you're following along in Discover Meteor, they do that in the next section - https://book.discovermeteor.com/chapter/creating-posts
For example, you put the method in a file called lib/collections/posts.js like this
Meteor.methods({
postInsert: function(postAttributes) {
check(Meteor.userId(), String);
check(postAttributes, {
title: String,
url: String
});

Categories

Resources