User is not defined Angular js - javascript

i have a problem when i click in the button it give me an error that user is not defined
i don't know what the problem
<input type="button" class="btn btn-danger" value="Active"
ng-click="Active(User)" />
this is my function in page Controller Asp MVC :
public string Active(AspNetUser User)
{
if (User == null) return "User Not Updated! Try Again";
var userToUpdate = db.AspNetUsers.Where(x => x.Id == User.Id).FirstOrDefault();
if (userToUpdate == null) return "User Not Found.";
if (userToUpdate.IsActive == true)
{
userToUpdate.IsActive = false;
}
else
{
if (userToUpdate.IsActive == false)
{
userToUpdate.IsActive = true;
}
db.SaveChanges();
return "User successfully Changed";
}
return "User already changed";
}
and this is my Script :
$scope.Active = function() {
$http({
method: "post",
url: "http://localhost:61484/AspNetUsers/Active",
datatype: "json",
data: JSON.stringify(User)
}).then(function(response) {
alert(response.data);
$scope.GetAllData();
})
};

You are not passing anything to the function $scope.Active. Pass the User:
$scope.Active = function(User) {...}

The datatype property is ignored by the AngularJS framework. Also it is not necessary to stringify JavaScript objects. The AngularJS framework does that automatically.
$scope.Active = function(user) {
$http({
method: "post",
url: "http://localhost:61484/AspNetUsers/Active",
̶d̶a̶t̶a̶t̶y̶p̶e̶:̶ ̶"̶j̶s̶o̶n̶"̶,̶
̶d̶a̶t̶a̶:̶ ̶J̶S̶O̶N̶.̶s̶t̶r̶i̶n̶g̶i̶f̶y̶(̶U̶s̶e̶r̶)̶
data: user
}).then(function(response) {
alert(response.data);
$scope.GetAllData();
})
};
For more information, see
AngularJS $http Service API Reference

Related

Why Ajax edit code not work properly? can you help me?

I m working on simple registration i have two forms one is registration another is city, When city is newly added it get added update perfectly but when i use city in registration form eg pune. pune will not get edited or updated, code written in ajax
function UpdateCity(Ids) {
debugger;
var Id = { Id: Ids }
$('#UpdateModel').modal('show');
$.ajax({
type: 'GET',
url: "/City/GetCityDetail",
data: Id,
dataType: "json",
success: function (city) {
$('#EditCityName').val(city.CityName);
$('#EditCityId').val(city.CityId);
}
})
$('#UpdateCityButton').click(function () {
var model = {
CityName: $('#EditCityName').val(),
CityId: $('#EditCityId').val()
}
debugger;
$.ajax({
type: 'POST',
url: "/City/UpdateCity",
data: model,
dataType: "text",
success: function (city) {
$('#UpdateModel').modal('hide');
bootbox.alert("City updated");
window.setTimeout(function () { location.reload() }, 3000)
}
})
})
}
Controller
public bool UpdateCity(City model, long CurrentUserId)
{
try
{
var city = db.Cities.Where(x => x.CityId == model.CityId && x.IsActive == true).FirstOrDefault();
if (city == null) return false;
city.CityName = model.CityName;
city.UpdateBy = CurrentUserId;
city.UpdateOn = DateTime.UtcNow;
db.SaveChanges();
return true;
}
catch (Exception Ex)
{
return false;
}
}
A few stabs in the dark here but, try changing your code to the following (with comments).
Controller:
// !! This is a POST transaction from ajax
[HttpPost]
// !! This should return something to ajax call
public JsonResult UpdateCity(City model, long CurrentUserId)
{
try
{
var city = db.Cities.Where(x => x.CityId == model.CityId && x.IsActive == true).FirstOrDefault();
if (city == null) return false;
city.CityName = model.CityName;
city.UpdateBy = CurrentUserId;
city.UpdateOn = DateTime.UtcNow;
db.SaveChanges();
// !! Change return type to Json
return Json(true);
}
catch (Exception Ex)
{
// !! Change return type to Json
return Json(false);
}
}
Script:
function UpdateCity(Ids) {
//debugger;
var Id = { Id: Ids };
$('#UpdateModel').modal('show');
$.ajax({
type: 'GET',
url: "/City/GetCityDetail",
data: Id,
dataType: "json",
success: function (city) {
$('#EditCityName').val(city.CityName);
$('#EditCityId').val(city.CityId);
},
error: function () {
// !! Change this to something more suitable
alert("Error: /City/GetCityDetail");
}
});
$('#UpdateCityButton').click(function () {
var model = {
CityName: $('#EditCityName').val(),
CityId: $('#EditCityId').val()
};
//debugger;
$.ajax({
type: 'POST',
url: "/City/UpdateCity",
data: model,
// !! Change return type to Json (return type from Server)
dataType: "json",
success: function (city) {
// !! Check result from server
if (city) {
$('#UpdateModel').modal('hide');
bootbox.alert("City updated");
// !! Why reload location?
// window.setTimeout(function () { location.reload(); }, 3000);
} else{
// !! Change this to something more suitable
alert("Server Error: /City/UpdateCity");
}
},
error: function () {
// !! Change this to something more suitable
alert("Error: /City/UpdateCity");
}
});
});
}
This should give you some more clues as to what's going on.

