Checking if user exists using AngularJS and ng-if - javascript

I am building a cross-platform app using Onsen UI, Monaca and AngularJS. I need to check if a user exists based on the UserID they enter. If the UserID is found, then the name is returned to me, else the user wont be able to proceed to the next screen.
I send the UserID via API call ($http) and get a JSON object as a response. When I enter a UserID I can retrieve the JSON object (tested and working) but I am stuck on authentication.
When the user clicks the LOG IN button, I show a modal (ons-modal) window with a message of the users name if the user is found, but I am stuck on showing the message LOGIN FAIL if no user is found.
Is there perhaps a better way to handle this rather than a modal window?
Below is my code. And below is an example of the JSON that is returned.
[{"employee_name":"John Doe"}]
There is also a Controller that handles the API calls and it can be assumed this is working OK as I am able to get user names - but just stuck on authentication.
login.html
<div style="text-align: center; color: #889DA8">
Enter your<br><strong>User ID</strong>
</div>
<form class="login-form" style="text-align: center" name="myForm">
<section style="padding: 8px">
<input type="password" class="text-input--underbar" required minlength="3" maxlength="4" ng-model-options="{ debounce : 800 }" placeholder="User ID" ng-model="userIDSearch" >
</section>
<section style="padding: 0 8px 8px">
<ons-button var="saveBtn" ng-disabled="myForm.$invalid" modifier="large" onclick="modal.show('modal')">Log In</ons-button>
</section>
</form>
<!-- Displays Modal Login Confirmation Screen -->
<ons-modal var="modal">
<div class="alert-dialog-mask"></div>
<div class="alert-dialog alert-dialog--android">
<div class="alert-dialog-title alert-dialog-title--android">
<div style="text-align: center">Please confirm your name</div>
</div>
<div class="alert-dialog-content alert-dialog-content--android">
<div style="text-align: center; padding-top: 10px; padding-bottom: 15px; padding-left: 10px; padding-right: 10px;">
<p ng-repeat="userID in userIDs">
<!-- If returned value != 0 then we have a valid User -->
<!-- NOT WORKING HERE -->
<span ng-if="userID.employee_name !== 0 ">
<strong>
{{userID.employee_name}}
</strong>
</span>
<!-- NOT WORKING HERE -->
<span ng-else>
<strong>
User ID not found. Please try again.
</strong>
</span>
</p>
</div>
</div>
<div class="alert-dialog-footer alert-dialog-footer--one">
<button class="alert-dialog-button alert-dialog-button--one" ng-click="modal.hide()">Cancel</button>
<button class="alert-dialog-button alert-dialog-button--primal alert-dialog-button--one" ng-click="myNavigator.pushPage('vehicle-id.html', {animation: 'slide'});" )>Ok</button>
</div>
</div>
</ons-modal>
Would this be better handled in the app-controller perhaps?
appController.js
// App Controller Start
angular.module("myApp", ['onsen']).controller("appController", function($scope, $http)
{
// Watch for changes in the User ID text field
$scope.$watch('userIDSearch', function()
{
fetchUSerID();
});
// Initialising the search field
$scope.userIDSearch = "";
function fetchUSerID()
{
$http.get("mymadeupdomain/api/login.php?userid=" + $scope.search).success(function(data)
{
$scope.userIDs = data;
});
}
});

Based on what I got from your question:
You can try initializing a $scope variable as $scope.result = false;
In the success loop of $http.get() (i.e if you get the user data), you can set it to true.
On Your modal window, you can use a condition like
<span ng-if = 'result'><{{bind user name variable here}}</span>
<span ng-if ='!result'>No User Found/ Login Failed</span>

Related

Why the button element is not working when used inside foreach loop inside view in a laravel?

