Angular2 is not hitting Api - angular2-forms

Here im trying to hit my Api from ang2 why its not hitting. Even my Fiddler also not caughing traffic please check my code
constructor(private fb: FormBuilder, private _http: Http) {
_http.get('http://localhost:40039/Api/Home/GetEmp').subscribe(result => {
this.ctstArrayList = result.json();
}
)}
doSubmit(): Observable<Customer> {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this._http.post('http://localhost:40039/Api/Home/SaveEmp', JSON.stringify(this.custobj), options)
.map(this.extractData)
.catch(this.handleError);
}
This is my html code here i implement ngtoch and other some validation
Html code
<form class="form-horizontal" novalidate (ngSubmit)="doSubmit()" [formGroup]="customerForm">
<fieldset>
<div class="form-group" [ngClass]="{'has-error': (customerForm.get('EmpName').touched ||
customerForm.get('EmpName').dirty) &&
!customerForm.get('EmpName').valid }">
<label for="name">Name</label>
<input type="text" class="form-control" formControlName="EmpName" [(ngModel)]="custobj.EmpName" />
<span>Hell{{custobj.EmpName}}</span>
<span class="help-block" *ngIf="(customerForm.get('EmpName').touched ||
customerForm.get('EmpName').dirty) &&
customerForm.get('EmpName').errors">
<span *ngIf="customerForm.get('EmpName').errors.required">
Please enter your first name.
</span>
<span *ngIf="customerForm.get('EmpName').errors.minlength || customerForm.get('EmpName').errors.maxlength">
The first name must be longer than 3 and max6 characters.
</span>
</span>
</div>
<button type="submit" class="btn btn-success btn-block" (click)="doSubmit(custobj)" [disabled]="!(customerForm.valid)">Submit</button>

Related

Get object from controller to view using ajax in .net mvc core

Controller:
[HttpGet]
public IActionResult Edit(int id)
{
Teacher teacher = teacherService.GetTeacherById(id);
EditTeacherData(teacher);
return View();
}
public JsonResult EditTeacherData( Teacher teacher)
{
return Json(teacher);
}
Ajax:
$.ajax({
type: "GET",
url: "/Teacher/EditTeacherData",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (data) {
debugger;
console.log(data)
},
error: function (response) {
debugger;
alert('eror');
}
});
View:
#model StudentTeacher.Models.TeacherViewModel
#{
ViewData["Title"] = "EditTeacher";
}
<h1>EditTeacher</h1>
<h4>Teacher</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form id="AddTeacherForm">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="TeacherId" id="TeacherId" />
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control" id="Name" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Designation" class="control-label"></label>
<input asp-for="Designation" class="form-control" id="Designation" />
<span asp-validation-for="Designation" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Education" class="control-label"></label>
<input asp-for="Education" class="form-control" id="Education" />
<span asp-validation-for="Education" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="JoiningDate" class="control-label"></label>
<input asp-for="JoiningDate" class="form-control" id="JoiningDate"/>
<span asp-validation-for="JoiningDate" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Save" class="btn btn-primary" id="Submit" />
</div>
</form>
</div>
</div>
teacherService is a service that retrieves data that match with id. But it return null object. When I use this EditTeacherData(teacher); ajax not return a null object But in debugger model show value takes this function. I just wanna get an object through ajax and show data in the field via ajax.
Obviously, there is no parameter passed in to the controller in your ajax, so Edit method will never receive the parameter passed in.
You can implement it with EF core. If you want to use ajax, you can refer to this.
You can also achieve it without ajax, it much easier, please refer to this.
You are not sending data from your ajax request. Please read this for clear understanding
$('#Submit').click(function(){
var formData = $('#AddTeacherForm').serialize();
$.ajax({
type: "GET",
url: "/Teacher/EditTeacherData",
data: formData,
success: function (data) {
debugger;
console.log(data)
},
error: function (response) {
debugger;
alert('eror');
}
});
})

ionic app ajax call works in browser with "ionic serve" but not on ios device with "ionic upload"