How can i use RedirectToAction within $.ajax POST?

I'm trying to redirect with the following method of the controller:
[HttpPost]
public async Task<IActionResult> CreateSchedinaB([FromBody]ListAssociazioni listAss)
{
var userr = await _manager.GetUserAsync(User);
var listSchedine = await _context.Schedine.ToListAsync();
List<Associazioni> listAssocia = new List<Associazioni>();
Schedine schedina = new Schedine();
bool doppione = false;
foreach (var item in listSchedine)
{
if (listAss.NomeS == item.Nome)
{
doppione = true;
}
}
if (doppione == false)
{
schedina.Nome = listAss.NomeS;
schedina.KsProfile = userr.ProfileId;
schedina.Id = _context.Schedine.Count() + 1;
_context.Schedine.Add(schedina);
}
else
{
ViewData["Success"] = "Data was saved successfully.";
return RedirectToAction("Index");
}
foreach (var item in listAss._listAssoc)
{
var giocata = _context.Giocate.Where(c => c.Id == item.KsGiocata).First();
var partita = _context.Calendario.Where(c => c.Id == item.KsPartita).First();
Associazioni tmp = new Associazioni { KsGiocataNavigation = giocata, KsPartitaNavigation = partita, KsSchedinaNavigation = schedina };
_context.Associazioni.Add(tmp);
}
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
I don't call the method with an asp-action in the view but with in $.ajax post in this way:
-VIEW:
`<div class="form-group">
<label asp-for="schedine.Nome" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input id="nomeSchedina" asp-for="schedine.Nome" class="form-control" />
<span asp-validation-for="schedine.Nome" class="text-danger"></span>
</div>
</div>
<a class="btn btn-default" onclick="InviaServer()" >CREA</a>`
-JS:
function InviaServer() {
var Nomes = $("#nomeSchedina").val();
if (Nomes == "" || Nomes == null) {
window.alert("Dai un nome alla tua schedina!");
return;
}
var listadef = {"NomeS": Nomes, "_listAssoc": json};
$.ajax({ // Send list to controller
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
url: "/Logged/CreateSchedinaB/",
type: "POST",
data: JSON.stringify(listadef),
success: function (response) {
console.log(response);
}
});
}
CONTROLLER - INDEX
[HttpGet]
public IActionResult Index()
{
return View();
}
The problem is that the method does not redirect to the page but sends the page in the browser console ... why?
Sorry my english ... I'm an "absolute beginner"
When you make an Ajax call, you are responsible to handle the response from server. For your case you can something like following.:
[HttpPost]
public ActionResult DoSomeStuffAndRedirect()
{
//Do some stuff you want
return Json(Url.Action("Contact"), JsonRequestBehavior.AllowGet);
//Note: Url.Action(...) would give you fully qualified url based on to an action and it adheres to the defined route templates.
}
On Client side you can do:
$.ajax({ // Send list to controller
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
url: "/Home/DoSomeStuffAndRedirect/",
type: "POST",
data: {},
success: function (response) {
location.href = response;
}
});
Hope this give you some idea to start with.
You do an ajax call, it cannot redirect you to something else.
You need to use something like this in ajax success:
success: function (response) {
document.location = '/Logged/index/';
}
Also in a backend method CreateSchedinaB don't redirect (it is usless, just return something to your ajax method response, for example about results for redirect, or errors)

AngularJS Http Post - 500 Internal Server Error

I know there's a lot of other 500 (Internal Server Error) questions out there, but reading them is still not helping my case.
I am working on two angularjs methods that have $http post calls in them.
FIRST PROBLEM
The first successfully hits the server-side controller, and returns a JSON object as I expect it, but my drop downs are not being filled by the result of the factory call.
One thing that concerns me, is the console output. (As you'll see in the code below I have several print statements.) The URL is printed, and then my drop down options field is printed as undefined, and then the response from the server comes back with the response. Do I need to tell the JS to wait for the response? Some sort of ASYNC?
SECOND PROBLEM
I have the exact same http post method call (but with new variables), and I get the 500 (Internal Server Error) error message. The server-side ctrl method is not being hit for this call (based on break point in ctrl).
Questions
How do I fill my drop down successfully with the result of the
$http.post call?
Why is my second $http.post method creating the 500 (Internal Server Error)?
Javascript
'use strict';
var app = angular.module('LineModule', ['ngMaterial']);
app.controller("LineCtrl", ['$scope', '$http', 'LineService',
function ($scope, $http, LineService) {
$scope.Types = LineService.get_DropDownList("Type");
console.log("Types:"); console.log($scope.Types);
$scope.Statuses = LineService.get_DropDownList("Status");
$scope.FundingSources = LineService.get_DropDownList("Funding_Source");
...
$scope.get_DeptLeader = function () {
$scope.SelectedLeader = LineService.get_DeptLeader($scope.CPOC_Title, $scope.CostCenter_ID);
};
}]);
app.factory('LineService', ["$http", function ($http) {
return {
...
***FIRST METHOD***
get_DropDownList: function (field) {
var info = {
section: 'Line',
field: field
};
var URL = getBaseURL() + 'DBO/DropDown_GetList';
console.log(URL);
var DropDown;
$http({
method: 'POST',
url: URL,
data: JSON.stringify(info),
})
.then(function (response) {
if (response !== 'undefined' && typeof (response) == 'object') {
DropDown = response.data;
console.log(DropDown);
return DropDown;
}
else {
console.log('ERROR:');
console.log(response);
return 'No Options Found';
}
});
},
***SECOND METHOD***
get_DeptLeader: function (CPOC_Title, CostCenter_ID) {
console.log("call get leader");
if (CPOC_Title < 1 || CPOC_Title == undefined) { return "No Title Selected"; }
if (CostCenter_ID < 1 || CostCenter_ID == undefined) { return "No Cost Center Selected"; }
console.log(CPOC_Title);
console.log(CostCenter_ID);
var info = {
Leader_ID: CPOC_Title,
CostCenter_ID: CostCenter_ID
};
var URL = getBaseURL() + 'DBO/DeptLeader_GetCurrent';
console.log(URL);
var DeptLeaders;
$http({
method: 'POST',
url: URL,
data: JSON.stringify(info),
})
.then(function (response) {
if (response !== 'undefined' && typeof (response) == 'object') {
DeptLeaders = response.data;
console.log(DeptLeaders);
return DeptLeaders;
}
else {
console.log('ERROR:');
console.log(response);
return 'No Options Found';
}
});
},
};
}]);
DBO Controller: Server-Side
[HttpPost]
public JsonResult DeptLeader_GetCurrent(string Leader_ID, string CostCenter_ID)
{
try {
List<SelectListItem> DL = DB.DeptLeader_GetByIDs(Leader_ID, CostCenter_ID);
return Json(DL, JsonRequestBehavior.AllowGet);
}
catch (Exception e){
string error = e.ToString();
return null;
}
}
[HttpPost]
public JsonResult DropDown_GetList(Sections section, DropDownFields field)
{
return Json(DB.GetDropDownValues(section, field), JsonRequestBehavior.AllowGet);
}
CSHTML
<div ng-app="LineModule" ng-controller="LineCtrl" class="container col-md-12">
...
<select ng-model="Type_ID" class="form-control" required>
<option ng-value="T.Value" ng-repeat="T in Types">{{T.Text}}</option>
</select>
...
<select ng-model="CPOC_Title" class="form-control" ng-change="get_DeptLeader()">
<option ng-value="D.Value" ng-repeat="D in DeptLeaders">{{D.Text}}</option>
</select>
{{SelectedLeader}}
...
</div>

AJAX call in external JavaScript file not reaching ActionResult in controller

I am trying to check if an email address exists in the database. I have an external JavaScript file that I am using to call my jQuery (to keep my view clean). Perhaps it is because I am running with SSL enabled? (I am using https)
Function in external js file:
function checkemail() {
var email = $("#email").val();
$.ajax({
url: "/Account/CheckEmailExists/",
data: JSON.stringify({ p: email }),
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data)
}
});
}
Action in Controller:
public ActionResult CheckEmailExists(string p)
{
bool bEmailExists = false;
using (RBotEntities EF = new RBotEntities())
{
var query = (from U in EF.AspNetUsers
where U.Email == p
select U).FirstOrDefault();
if(query.Email != null)
{
bEmailExists = true;
}
else
{
bEmailExists = false;
}
}
return Json(bEmailExists, JsonRequestBehavior.AllowGet);
}
I seem to be getting an error stating the following:
XML Parsing Error: no root element found Location:
https://localhost:44347/Account/CheckEmailExists/ Line Number 1,
Column 1:
My understanding would be that this ActionResult does not exist. But it does ?
Am I doing something wrong, or is there a reason why an ActionResult can not be called via an external JavaScript file ?
Try this
In Controller
[httppost]
public ActionResult CheckEma.........
In JS
function checkemail() {
var email = $("#email").val();
$.ajax({
url: "/Account/CheckEmailExists/",
data: { p: email },
type: "POST",
success: function (data) {
alert(data)
}
});
}
No need for Json.Stringify and ContentType here
function checkemail() {
var email = $("#email").val();
$.ajax({
url: "/Account/CheckEmailExists",
data: { p: email },
type: "POST",
success: function (data) {
alert(data)
}
});
}
So I found out what was causing the issue...
Above my Action result, I needed to add [AllowAnonymous] data annotation and then it reached my ActionResult! I would prefer to not allow anonymous, but it works and I wanted to share this in case it helps someone else. Below is my code:
ActionResult:
[AllowAnonymous]
public ActionResult CheckEmailExists(string p)
{
bool bEmailExists = false;
using (RBotEntities EF = new RBotEntities())
{
var query = (from U in EF.AspNetUsers
where U.Email == p
select U).FirstOrDefault();
if (query.Email != null)
{
bEmailExists = true;
}
else
{
bEmailExists = false;
}
}
return Json(bEmailExists, JsonRequestBehavior.AllowGet);
}
JavaScript function in JavaScript File:
function checkemail() {
var email = $("#email").val();
var bReturnedValue = false;
$.ajax({
url: "/Account/CheckEmailExists/",
data: { p: email },
async: false,
success: function (data) {
if(data)
{
bReturnedValue = true;
}
else
{
bReturnedValue = false;
}
}
});
return bReturnedValue;
}
And this is how I initiated it(I am doing a popover to specify that the email exists):
$("#createacc_next").click(function () {
var bEmailExists = false;
bEmailExists = checkemail();
if (bEmailExists) {
$("#email").attr("disabled", false).css("border-color", "red");
$('#email').popover({ title: 'Attention', content: 'Email address already exists', placement: 'top', trigger: 'focus' });
Email_Validation_Passed = false;
}
})