I need a graph inside a card, with records from the database.
Each card contains a button element, which onclick, updates the value for the particular ID of the card. . The value will be triggered through the event.
Controller:
class SampleController extends Controller
{
public function index()
{
$users=User::all();
return view('progress', ['users'=> $users]);
}
#foreach($users as $user)
<div class="card">
<div class="card-title">
<div class="caption">
{{ $user['name'] }}
</div>
<div class="actions">
<div class="btn">
<button id="ref">Refresh</button>
</div>
</div>
</div>
<div class="card-body" id="{{ $user['id'] }}">
<center>
<div style=" display:inline; width: 200px; height: 200px;">
<input
class="graph"
data-max="{{ $user['goal'] }}"
value= ""
/>
</div>
</center>
</div>
</div>
#endforeach
</div>
Script::
var pusher = new Pusher('xxxxxxx', {
cluster: 'ap3',
encrypted: true
});
// Subscribe to the channel we specified in our Laravel Event
var channel = pusher.subscribe('my-channel');
channel.bind('App\\Events\\myEvent', function(data){
target = data.id;
value = data.value;
//Refresh button
$('#ref').click(function(){
$.ajax({url: '/api/getId/' + target,
success: function(){
alert('THe UI is updated' + value);
$(target).block({
message: 'processing',
timeout: 20000,
});
$(target).unblock();
}
});
});
When I pass the value through tinker like the below,
event(new App\Events\myEvent('3',40));
I could see the particular Id(3) is updated with the value 40.
The purpose of refresh is ,the card should be blocked for 20seconds, Meanwhile If I pass the value through Event for the particularId, It unblocks the card and updates the card with the new value.
The problem is ,If I have 10 cards, only the refresh button in the first card works, the refresh button in the remaining cards doesn't work.
How can I make the refresh button work in all the cards?
Could anyone please help?
Many thanks.

how do i send ajax request by using onclick event without form enclosed tags in django

this is image that i want to doactually i have a div content,i have apply onclick event on that div when user click on that div the text between these tags should be sent to server and then display in the table as well.i have done something guid me where is the error actually,because $.ajax not working it raising an error
e.g: $.ajax is not fnction
players.html
<div class="selectize-control single">
<div class="selectize-input items has-options not-full">
<input type="text" autocomplete="off" tabindex=""
id="select_player" style="width: 146.75px; opacity: 1; position:
relative; left: 0px;" placeholder="Adauga jucator la echipa">
</div>
<div class="selectize-dropdown single liststyle" id="listitems"
style="display: None; width: 987px; top: 29px; left: 0px; visibility:
visible;">
<div class="selectize-dropdown-content">
{% block listplayers %}
{% if player is not None %}
{% for p in player %}
<div class="option selected curserstyle sp" id="{{p.id}}" data-selectable="" data-value="{{p.YourName}}">{{p.YourName}}1</div>
<div class="option selected curserstyle sp" id="49" data-selectable="" data-value="{{p.YourName}}">{{p.YourName}}2</div>
{% endfor %}
{% else %}
<div class="text-center">
List is Empty
</div>
{% endif %}
{% endblock %}
</div>
</div>
</div>
javascript
$("#listitems").on('click',function(e){
// preventing from page reload and default actions
e.preventDefault();
// serialize the data for sending the form data.
var serializedData = $(this).serialize();
// make POST ajax call
$.ajax({
type:'get',
url:"/templates/dashboard/players",
data:serializedData,
success:function(responce){
// on successfull creating object
// 1. clear the form.
$("#listitems").trigger('reset');
// 2. focus to nickname input
$(".sp").focus();
// display the newly friend to table.
var instance = JSON.parse(response["instance"]);
var fields = instance[0]["fields"];
var x = document.getElementById(user_id).textContent;
$("#playername").append('<div class="row list-row player-row " id="targetdel'+i+'"><div class="col-md-6 title"><a id="playername" href="#">'+x+'</a></div><div class="col-md-2 company text-center has-checkbox"><label class="green checkbox-box"><input type="checkbox" class="checkbox_entity checkbox_captain" id="captain" data-entity_id="17270" data-entity_type="captain" data-url_ajax="update_team_player"><span class="checkmark"></span></label></div> <div class="col-md-2 company text-center has-checkbox"> <label class="green checkbox-box "><input type="checkbox" class=" checkbox_entity checkbox_observer " id="cd_btn" data-entity_id="'+i+'" data-entity_type="observer" data-url_ajax="update_team_player style="background-color:black;" "> <span class="checkmark"></span> </label></div><div class="col-md-2 actions company text-right"><a href="" class="remove_entity_data" data-entity_id="17270" data-entity_type="team_player" > </a><button id = "'+i+'" class="btn del" style="text-transform: none;background-color: #ed143d00;padding: 0px 9px;border: none;color: #a2a2a2;">x</button></div></div>');
i++;
},
error: function (response) {
// alert the error if any error occured
alert("this one is error");
alert(response["responseJSON"]["error"]);
},
})
})
Apart from you using response in the success of the ajax when you have function(responce), you may be using the slim build of Jquery.
You should make sure you are using the full version of Jquery as the slim build for some reason does not have ajax included in it.
An easy way to check is to go to where you have defined your scripts and see whether your script has slim in it.
This is, I believe, the latest full version of jquery. This is what you should have.
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
not this
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>

how to show modal windows dynamically and send data with Flask

I'm trying to insert modal window html code dynamically upon user click on which item otherwise i load all of the items' modal window code in the html. I also have some inputs in the modal window loading from Flask/Sql and i want to let user update any of them so i need to send data back to python on submit button clicked. But right now because of i have too many modal windows (even though they have separate ids) i couldn't find a way to achieve this
Here is my code:
routes.py
#app.route('/viewApart', methods=['GET', 'POST'])
def viewApart():
apts = []
getApts = db.engine.execute("SELECT * FROM apartments")
for a in getApts:
apts.append((a))
rooms = []
getRooms = db.engine.execute("SELECT * FROM rooms")
for r in getRooms:
rooms.append((r))
return render_template('apartments.html', title=_('Apartments'), apts=apts, rooms=rooms)
apartments.html
....
<section class="container">
<div class="row">
.. below some gallery code to show individual items from apts ..
{% for apt in apts %}
<div class="col-md-3">
<a href="javascript:void(0);" class="widget__v2 apt-widget rounded-corners box-shadow__v1 white" data-anchor="modalwindow" data-target="edit-apartment{{ apt[0] }}" id="apt{{ apt[0] }}">
<div class="widget-header">
<figure class="image h-180">
<img src="{{url_for('static', filename='_assets/img/apt/{{ apt[0] }}.jpg')}}" alt="" class="image__scaledown">
</figure>
.. below model window ..
<div id="edit-apartment{{ apt[0] }}" class="modal large">
<div class="modal-wrapper">
<div class="modal-inner">
<div class="modal-header">
<h3 class="title">{{ _('Edit Apartment') }}</h3>
</div>
<div class="modal-content">
<div class="row medium-gutter">
<div class="col-md-6">
<div class="row medium-gutter">
<div class="col-md-8">
<div class="form-group">
<div class="form-group-title clearfix">
<label for="apt_display_name">{{ _('Display Name') }}</label>
<div class="lh-24 text__default-grey pull-right" data-tooltip="true" data-tooltip-direction="up" data-multiline="true"
data-content="..">
<i class="icofont-question-circle"></i>
</div>
</div>
<input id="apt_display_name" type="text" class="form-control" value="{{ apt[1] }}">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="apt_number">{{ _('Apt. Number') }}</label>
<input id="apt_number" type="text" class="form-control" value="{{ apt[2] }}">
</div>
</div>
</div>
.. and so on...
.. and submit button ..
{{ _('Save Changes') }}
</div>
</section>
Right now even with multiple model windows, i can display the current data in modal window, so what i want to achieve this upon clicking on btnSubmit button i need to send all input values back to python so i can update my sql or insert new one. Please let me know if more code is needed..
Thanks
If I am understanding your question correctly - a skeleton version of your page would be something like this
<!DOCTYPE html>
<html>
<body>
<p>INTRODUCING MY AWESOME SITE AND 2 DIVS YOU CAN CLICK</p>
<div id="apt_1_modal">
<input id="apt_1_text"></input>
<a onclick="myFunction(event)">Submit</a>
</div>
<div id="apt_2_modal">
<input id="apt_2_text"></input>
<a onclick="myFunction(event)">Submit</a>
</div>
</body>
</html>
You will need JavaScript to handle the user interaction - the script would look something like this. You can either append this script directly to your render_template output or you can append it as a file.
The script will do 2 things - first capture what your user is inputting and second, send that data over to flask
<script>
function myFunction(e) {
//FIRST WE CAPTURE THE VALUE THAT THE USER INPUTS
let userInput = {toSend: e.currentTarget.previousElementSibling.value}
//THEN WE SEND IT TO THE FLASK BACKEND USING AJAX (Fetch API)
fetch("/api/path/to/flask/route", {
method: 'POST',
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(userInput)
}
</script>
Now you need a function that can handle the userInput data
Backend
from flask import Flask, request #import main Flask class and request object
#app.route('/api/path/to/flask/route', methods=['POST'])
def capture_userinput():
req_data = request.get_json()
recd_data = req_data['toSend']
your_code_to_push_data_to_db(recd_data) #Depends on your ORM/DB
I hope I have given you an idea of how to go about - You will most certainly have to change the way to capture userInput, tweak the fetch call and send/capture additional data in your flask api.

Angular js - Not able to regenerate the view over ng-view on page reload

I am new to Angualr Js, I am trying to implement a simple app, Below is my requirement,
My application has three roles, basing on the roles i am rendering different pages.
In the role based rendered page, i have few links, on click of each link, i am rendering few more features.
Initially i am using ng-include to render my view by calling a method in my controller which hits the service and get the role and basing on the role, i am returning the view.
Home.html
<html>
<head>
<meta charset="ISO-8859-1">
<title></title>
</head>
<body>
<div class="container" data-ng-app="vendorPortalApp" data-ng-controller="vendorPortalController">
<div data-ng-include="getView()">
</div>
</div>
</body>
I am intializing the angular services and controller along with routes here
app.js
angular.module('vendorPortalApp', ['vendorPortalApp.controllers','vendorPortalApp.services','ngRoute']).config(['$routeProvider', function($routeProvider) {
$routeProvider.
when("/home", {controller: "vendorPortalController"}).
when("/home/resetPassword", {templateUrl: "features/resetPassword.html", controller: "vendorResetPasswordController"}).
when("/home/editProfile",{templateUrl: "features/editProfile.html",controller:"vendorEditProfileController"}).
otherwise({redirectTo: '/home'});}]);
Controller.js
angular.module('vendorPortalApp.controllers', []).controller('vendorPortalController', function($scope,serviceApi) {
$scope.role = null;
serviceApi.getUserSessionData().success(function (response) {
$scope.role = response;
});
$scope.getView = function() {
if($scope.role == "SuperAdmin"){
return "views/SuperAdmin.html";
}else if($scope.role == "Admin"){
return "views/Admin.html";
}else if($scope.role == "User"){
return "views/User.html";
}else {
return null;
}
}}).controller('vendorResetPasswordController',function($scope,serviceApi){
}).controller('vendorEditProfileController',function($scope,serviceApi){
});
views/SuperAdmin.html
<div class="left-content">
Edit Profile
Reset Password
</div>
<div class="right-content">
<ng-view></ng-view>
</div>
I have a folder named features, in which i have editProfile.html, and resetPassword.html partial views, i wanted to get these partial views rendered on anchor click on SuperAdmin.html
editProfile.html
<section data-ng-controller="vendorEditProfileController">
<h1>Edit Profile</h1>
Firstname : <input type="text" name="firstname"/>
Lastname : <input type="text" name="lastname"/>
<input type="submit" value="Submit" />
</section>
ResetPassword.html
<section data-ng-controller="vendorResetPasswordController">
<h1> Reset Password </h1>
Password : <input type="password" name="reset-password">
Confirm Password : <input type="password" name="confirm password">
<input type="submit" value="Submit"/>
</section>
I am able to render the views based on role, Once the SuperAdmin.html view got rendered, i have few anchor links on the page, on each anchor link it references to #/home/editProfile and #/home/resetPassword, these url pattern match in the route configuration and render the appropriate feature from the features folder.
The only issue i am facing is, Lets say i have clicked on reset password link, my url gets updated to http://locahost/vendorapp/home.html#/home/resetPassword
and i get the reset password feature rendered over my page, Now when i am reloading the page, it gives me an issue, it wipes away the resetPassword.html feature, and even when we click on reset password link, it does not generate the view. Any help on this will be appreciated!

Changing HTML Form Text Using Javascript and/or Razor

I'm working in a view that deals with creating account information and resetting passwords. Where I'm stuck: depending if the password request was sent, approved, or denied, this will in turn change how the log in screen/password request appears. I want it to change the present text in the form and update it with a message and the user can submit OK, etc. so the browser will close automatically (or have the current form be hidden so I can create a new one with the information, whichever is easier).
Before I had an alert to send the message, but now I need it as HTML to style it.
//All of this is in a Javascript script tag
var reset = getParameterByName('reset');
if (reset == "sent") {
//alert("Done! Please check your email to confirm.")
//How can I change the current text on the form?
document.getElementsByClassName('panel-login').innerHTML = "<div class='panel-login' style='color: white; background-color: blue;'><p>Done! Please check your email to confirm.</p></div>";
//Here so I know something is updating on the site...
var message = "<div style='color: white; background-color: blue;'><p>Done! Please check your email to confirm.</p></div>";
document.write(message);
}
if (reset == "fail") {
alert("Password reset request failed.")
}
if (reset == "approved") {
alert("Confirmed! A password reset email has been issued.")
#*var url = '#Url.Action("Login", "Account")';
window.location = url;*#
}
(Whatever works with the first if (sent) will be copied and pasted into the last two once I get this working.)
This is the HTML for the above:
<div class="panel_login" style="opacity: 0.9;">
<div class="">
#using (Html.BeginForm("ResetPassword2", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { #class = "form-signin mg-btm" }))
{
<div class="" style="padding-left: 20px; padding-right: 20px; padding-bottom: 20px; padding-top: 10px; ">
<div class="">
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "Password reset was unsuccessful. Please check email and try again.")
<label>Email</label>
<div class="input-group">
<span id="emailinput" ng-model="user.EMAIL" class="input-group-addon"><span class="glyphicon glyphicon-user"></span></span>
#Html.TextBoxFor(m => m.Email, new { #class = "form-control", placeholder = "" })
#Html.ValidationMessageFor(m => m.Email)
</div>
</div>
</div><div class="panel-footer">
<div class="row centered">
<div class="col-xs-12">
<button id="singlebutton" name="singlebutton" class="btn btn-primary" onclick="Back(); return false;">Cancel</button>
<button class="btn btn-large btn-danger" type="submit" ng-click="resetpassword(user)">Request Password Reset</button>
</div>
</div>
</div>
}
</div>
I've tried hiding the panel-login so I can create a new div/element to display the message/form. It didn't work (doing something wrong):
document.getElementsbyClassName('panel-login').style.display = 'none';
Learned that since it was an array, I will need something else since the above produces a null and error. Tried using a variable to get the class and then a for statement to target it to style. Again, no avail.
I'm not familiar with Razor (still learning) and copying what I need in JavaScript seems to just replicate things instead of changing what's already there. Thanks in advance.
If I follow you, getElementsByClassName is the culprit. Try:
var loginPanel = document.getElementsbyClassName('panel-login')[0];
This will find the first match in the array.
I ended up figuring this out.
Essentially, I created other divs which is styled similarly to the log in screen and in the same position, but kept them hidden until they're called by their function to appear depending on user input and URL. Log in screen originally is visible but later hidden when another div is made visible to display the tailored message.
I first created this through Javascript (using functions to create HTML), but later changed it to HTML and CSS but still used JS to call the functions. The main reason I had to switch is because some messages after being confirmed either submitted something or was supposed to close the tab or go back and I had trouble doing so since apparently a script can't close the current page that didn't initially open it. Still having that problem in Chrome TBH.

Categories