Breaking my head on this one for 3 days already. The app works in the browser but not on the ios device. If I alert the data from the ajax call it is returned null on the ios device.
REGISTER.HTML
<div ng-controller='MainCtrl'>
<div class="list">
<span>test{{responseMessage}}</span>
<label class="item item-input item-stacked-label">
<span class="input-label">Username</span>
<input class="form-control" type="text" ng-model="username" placeholder="Username">
</label>
<label class="item item-input item-stacked-label">
<span class="input-label">Email</span>
<input class="form-control" type="text" ng-model="email" placeholder="Email">
</label>
<label class="item item-input item-stacked-label">
<span class="input-label">Password</span>
<input class="form-control" type="password" ng-model="password" placeholder="Password">
</label>
<label class="item item-input item-stacked-label">
<span class="input-label">Password retype</span>
<input class="form-control" type="password" ng-model="retypepassword" placeholder="Retype password">
</label>
<button class="button button-block button-positive" ng-click="register()">Register</button><br>
</div>
</div>
APP.JS
.controller('MainCtrl', function($scope, $ionicSideMenuDelegate, $http) {
$scope.register = function () {
var request = $http({
method: "post",
url: "https://www.dummylink.com/app/php/register.php",
data: {
username: $scope.username,
email: $scope.email,
password: $scope.password,
retypepassword: $scope.retypepassword
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded'}
});
request.success(function (data) {
$scope.responseMessage = data;
});
request.error(function (data) {
alert(data);
});
}
})
First a big thanks to tommybananas for trying to help me! Eventually the problem wasn't CORS related.
The problem was that my ssl certificate wasn't installed correctly. I removed it and installed it again. Now everything is working!

Saving data through AngularJS

Update:
I have replaced <input type=submit to <button ... and also remove the form tag from my html, after modifying my code i do not see it executing my JS and I have a debugger line in the code and it does not break....
I'm trying to POST data and I have all the code in placed and wired-up correctly (I believe) but when I try to Submit my page # My page gets refreshed, I don't see any event is firing and I have set debugger in the JS, and I do not see any JS error in developer tool
What I'm missing here apart from my code?
here is my code:
//HML code
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>My AngularJS App</title>
<script src="../AppScripts/RequesterAdd.js"></script>
</head>
<body>
<form>
<div ng-app="requesterAddModule" ng-controller="requesterAddController" class="container">
<h2> add requester</h2>
<div ng-show="ShowMessage">Record saved Successfully</div>
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>HostModel</h4>
<hr />
<div class="form-group">
<div>First Name:</div>
<div class="col-md-10">
<input type="text" ng-model="FirstName" required class="form-control input-lg" placeholder="First Name" />
</div>
</div>
<div class="form-group">
<div>Middle Name:</div>
<div class="col-md-10">
<input type="text" ng-model="MiddleName" required class="form-control input-lg" placeholder="Middle Name" />
</div>
</div>
<div class="form-group">
<div>Last Name:</div>
<div class="col-md-10">
<input type="text" ng-model="LastName" required class="form-control input-lg" placeholder="Last Name" />
</div>
</div>
<div class="form-group">
<div>eMail Address:</div>
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-envelope"></i></span>
<input type="text" ng-model="Email" required class="form-control input-lg" placeholder="Email Address" />
</div>
</div>
<div class="form-group">
<div>Is Host Active:</div>
<div class="col-md-10">
<input type="checkbox" ng-model="Active" required class="control-label col-md-2" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" id="btnCreate" data-ng-click="addRequester_ClickEvent" value="Create" class="btn btn-primary" />
</div>
</div>
</div>
<div>
#Html.ActionLink("Back to List", "Index")
</div>
</div>
</form>
</body>
</html>
//JS:
var requesterAddModule = angular.module("requesterAddModule", []);
requesterAddModule.factory('requesterAddService',
['$http', function ($http) {
return {
addRequester: function (reqesterData) {
console.log(reqesterData);
debugger;
$http({
url: 'PersistRequester',
method: 'POST',
data: reqesterData
}).then (function (response) {
if (response !== 'undefined' && typeof(response) == 'object') {
window.location.href = '/'
}
},
function(response) {
//failed
}
);
}
};
}]);
requesterAddModule.controller('requesterAddController', ['$scope', '$http', '$window', 'requesterAddService', function ($scope, $http, $window, requesterAddService) {
$scope.addRequester_ClickEvent = function () {
var req = {};
debugger;
req["FirstName"] = $scope.FirstName;
req["MiddleName"] = $scope.MiddleName;
req["LastName"] = $scope.LastName;
req["Email"] = $scope.Email;
req["Active"] = $scope.Active;
requesterAddService.addRequester(req);
}
}]);
//MVC Server side code:
[HttpPost]
public JsonResult PersistRequester(Requester requester)
{
var req = requester;
//if (ModelState.IsValid)
// {
req.CreatedDateTime = DateTime.Now;
db.Requesters.Add(requester);
db.SaveChanges();
return Json(new { Status = "Success" });
//}
}
You're using a form without a method and action which will by default post to the current url. I would highly recommend not to use a form or at least not using an <input type="submit" /> which will default in all the browsers to submit the form.
You're clearly using Bootstrap 3 here so why not just remove the form tag and the submit button and replace it with another element which will not trigger the form post and style it with class="btn btn-primary". Some could argue against this practise along the graceful degradation guidelines but since this particular form is not built from ground up to support the non-js scenario, it is best not to allow browser submit at all.
Also, in your service where you're doing the actual post, you specifically tell the page to reload.
if (response !== 'undefined' && typeof(response) == 'object') {
window.location.href = '/'
}
You should pass this data back to the viewmodel so that the view can re-render and display the response.
If you change the url, the view state is lost and the page will simply render again to the initial state.
instead line
<input type="submit" id="btnCreate" data-ng-click="addRequester_ClickEvent" value="Create" class="btn btn-primary" />
please do
<button id="btnCreate" data-ng-click="addRequester_ClickEvent()" class="btn btn-primary" >Create</button>
I've just tested and is working for me replace:
<input type="submit" id="btnCreate" data-ng-click="addRequester_ClickEvent" value="Create" class="btn btn-primary" />
with
<button id="btnCreate" data-ng-click="addRequester_ClickEvent()" value="Create" class="btn btn-primary" >submit</button>
and I've change a bit your service to :
requesterAddModule.factory('requesterAddService',
['$http', function ($http)
{
return {
addRequester: function (reqesterData)
{
console.log(reqesterData);
debugger;
$http.post('PersistRequester', reqesterData).then(function (response)
{
if (response !== 'undefined' && typeof (response) == 'object') {
window.location.href = '/'
}
},
function (response)
{
//failed
}
);
}
};
}]);
it's posting to /home/PersistRequester if method 'PersistRequester' exist in other controller ie : foo controller change
$http.post('PersistRequester', reqesterData).then(function (response)
to $http.post('foo/PersistRequester', reqesterData).then(function (response)

Can't seem to get AngularFire '$update' working

I’m pretty new to Angular, Firebase and AngularFire, so it's probable I'm going about this the wrong way.
Basically I have a form in a modal(UI Bootstrap) and I want to update some previously stored values, but AngularFire ‘$update’ doesn’t update them in Firebase. Creating and deleting items outside the modal is working fine.
This is within my service:
updateItem: function (id, item) {
var item_ref = new Firebase(FIREBASE_URL + ‘/items/‘ + user_id + '/' + id);
var item = $firebase(item_ref);
item.$update({
name: item.name,
notes: item.notes
});
}
This is within my controller:
$scope.edit = function(id) {
$modal.open({
templateUrl: 'views/item.html',
backdrop: 'static',
keyboard: false,
resolve: {
data: function() {
return {
title: 'Edit item',
item: Items.getItem(id)
};
}
},
controller: 'EditItemCtrl'
})
.result.then(function(item) {
Items.updateItem(item.$id, item);
});
};
This is my modal controller:
app.controller('EditItemCtrl', function ($scope, $modalInstance, data) {
$scope.data = data;
$scope.ok = function(item) {
$modalInstance.close(item);
};
$scope.cancel = function() {
$modalInstance.dismiss();
};
});
This is my modal template:
<div class="modal-content">
<div class="modal-header">
<button class="close" style="margin-top: -10px;" type="button" ng-click="cancel()">×</button>
<h3>{{data.title}}</h3>
</div>
<div class="modal-body">
<form name="editItem" role="form" novalidate>
<div class="form-group">
<label class="sr-only" for="itemName">Item name</label>
<input name="name" type="text" class="form-control" placeholder="Item name" value="{{data.item.name}}" ng-model="data.item.name">
</div>
<div class="form-group">
<label class="sr-only" for="itemNotes">Item notes</label>
<textarea name="notes" class="form-control" rows="2" id="itemNotes" placeholder="Notes" ng-model="data.item.notes" ng-maxlength="500">{{data.item.notes}}</textarea>
</div>
</form>
</div>
<div class="modal-footer">
<button class="btn btn-default" type="button" ng-click="cancel()">Cancel</button>
<button class="btn btn-primary" type="button" ng-click="ok(editItem.data.item)">OK</button>
</div>
</div>
Stepping through everything shows that the item to be updated and new values are being passed through to the service, but they're not making their way into Firebase.
I'm guessing that I'm probably going about this the wrong way though - any guidance would be much appreciated.

How to update password using angularjs and rails/devise?

I'm having a problem trying to update a users password using a simple form with old and new password. The problem is I post {"user[current_password]":$scope.user.password,"user[password]":$scope.user.newpassword} data to my Devise::RegistrationsController and I get a simple 422 Unprocessable Entity response. Where am I going wrong?
This is my html
<div ng-controller="PasswordCtrl">
<form id="password-card" class="row" style="display:none;" name="password_form" ng-submit="changePassword()" novalidate>
<div class="span5">
<div class="form-inputs">
<label for="nPass"><%= I18n.t("registration.edit.current_password") %></label>
<input name="uPass" class="required" type="password" ng-model="user.password" required >
<div ng-show="password_form.uPass.$dirty && password_form.uPass.$invalid">Missing:
<span ng-show="password_form.uPass.$error.required">You must provided your current password.</span>
</div>
<label for="nPass"><%= I18n.t("registration.edit.new_password") %></label>
<input name="nPass" class="required" type="password" ng-model="user.newpassword" required >
<div ng-show="password_form.nPass.$dirty && password_form.nPass.$invalid">Missing:
<span ng-show="password_form.nPass.$error.required">Tell us your new password.</span>
</div>
<button id="x" type="submit" ng-disabled="!password_form.$valid" class="button secondary prefix">Breyta</button>
</div>
</div>
</form>
</div>
This is my angular controller
var PasswordCtrl=function($scope,registrationService, $http){
$scope.changePassword=function(){
console.log("current_password",password_form.uPass.value);
$http({
method: 'PUT',
url: '/skraning.json',
headers: {'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')},
data: {"user[current_password]":$scope.user.password,"user[password]":$scope.user.newpassword}
}).
success(function(data, status, headers, config) {
console.log("done",data);
});
};
};
your data object passed is not valid( user[current_password] & user[password]) : try like this with quotes
data: {"user['current_password']":$scope.user.password,"user['password']":$scope.user.newpassword}

Resources