Laravel 5.3 AJAX login doesn't redirect

I have similar issue like this one.
I'm trying to make AJAX login using Laravel 5.3 Auth.
Here's what I got so far:
var login = function()
{
var data = {};
data["email"] = $('#email').val();
data["password"] = $('#password').val();
if($('#remember').is(':checked'))
data["remember"] = "on";
$.ajax({
type: "POST",
url: '/login',
data: JSON.stringify(data),
// data: data,
headers : { 'Content-Type': 'application/json' },
success: function(data) {
console.log(data);
// window.location.href = "/dashboard";
}
});
};
I'm sending CRSF token as X-CSRF-TOKEN header.
The problem is that when I successfully login, I say on the same page,
but in Network tab I can see that /dashboard page is loaded by I'm not
redirected.
In the same manner, when I pass wrong credentials, I stay on the same page,
but I can see that /login page is loaded in the separate call with an error message that should be actually displayed.
Also, I've tried without headers : { 'Content-Type': 'application/json' },
and sending data as: data = data, but I get the same thing.
Why the browser doesn't redirect to that page since it is loading it in the "background"?
Edit: I'm getting correct page as request response as well, I can see it
in console (console.log(data);).
//Login FORM
$(document).on('submit', 'form#FormID', function(e) {
e.preventDefault();
var forms = document.querySelector('form#FormID');
var request = new XMLHttpRequest();
var formDatas = new FormData(forms);
request.open('post','/login');
request.send(formDatas);
request.onreadystatechange = function() {
if (request.readyState === 4) {
if (request.status === 200) {
if (request.responseText == 'success') {
setTimeout(function() {
window.location.href = "/dashboard";
}, 5000);
}else{
};
}
}
}
});
//Controller
public function authUser(Request $request){
$data = $request->except('_token');
$validate = \Validator::make($data, [
'email' => 'email'
]);
if ($validate->fails())
return 'Invalid email format for username.';
if (\Auth::attempt($data)) {
return 'success';
}else{
return 'Invalid username or password';
}
}
//Route
Route::post('/login', 'YourController#authUser');
The problem might be with the response AJAX request is expecting before redirect.
Try the above code.
in the controller method
function login(Request $request){
if(\Auth::attempt($request)){
return response()->json('success');
}else{
return response()->json('wrong username or pass', 401);
}
}
in ajax
$.ajax({
type: "POST",
url: '/login',
data: JSON.stringify(data),
// data: data,
headers : { 'Content-Type': 'application/json' },
success: function(data) {
console.log(data);
window.location.href = "/dashboard";
},
error : function(data){
alert(data);
}
});
Here's an interesting solution.
/**
* Get the failed login response instance.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
protected function sendFailedLoginResponse(Request $request)
{
if ($request->ajax()) {
return response()->json([
'error' => Lang::get('auth.failed')
], 401);
}
return redirect()->back()
->withInput($request->only($this->username(), 'remember'))
->withErrors([
$this->username() => Lang::get('auth.failed'),
]);
}
And this:
var loginForm = $("#loginForm");
loginForm.submit(function(e) {
e.preventDefault();
var formData = loginForm.serialize();
$('#form-errors-email').html("");
$('#form-errors-password').html("");
$('#form-login-errors').html("");
$("#email-div").removeClass("has-error");
$("#password-div").removeClass("has-error");
$("#login-errors").removeClass("has-error");
$.ajax({
url: '/login',
type: 'POST',
data: formData,
success: function(data) {
$('#loginModal').modal('hide');
location.reload(true);
},
error: function(data) {
console.log(data.responseText);
var obj = jQuery.parseJSON(data.responseText);
if (obj.email) {
$("#email-div").addClass("has-error");
$('#form-errors-email').html(obj.email);
}
if (obj.password) {
$("#password-div").addClass("has-error");
$('#form-errors-password').html(obj.password);
}
if (obj.error) {
$("#login-errors").addClass("has-error");
$('#form-login-errors').html(obj.error);
}
}
});
});

Categories

Resources