I have A front end Angular form, with Node reviving the data on the back end.
I have conditions on the from in the front end written in Angular, I would like have some extra conditions that would display with a new button to replace the submit button if the post was successful.
dose anyone know how I would do this ? I was thinking something like ng-hide/show show text and button and hide form and submit button on form completion.
Node Code
var firstFunction = function () {
var promise = new Promise(function (resolve) { // may be redundant
setTimeout(function () {
app.post('/api/data', function (req, res) {
console.log(req.body);
// Get varibles from the post form
var email_user = req.body.email;
var first_name = req.body.fname;
var last_name = req.body.lname;
// res.send(email_user);
res.send(first_name + ' ' + last_name + ' ' + email_user);
//resolve when get the response
resolve({
data_email: email_user,
data_first_name: first_name,
data_last_name: last_name
});
});
}, 2000);
});
return promise;
};
Angular code (view)
<div class="form-group">
<label for="first-name">First Name*</label>
<input type="text" class="form-control col-sm-12" name="Fname" placeholder="Enter first name"
ng-model="formData.Fname"
ng-required="true">
<span ng-if="!myForm.Fname.$invalid" class="glyphicon glyphicon-ok " style="color: green" aria-hidden="true"></span>
</div>
<div class="form-group">
<label for="first-name">Last Name*</label>
<input type="text" class="form-control col-sm-12" name="Lname" placeholder="Enter last name"
ng-model="formData.Lname"
ng-required="true">
<span ng-if="!myForm.Lname.$invalid" class="glyphicon glyphicon-ok " style="color: green" aria-hidden="true"></span>
</div>
<div class="form-group">
<label for="first-name">Email*</label>
<input type="email" class="form-control col-sm-12" name="email" placeholder="Enter valid E-mail"
ng-model="formData.email"
ng-required="true">
<span ng-if="!myForm.email.$invalid" class="glyphicon glyphicon-ok " style="color: green" aria-hidden="true"></span>
</div>
<div class="form-group row">
<div class="col-xs-6 col-xs-offset-3">
<button type="submit" class="btn btn-block btn-info"
ng-disabled="!myForm.$valid">
Submit <span class="glyphicon glyphicon-circle-arrow-right"></span>
</button>
</div>
Angular code (controller)
FirstModule.controller('formController', function ($scope, $http) {
$scope.formData = {};
$scope.processForm = function (Fname, Lname, email) {
var data = {
fname: $scope.formData.Fname,
lname: $scope.formData.Lname,
email: $scope.formData.email
};
//Call the services
//Change http://localhost:8080/api/data to /api/data when live
$http.post('http://localhost:8080/api/data', JSON.stringify(data)).then(function (response) {
if (response.data)
$scope.formData = "Post Data Submitted Successfully!";
}, function (response) {
$scope.formData = "Post Data Submitted Failed";
$scope.statusval = response.status;
$scope.statustext = response.statusText;
$scope.headers = response.headers();
});
};
});
Related
I have a simple query submission form with name, email and query fields and a component with a controller function having the submit function to submit the form.
I am using ng-submit directive in the <form></form> tag to submit the user input and display a success message on submission.
below is the code for the respective files.
contact.html
<div ngController="contactController as vm">
<div class="heading text-center">
<h1>Contact Us</h1>
</div>
<div>
<form class="needs-validation" id="contactForm" novalidate method="post" name="vm.contactForm" ng-submit="saveform()">
<div class="form-group row">
<label for="validationTooltip01" class="col-sm-2 col-form-label">Name</label>
<div class="input-group">
<input type="text" class="form-control" id="validationTooltipName" placeholder="Name" ng-model="vm.name" required>
<div class="invalid-tooltip">
Please enter your full name.
</div>
</div>
</div>
<div class="form-group row">
<label for="validationTooltipEmail" class="col-sm-2 col-form-label">Email</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text" id="validationTooltipUsernamePrepend">#</span>
</div>
<input type="email" class="form-control" id="validationTooltipEmail" placeholder="Email"
aria-describedby="validationTooltipUsernamePrepend" ng-model="vm.email" required>
<div class="invalid-tooltip">
Please choose a valid email.
</div>
</div>
</div>
<div class="form-group row">
<label for="validationTooltip03" class="col-sm-2 col-form-label">Query</label>
<div class="input-group">
<input type="text" class="form-control" id="validationTooltipQuery" ng-model="vm.query" placeholder="Query" required>
<div class="invalid-tooltip">
Please write your Query.
</div>
</div>
</div>
<div class="btn-group offset-md-5">
<button class="btn btn-primary" type="submit">Submit</button>
<button class="btn btn-default" type="button" id="homebtn" ng-click="navigate ('home')">Home</button>
</div>
</form>
<span data-ng-bind="Message" ng-hide="hideMessage" class="sucessMsg"></span>
</div>
</div>
contact.component.js
angular.module('myApp')
.component('contactComponent', {
restrict: 'E',
$scope:{},
templateUrl:'contact/contact.html',
controller: contactController,
controllerAs: 'vm',
factory:'userService',
$rootscope:{}
});
function contactController($scope, $state,userService,$rootScope) {
var vm = this;
$scope.navigate = function(home){
$state.go(home)
};
$scope.saveform = function(){
$scope.name= vm.name;
$scope.email= vm.email;
$scope.query= vm.email;
$scope.hideMessage = false;
$scope.Message = "Your query has been successfully submitted."
};
$scope.user = userService;
};
//localStorage code
function userService($rootScope) {
var service = {
model: {
name: '',
email: '',
query:''
},
SaveState: function () {
sessionStorage.userService = angular.toJson(service.model);
},
RestoreState: function () {
service.model = angular.fromJson(sessionStorage.userService);
}
}
$rootScope.$on("savestate", service.SaveState);
$rootScope.$on("restorestate", service.RestoreState);
return service;
$rootScope.$on("$routeChangeStart", function (event, next, current) {
if (sessionStorage.restorestate == "true") {
$rootScope.$broadcast('restorestate'); //let everything know we need to restore state
sessionStorage.restorestate = false;
}
});
//let everthing know that we need to save state now.
window.onbeforeunload = function (event) {
$rootScope.$broadcast('savestate');
};
};
UPDATE: On Submit, When I check the response in network tab in dev tools, I do not see the submitted values. All I see is the markup.
In your template, the name of the method is saveform:
ng-submit="saveform()"
But in your controller, it's save:
$scope.save = function() { ... }
Rename it to saveform:
$scope.saveform = function() { ... }
I have a login form and I am trying to login using a PUT method as to store the logged-in username. But for some reason it's not hitting the server and not logging in. Could you please help?
I want this to go to the login page and failing to do so. Please help
Below is the code for the same:
HTML:
<form name="login" class="login-form request-form form-horizontal" method="post" id="login-user">
<p class="pl-sign">Please Sign In</p>
<div class="form-group" id="login-fields">
<div class="cols-sm-10">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-user fa" aria-hidden="true"><span class="text--white glyphicon glyphicon-user"></span></i>
</span>
<input type="text" name="user" id="user" placeholder="Username" class="form-control" required/>
</div>
</div>
</div>
<div class="form-group" id="login-fields">
<div class="cols-sm-10">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-user fa" aria-hidden="true"><span class="text--white glyphicon glyphicon-lock"></span></i>
</span>
<input type="password" name="pass" id="pass" placeholder="Password" class="form-control" required/>
</div>
</div>
</div>
<input class="view sign-in-app" type="submit" value="Sign In" id="submit-login" />
<div class="forgot-up">
forgot username/password ?
</div>
</form>
jQuery:
$("#login-user").validate({
submitHandler: userLogin
});
function userLogin() {
var username = $('#user').val();
var password = $('#pass').val();
var data = $("#login-user").serialize();
var userUrl = 'http://website.com/DatabaseName/Tablename/' + username + '/login?' + password + '';
console.log(data);
$.ajax({
url: userUrl,
type: 'PUT',
data: data,
success: function(data) {
if (data == 0) {
window.location.href = "http://website.com/page2.html";
} else if (data == -1) {
("#error").html('<span class="error">Incorrect username or password</span>');
} else {
$("#error").fadeIn(1000, function() {
$("#error").html('<div class="alert alert-danger"><span class="glyphicon glyphicon-info-sign"></span> ' + data + ' !</div>');
});
}
}
});
}
If you don't want a form submit to laod a new page (or relaod the current one if action isn't defined in the form), use preventDefault() method on the passed in event to the event handler
function userLogin(e) {
e.preventDefault();
... rest of your code
I'm assuming
submitHandler: userLogin
in the validate object will pass on the event object
In the code below when I click edit the other boxes loose the edited icon until cancel is clicked.
Is there away that I can have it so that if a box is not being edited it keeps the normal state of code?
The library I am using is: https://vitalets.github.io/x-editable/
Normal State:
When an edit button is clicked:
jQuery:
/* X-Editable */
$(function(){
$.fn.editable.defaults.mode = 'inline';
$.fn.editable.defaults.params = function (params) {
params._token = $("#_token").data("token");
return params;
};
var dataURL = $('.updateField').data('url');
var inputName = $('.updateField').attr("name");
$('.updateField').editable({
type: 'text',
url: dataURL,
name: inputName,
placement: 'top',
title: 'Enter public name',
toggle:'manual',
send:'always',
ajaxOptions:{
dataType: 'json'
}
});
$('.edit').click(function(e){
var container = $(this).closest('.input-group'); // !!
var input = container.find('.updateField');
var inputName = input.attr('name');
var dataURL = input.data('url');
console.log(inputName);
e.stopPropagation();
container.find('.updateField').editable('toggle'); // !!
container.find('.edit').hide(); // !!
});
$(document).on('click', '.editable-cancel, .editable-submit', function(e){
$(e.target).closest('.input-group').find('.edit').show(); // !!
})
//ajax emulation. Type "err" to see error message
$.mockjax({
url: '/post',
responseTime: 100,
response: function(settings) {
if(settings.data.value == 'err') {
this.status = 500;
this.responseText = 'Validation error!';
} else {
this.responseText = '';
}
}
});
});
Normal State HTML:
<input name="__RequestVerificationToken" type="hidden" value="{{ csrf_token() }}" />
<div class="box-body">
<div class="form-group">
<label class="col-sm-2 control-label" for="siteName">Website Name</label>
<div class="col-sm-3">
<div class="input-group">
<input class="form-control updateField" data-url="{{ route('generalDataSubmit', 1)}}" data-title="Website Name" name="siteName" placeholder="Email" type="input" value="{{ old('siteName', $siteSettingsData->siteName)}}"> <span class="input-group-btn"><button class="btn btn-default edit" type="button"><span class="glyphicon glyphicon glyphicon-pencil"></span></button></span>
</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label" for="siteEmail">Website E-Mail Address</label>
<div class="col-sm-3">
<div class="input-group">
<input class="form-control updateField" data-url="{{ route('generalDataSubmit', 1) }}"data-title="Website E-Mail Address" name="siteEmail" placeholder="Site E-Mail" type="email" value="{{ old('siteEmail', $siteSettingsData->siteEmail) }}"> <span class="input-group-btn"><button class="btn btn-default edit" type="button"><span class="glyphicon glyphicon glyphicon-pencil"></span></button></span>
</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label" for="siteCopyright">Website Copyright</label>
<div class="col-sm-3">
<div class="input-group">
<input class="form-control updateField" data-url="{{ route('generalDataSubmit', 1)}}" data-title="Website Copyright" name="siteCopyright" placeholder="Site Copyright" type="input" value="{{ old('siteCopyright', $siteSettingsData->siteCopyright)}}"> <span class="input-group-btn"><button class="btn btn-default edit" type="button"><span class="glyphicon glyphicon glyphicon-pencil"></span></button></span>
</div>
</div>
</div>
</div>
<!-- /.box-body -->
try changing the following line:
container.find('.edit').hide();
to
$(this).hide();
It seems like you are using some bootstrap design template.From my point of view the code
$('.edit').click(function(e){
var container = $(this).closest('.input-group'); // !!
var input = container.find('.updateField');
var inputName = input.attr('name');
var dataURL = input.data('url');
console.log(inputName);
e.stopPropagation();
container.find('.updateField').editable('toggle'); // !!
container.find('.edit').hide(); // !!
});
seems ok.I don't understand the line container.find('.updateField').editable('toggle'); // !! in the function.Are you using some kind of library. My suggestion is to remove that line from your code and test.Also check whether you are getting the correct value of inputName outputted.And finally check in the console for any errors when you click the edit button.
Try using $(e) instead of $(this) in the following code:
$('.edit').click(function(e){
//var container = $(this).closest('.input-group');
var container = $(e).closest('.input-group');
var input = container.find('.updateField');
var inputName = input.attr('name');
var dataURL = input.data('url');
console.log(inputName);
e.stopPropagation();
container.find('.updateField').editable('toggle'); // !!
container.find('.edit').hide(); // !!
});
I am creating a Json object. Inside that I am creating an array, the array will push some fields dynamically when user clicks add buttons, I want to store the dynamic fields values in scope variable called table and passing that to submit() function, so when the user clicks the save button it calls the submit() function, where it send that field values to node using $http.
The values which is sent to node js server is not inserting in tables
HTML
<form ng-controller="NewTableCtrl" ng-app="myApp" name="frm" class="form-inline" ng-submit="submitTable()">
<input type="string" name="cat_name" class="form-control" ng-model="table.cat_name" placeholder="Enter Category Name" ng-pattern="/^[a-zA-Z]*$/" required>
<input type="text" name="cat_desc" class="form-control" ng-model="table.cat_desc" placeholder="Enter Your Description" ng-pattern="/^[a-zA-Z]*$/" required>
<input type="disable" class="form-control" name="count" ng-model="table.fields.length">
<fieldset ng-repeat="field in table.fields track by $index" >
<input type="text" ng-model="table.fields[$index].item_name" class="form-control" name="item_name" placeholder="Category Item Name" ng-pattern="/^[a-zA-Z]*$/" required>
<input type="text" ng-model="table.fields[$index].item_desc" class="form-control" name="item_desc" placeholder="Category Item Description" ng-pattern="/^[a-zA-Z]*$/" required>
<input type="number" ng-model="table.fields[$index].item_count" class="form-control" name="item_count" ng-pattern="/^[0-9]/" placeholder="Category Item View Count" required>
<div class="form-group move-down">
<label for="Autocomplete">Generic Autocomplete</label>
<input type="text" id="Autocomplete" class="form-control" ng-autocomplete="table.fields[$index].result1" details="details1" options="options1"/>
</div>
<span class="help-block well" ng-show="frm.item_count.$error.pattern">numbers only allowed</span>
<button ng-click="removeChoice()" class="remove btn btn-danger" >close</button>
</fieldset>
<!-- <button ng-click="removeChoice()" >close</button> -->
<div>
<button class="addfields btn btn-success" ng-disabled="!frm.cat_name.$dirty||!frm.cat_desc.$dirty||frm.cat_desc.$invalid||frm.cat_name.$inavalid||!frm.item_name.$dirty||frm.item_name.$invalid||!frm.item_desc.$dirty||frm.item_desc.$invalid||!frm.item_count.$dirty||frm.item_count.$invalid" ng-click="submit(table)">Save</button>
<button class="addfields btn btn-success" ng-click="addFormField()" ng-disabled="!frm.cat_name.$dirty||!frm.cat_desc.$dirty||frm.cat_desc.$invalid||frm.cat_name.$inavalid">Add fields</button>
</div>
<span class="help-block" class="well" style="color:red" ng-show="frm.cat_desc.$error.pattern">ERROR:<BR/>text only allowed</span >
<span class="help-block" class="well" style="color:red" ng-show="frm.cat_name.$error.pattern">ERROR:<BR/>text only allowed</span >
<span class="help-block" style="color:red" ng-show="frm.item_desc.$error.pattern">ERROR:<BR/>text only allowed</span >
<span class="help-block" style="color:red" ng-show="frm.item_name.$error.pattern">ERROR:<BR/>text only allowed</span >
<pre>{{ table | json }}</pre>
</form>
Angular Code
var app = angular.module('myApp', ['ngAutocomplete']);
app.controller('NewTableCtrl', function($scope,$http) {
var counter=0;
$scope.table = { fields: [] };
$scope.addFormField = function() {
$scope.table.fields.push('');
}
$scope.submitTable = function() {
console.log($scope.table);
}
$scope.removeChoice = function() {
$scope.table.fields.splice(this.$index,1);
};
$scope.result1 = '';
$scope.options1 = null;
$scope.details1 = '';
$scope.details3 = '';
$scope.submit=function(category){
$http({method:"post",url:"http://localhost:3000/insert",data:category})
.then(function(data){
/* Success callback */
alert("Data hase been entered!");
// console.log("success");
},function(err){
/* Failure callback */
alert("Something went wrong!");
});
}
});
Node
var mysql=require('mysql');
var http=require('http');
var uuid = require('node-uuid');
var path=require('path');
var express=require('express');
var app=express();
var bodyparser=require('body-parser');
app.use(bodyparser.json());
app.use(bodyparser.urlencoded({extended: true}));
var myconnection = mysql.createConnection({
host : "localhost",
user : "root",
password : "",
database : "siva"
});
app.use(express.static(__dirname + ""));
var uqid= uuid.v1();
var it_id=uuid.v4();
var tt=1;
var status="active";
app.post("/insert",function(req,res){
console.log(req.body);
/* TODO: Now just check that your drive function is correct, SQL is correct and whether what arguements passed to SQL callback is correct */
myconnection.query('Insert into cate_tbl (cat_id,cat_name,cat_desc,cat_view_count,cat_status) VALUES ("'+uqid+'","'+req.body.cat_name+'","'+req.body.cat_desc+'","'+tt+'","'+status+'")',function(err, results, fields) {
//if (err) throw err;
if (err) {console.log("DB Error"+err); res.send("add failed"+err);}
else res.send("add success");
});
myconnection.query('Insert into cate_item (cat_it_id,cat_it_name,cat_pid,cat_it_count,cat_it_desc,cat_it_status) VALUES ("'+it_id+'","'+req.body.item_name+'","'+uqid+'","'+req.body.tem_count+'","'+req.body.item_desc+'","'+status+'")',function(err, results, fields) {
//if (err) throw err;
if (err) {console.log("DB Error"+err); res.send("add failed"+err);}
else res.send("add success");
});
});
app.get('/',function(req,res){
res.sendfile("index.html");
});
app.listen(3000,function(){
console.log("It's Started on PORT 3000");
})
I have this textarea in my MVC project
<textarea id="edit-content" name="content" placeholder="Text content goes here">#Model.content</textarea>
but when I try to send this to a Json call like this
<script type="text/javascript">
function save() {
var $title = $('#edit-title'),
$content = $('#edit-content'),
$messageLoading = $('#message-edit-loading'),
$messageError = $('#message-edit-error'),
$id = $('#edit-id');
updateComment($id.val(), $title.val(), $content.val())
.done(function (data) {
if (data.IsValid()) {
$messageError.html('');
$messageError.removeClass('hidden');
$messageLoading.removeClass('hidden');
$messageLoading.html('The text is saved');
} else {
$messageError.removeClass('hidden');
$messageError.html(data.Message);
}
})
.fail(function (xhr, message) {
$messageError.removeClass('hidden');
$messageError.html('Registration failed: ' + message);
})
};
</script>
I get the original value of #Model.content instead of the new value.
Edit
my script.js code
function updateComment(id, title, content) {
return $.get("/Chapter/GetJSON_Update",
{
id: id,
title: title,
content: content
},
'json');
};
the entire code from my Edit.cshtml
#model Academia_Unitate.Models.Chapter
#{
ViewBag.Title = "Edit " + Model.title;
Layout = "~/Views/Shared/_Layout.cshtml";
}
#Html.Partial("~/Views/Shared/_TinyMCE.cshtml")
<div id="edit">
<h1>
Edit #Model.type.name
</h1>
<div class="" role="form">
<div class="form-group">
<label class="sr-only" for="title">Title</label>
<input class="form-control" type="text" id="edit-title" placeholder="Enter a title" value="#Model.title" required="required" />
</div>
<div class="form-group">
<label class="sr-only" for="content">Content</label>
<textarea id="edit-content" name="content" placeholder="Text content goes here">#Model.content</textarea>
</div>
<button type="submit" class="btn btn-success" id="save-btn" onclick="save()"><span class="glyphicon glyphicon-ok"></span> Save</button>
<span id="message-edit-loading" class="alert hidden"></span>
<span id="message-edit-error" class="alert alert-danger hidden"></span>
</div>
</div>
<input type="hidden" value="#Model.id" id="edit-id"/>
<script type="text/javascript">
function save() {
var $title = $('#edit-title'),
$content = $('#edit-content'),
$messageLoading = $('#message-edit-loading'),
$messageError = $('#message-edit-error'),
$id = $('#edit-id');
updateComment($id.val(), $title.val(), $content.val())
.done(function (data) {
if (data.IsValid()) {
$messageError.html('');
$messageError.removeClass('hidden');
$messageLoading.removeClass('hidden');
$messageLoading.html('The text is saved');
} else {
$messageError.removeClass('hidden');
$messageError.html(data.Message);
}
})
.fail(function (xhr, message) {
$messageError.removeClass('hidden');
$messageError.html('Registration failed: ' + message);
})
};
</script>
You most likely have more than one on your page, either make their id attributes unique or target the index in your jQuery.