replace angular app with another via $http - javascript

I am using Angular to try to replace my login form with a registration form when a user clicks "Sign up," but I can't seem to get the second form to interact with angular, since the controller loads before the second form.
As of right now, I'm using JQuery's html() function to replace the form, and if I were just using Jquery as a function, I'd just do the following:
$(window).on('click','submit',function(){
//function here
});
but I can't seem to get anything similar to work in Angular.
Original Form:
<div ng-app="login" ng-controller="loginCtrl">
<div id="formContainer">
<form ng-submit="loginSubmit()" id="loginForm" name="loginForm">
email: <input id="email" name="email" ng-model="email">
password: <input id="pw" name="pw" ng-model="pw">
<div class="row center">
<span ng-click="signup()" id="signupButton" class="button">Sign Up</span>
<span ng-click="login()" id="loginButton" class="button">Submit</span>
</div>
</form>
</div>
</div>
Registration Form:
<div ng-app="signup" ng-controller="signupCtrl" class="flexRow">
<form ng-submit="signupSubmit()" id="signupForm" name="signupForm">
email: <input name="signupEmail" ng-model="signupEmail" type="email">
password: <input name="signupPw" ng-model="signupPw">
first name: <input name="signupFirstName" ng-model="signupFirstName">
last name: <input name="signupLastName" ng-model="signupLastName">
<div>
<span ng-click="register()" id="register" class="button">Register</span>
</div>
</form>
</div>
Controller:
app.controller("loginCtrl",function($scope, $http){
//sign up
$scope.signup = function(){
$http({
method: "POST",
url: "/functions/signup",
data: {/* data in here */},
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(
function successCallback(response){
$('#formContainer').html((response.data));
}, function errorCallback(response){
alert('error: \n'+ response.data);
}
);
}
//registration
$scope.register = function(){
$http({
method: "POST",
url: "/functions/register",
data: {/*data here */},
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(
function successCallback(response){
$('#auth').html(response.data);
}, function errorCallback(response){
$('#auth').html('ERROR: ' + response.data);
}
);
}
});
Is there any way I can have the controller read the ng-click event on the dynamically added content?

Rule #1: Don't mix jQuery with Angular, especially in controllers.
You're breaking the Angular data binding by replacing the form contents with jQuery. Probably the easiest way to do what you are wanting to do is to have certain fields visible for existing users (username/password, and login button) and the other fields (for creating an account) visible when the signup button is clicked. This can be accomplished via a simple ng-show, and you don't need a second app for it (like you have listed in your example.)
<div ng-app="login" ng-controller="loginCtrl">
<div id="formContainer">
<form ng-show="!register" id="loginForm" name="loginForm">
email: <input id="email" name="email" ng-model="email">
password: <input id="pw" name="pw" ng-model="pw">
<div class="row center">
<span ng-click="signup()" id="signupButton" class="button">Sign Up</span>
<span ng-click="login()" id="loginButton" class="button">Submit</span>
</div>
</form>
<form id="signupForm" name="signupForm">
email: <input name="signupEmail" ng-model="signupEmail" type="email">
password: <input name="signupPw" ng-model="signupPw">
first name: <input name="signupFirstName" ng-model="signupFirstName">
last name: <input name="signupLastName" ng-model="signupLastName">
<div>
<span ng-click="register()" id="register" class="button">Register</span>
</div>
</form>
</div>
</div>
And the controller...
app.controller("loginCtrl",function($scope, $http){
$scope.register = false;
$scope.signup = function(){
$scope.register = !$scope.register;
};
//sign up
$scope.login= function(){
$http({
method: "POST",
url: "/functions/login",
data: {/* data in here */},
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(
function successCallback(response){
//do something after success, like maybe redirect to a new page
}, function errorCallback(response){
alert('error: \n'+ response.data);
}
);
}
//registration
$scope.register = function(){
$http({
method: "POST",
url: "/functions/register",
data: {/*data here */},
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(
function successCallback(response){
//do something after success, like maybe redirect to a new page
}, function errorCallback(response){
alert('error: \n'+ response.data);
}
);
}
});

Related

in Laravel I GOT AN ERROR The POST method is not supported for this route. Supported methods: GET, HEAD

I am trying to when the customer wants to upload an image or logo I want this image to display it in front of him by span element for him to make sure he uploaded the correct image to the system but when I press on upload I got POST method is not supported for this route. Supported methods: GET, HEAD. error
here is my code in card_view_blade
<div class="form-group row">
<div class="col-md-8">
<form method="post" id="upload-image-form" enctype="multipart/form-data">
#csrf
<div class="input-group" data-type="image">
<input type="file" name="file" class="form-control" id="image-input">
<button type="submit" class="btn btn-success">Upload</button>
</div>
</form>
</div>
<div class="col-md-4">
<div class="alert" id="message" style="display: none"></div>
<span id="uploaded_image"></span>
</div>
</div>
here is the js code
#section('script')
<script type="text/javascript">
$(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#upload-image-form').submit(function(e) {
e.preventDefault();
let formData = new FormData(this);
$('#message').hide().html('');
$.ajax({
type:'POST',
url: `/upload-images`,
data: formData,
dataType:'JSON',
contentType: false,
cache: false,
processData: false,
success: (data) => {
console.log("success-",data);
if (data) {
this.reset();
$('#message').show().html(data.message);
$('#message').addClass(data.class_name);
$('#uploaded_image').html(data.uploaded_image);
}
setTimeout(function(){
$('#message').hide().html('');
}, 3000);
},
error: function(data){
console.log("error-",data);
// $('#image-input-error').text(data.responseJSON.errors.file);
$('#message').show().html('Something went wrong');
$('#message').addClass('danger');
$('#uploaded_image').html('');
setTimeout(function(){
$('#message').hide().html('');
}, 3000);
}
});
});
})
</script>
#endsection
route code
Route::post('/upload-images', 'CheckoutController#storeImage' )->name('images.store');
Nothing seems to be wrong with the code perhaps the routes are cached. Try clearing them first and see if the problem is resolved or not with the following commands:
php artisan route:clear

Jquery form submitting before validation

I want to validate a form for inputs with the 'required' attributes but it appears that "e.preventDefault()" is not working. The form submits and the POST succeeds but with the unvalidated data and I can't find where the problem is.
<form>
<label for="name" class="control-label">Name</label>
<input type="text" id="name" class="form-control" required>
<label for="phone" class="control-label">Phone Number</label>
<input type="text" id="phone" class="form-control" required>
<label for="email" class="control-label">Email address</label>
<input type="email" id="email" class="form-control" required>
<div id="form-response"></div>
<button class="btn btn-lg btn-primary btn-block" id="submit" type="submit" style="background-color:#28547C;">Request Appointment</button>
</form>
JS:
$(document).ready(function() {
$("#submit").click(function(e) {
e.preventDefault();
var name = $("#name").val(),
email = $("#email").val(),
phone = $("#phone").val()
$.ajax({
type: "POST",
url: 'https://a2xvt72c0c.execute-api.us-west-2.amazonaws.com/prod',
contentType: 'application/json',
data: JSON.stringify({
'name': name,
'phone':phone,
'email': email
}),
success: function(res) {
$('#form-response').html('<div class="alert alert-info" role="alert">Thank you! Appointment request has been sent. We will contact you soon. </div>');
},
error: function() {
$('#form-response').html('<div class="alert alert-info" role="alert">Something went wrong... We are working on it!</div>');
}
});
})
});
JS Fiddle: https://jsfiddle.net/yhgz55y0/
Right now you are using a click event and not a submit event. If you switch it to:
$("#submit").submit(function(e) {...
the validation works.
Your form is submitting because you are calling the $.post() immediately without stopping. You want to run validation against your name, email and phone variables and if any are not valid, return early or put the entire thing into an if block.
What e.preventDefault() does is prevents the browser built-in actions. But as your form has no action or target properties, you are effectively canceling a no-op, hence why this is not behaving as you expect it to.
preventDefault is a function that prevents a normal task from executing. Here you prevent the click on a button. A button doesn´t have a function in this form so there won´t be any difference. You want to prevent de form from submiting. If you change your code to this:
$(document).ready(function() {
$("form").submit(function(e) {
e.preventDefault();
var name = $("#name").val(),
email = $("#email").val(),
phone = $("#phone").val()
$.ajax({
type: "POST",
url: 'https://a2xvt72c0c.execute-api.us-west-2.amazonaws.com/prod',
contentType: 'application/json',
data: JSON.stringify({
'name': name,
'phone':phone,
'email': email
}),
success: function(res) {
$('#form-response').html('<div class="alert alert-info" role="alert">Thank you! Appointment request has been sent. We will contact you soon. </div>');
},
error: function() {
$('#form-response').html('<div class="alert alert-info" role="alert">Something went wrong... We are working on it!</div>');
}
});
})
});
This assuming you only have 1 form on your page. This will prevent the form from submiting.

How to tell angularjs form that the input value has changed

I built a sign up from using angularjs. The submitting process is OK. Then I want to make a validation of checking if the email is already registered. If exist, show the error message informing that the email exists. The problem I face is when user changes the email address, the submitted email is still the previous one. How to tell angular that the input value has changed and submit the newly inserted values.
My sign up form
<div ng-controller="signupController">
<form ng-submit="doSignup()">
<h2 class="form-signin-heading">Sign Up</h2>
<div class="login-wrap">
<input type="text" name="email" class="form-control" autofocus="" ng-model="formData.email">
<span class="text-danger">{{ emailExistError }}</span>
<input type="password" name="password" class="form-control" placeholder="Password" ng-model="formData.password">
<input type="password" name="password_conf" class="form-control" placeholder="">
<button class="btn btn-lg btn-login btn-block" type="submit">Sign Up</button>
</div>
</form>
</div>
The app.js
angular.module('myApp', ['ngRoute', 'ngSanitize'])
.controller('mainController', function ($scope, $http) {
})
.controller('signupController', function ($scope, $http,$window) {
$scope.formData = {};
$scope.doSignup = function () {
$http({
method: 'post',
url: 'signup.php',
data: $.param($scope.formData),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function (data) {
$scope.login = data;
if (data.status == 'ok') {
$('#successModal').modal('show');
}
else if (data.status == 'email exist'){
$scope.emailExistError = 'Email exist. Use different email';
}
else {
$('#failedModal').modal('show');
}
})
}
})
try
$watch('email',function(newVal,oldVal){
if(newVal!=oldVal){
$scope.doSignup();
}});

Angular Form Trouble Binding to Scope

I have a simple Angular form with a textbox and some hidden fields. This form is recycled many times on my page.
<form accept-charset="UTF-8" name="form.jobAppForm" class="pitch-form" novalidate>
<div style="display:none;">
<input name="authenticity_token" type="hidden" ng-value="window._token">
<input name="user_id" type="hidden" ng-value="<%= current_user.id %>">
<input name="job_description_id" type="hidden" ng-value="j.id">
<input name="company_id" type="hidden" ng-value="j.company_id">
</div>
<div class="form-group">
<textarea class="apply-textbox" id="pitch" name="pitch" ng-model="jobApp.pitch"></textarea>
</div>
<input class="apply-submit-btn" name="commit" type="submit" value="Submit Application" ng-click="createApplication(jobApp)" onClick="this.disabled=true;this.value='Sending…';">
</form>
In my controller I have a newApplication method that initializes $scope.jobApp and then a createApplication method that sends a post request to the server. If I log the value of $scope.jobApp when createApplication is called, all the attributes are still set to null. Only the pitch attribute seems to be bound. If I enter a pitch, that is bound to the scope, but nothing else is. I'm not sure what I'm missing. Why is pitch bound but none of the other attributes? Here are my controller methods.
$scope.newApplication = function() {
console.log('new app')
$scope.form = {}
$scope.jobApp = {
token: null,
user_id: null,
job_description_id: null,
company_id: null,
pitch: null
};
};
$scope.createApplication = function() {
var jobAttributes = $scope.jobApp;
console.log(jobAttributes)
if ($scope.form.jobForm.$valid) {
$http({
method: 'POST',
url: '/applications',
data: jobAttributes,
headers: {'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json, text/plain, */*'}
}).success(function(data, status){
console.log('success');
}, function(err){
alert("Failed to save job! Server responded with: " + err)
});
};
}
Note: I've tried setting ng-model="jobApp.attribute" for the other attributes as well as using value= rather than ng-value= to no effect.
like #HaukurHaf, you need to use ng-model on the form field.
<form accept-charset="UTF-8" name="form.jobAppForm" class="pitch-form" novalidate>
<div style="display:none;">
<input name="authenticity_token" type="hidden" ng-model="jobApp.token">
<input name="user_id" type="hidden" ng-model="jobApp.user_id">
<input name="job_description_id" type="hidden" ng-model="jobApp.job_description_id">
<input name="company_id" type="hidden" ng-model="jobApp.company_id">
</div>
<div class="form-group">
<textarea class="apply-textbox" id="pitch" name="pitch" ng-model="jobApp.pitch"></textarea>
</div>
<input class="apply-submit-btn" name="commit" type="submit" value="Submit Application" ng-click="createApplication(jobApp)" onClick="this.disabled=true;this.value='Sending…';">

angular resource passing unwanted parameters

I am trying to setup a server side authentication service using rails like this :
Javascript:
angular.module('myApp',['ngResource'])
.factory("Session",['$resource',function($resource){
return $resource('/sessions',{}, {
create: {method: 'POST', isArray: false},
destroy: {method:'DELETE', url: '/sessions/destroy.json' }
});
}])
.controller("LoginController",['$scope','Session',function($scope,Session){
$scope.model = {};
$scope.login = function(username,password){
//Session.save({username: username, password: password}).then(function(success){
// $scope.model.user = success.data;
// console.log("New Session");
//},function(error){
// console.log("Login failed!!!");
// console.log(error);
//});
$scope.model.user = {
first: "John",
last: 'Doe'
};
};
$scope.logout = function(){
Session.destroy().then(function(success){
$scope.model.user = {};
console.log("Session Deleted!!!");
},function(error){
console.log("Error in Session delete...");
console.log(error);
})
};
}]);
html:
<div class="navbar navbar-inverse" role="navigation" ng-controller="LoginController">
<div class="navbar-right navbar-form " style="color:white" ng-show="model.user">
<span class="glyphicon glyphicon-user"></span>
<span>{{ model.user.first + ' ' + model.user.last}}</span>
<button ng-click="logout()" type="submit" class="btn btn-danger navbar-btn">Logout</button>
</div>
<div class="navbar-form navbar-right" role="login" ng-hide="model.user">
<div class="form-group">
<a ng-href="#">new user? </a>
<a ng-href="#"> forgot password?</a>
</div>
<form class="form-group" name="loginForm" ng-submit="login()">
<input type="text" class="form-control" placeholder="username" ng-model="username" />
<input type="password" class="form-control" placeholder="password" ng-model="password" />
<button type="submit" class="btn btn-primary navbar-btn">Login</button>
</form>
</div>
</div>
But when I make a logout request, angular is putting a extra parameter see rails server log:
Started DELETE "/sessions/destroy.json" for 127.0.0.1 at 2014-04-26 18:30:30 -0400
Processing by SessionsController#destroy as JSON
Parameters: {"id"=>"destroy"}
Why is this happening ?
try this:
angular.module('myApp',['ngResource'])
.factory("Session",['$resource',function($resource){
return $resource('/sessions/:action',{}, {
create: {method: 'POST', isArray: false},
destroy: {method:'DELETE', params: { action: 'destroy.json' } }
});
}])

Categories

Resources