How to check if query params are empty with AngularJS forms - angularjs

I have a project where i use query params which are passed to the back end for a search.
They are passed using the $http.get method in AngularJS.
Some params are not required for the search, so I want them to not be in the url when they are empty.
How can i get this functionality?
Below is my code:
<!DOCTYPE html>
<html lang="en" ng-app = "searchApp">
<script type="text/javascript">
var searchApp = angular.module("searchApp", []);
searchApp.controller("searchListingsCtrl", ['$scope', '$http', function($scope, $http) {
$scope.searchListings = function(){
if ($scope.checkIn == '') {}
var searchListingObj = {
checkIn : $scope.checkIn,
checkOut : $scope.checkOut,
country : $scope.country,
city : $scope.city,
state : $scope.state,
accommodates : $scope.accommodates,
}
var res = $http.get('http://www.localhost:8080/messenger/webapi/listings', searchListingObj);
res.success(function(data, status, headers, config) {
$scope.message = data;
});
res.error(function(data, status, headers, config) {
alert( "failure message: " + JSON.stringify({data: data}));
});
};
}]);
</script>
<body ng-controller="searchListingsCtrl">
<form action="/listings" name="listings" ng-submit="searchListings()">
<input type="text" name="neighborhood" placeholder="Neighborhood:" ng-model="state">
<input type="text" name="town" placeholder="Town:" ng-model="city">
<input type="text" name="country" placeholder="Country:" ng-model="country">
People:<select class="peopleSelect" placeholder="People:" ng-model="accommodates"> </select>
<input type="text" id="arrival" name="arrival" value="Arrival" ng-model="checkIn">
<input type="text" id="departure" name="depart" value="Departure" ng-model="checkOut">
<input type="submit" name="submit" value="Search" id="Search_submit">
</form>
</body>

Use the required attribute on inputs to prevent form submission of empty fields:
<form ̶a̶c̶t̶i̶o̶n̶=̶"̶/̶l̶i̶s̶t̶i̶n̶g̶s̶"̶ name="listings" ng-submit="searchListings()">
<input type="text" name="neighborhood" placeholder="Neighborhood:"
ng-model="fdata.state" ͟r͟e͟q͟u͟i͟r͟e͟d͟ />
<input type="text" name="town" placeholder="Town:"
ng-model="fdata.city" ͟r͟e͟q͟u͟i͟r͟e͟d͟ />
<input type="text" name="country" placeholder="Country:"
ng-model="fdata.country" ͟r͟e͟q͟u͟i͟r͟e͟d͟ />
People:<select class="peopleSelect" placeholder="People:"
ng-model="fdata.accommodates" ͟r͟e͟q͟u͟i͟r͟e͟d͟ />
</select>
<input type="text" id="arrival" name="arrival" value="Arrival"
ng-model="fdata.checkIn" ͟r͟e͟q͟u͟i͟r͟e͟d͟ />
<input type="text" id="departure" name="depart" value="Departure"
ng-model="fdata.checkOut" ͟r͟e͟q͟u͟i͟r͟e͟d͟ />
<input type="submit" name="submit" value="Search" id="Search_submit" />
</form>
For more information, see AngularJS Developer Guide - Forms.
Also notice how the ng-model attributes have been changed to put the data on a JavaScript object. This makes it easier to submit:
$scope.fdata = {};
var url = "http://www.localhost:8080/messenger/webapi/listings";
$scope.searchListings = function() {
var config = { params: fdata };
$http.get(url, config)
.then(function(response) {
$scope.message = response.data;
})
.catch(function(response) {
var data = response.data;
console.log( "failure message: " + JSON.stringify({data: data}));
throw response;
});
};
Also be aware that the $http .success and .catch methods have been deprecated and removes from AngularJS v1.6. Instead, use the .then and .catch methods.

Related

How to pass data-plugin="timepicker" value to controller in angularJS

I have code to pass date and time to controller.
Here is HTML code,
<div class="page-content" ng-app="app">
<div ng-controller="postAppoinmentCtr as ctrl" class="panel-body">
<form ng-submit="submitForm()" id="form1">
<input name="time" ng-model="time" type="text" class="form-control" ng-model="time" data-plugin="timepicker" autocomplete="off"/>
<input name="date" ng-model="date" type="text" class="form-control" data-plugin="datepicker"/>
<input..ng-model="type"...></input>
<input..ng-model="Description"...></input>
<button ...>
</form>
</div>
</div>
Here is angular js part
var app = angular.module('app', []);
app.controller('postAppoinmentCtr', function($scope, $http, $location) {
$scope.submitForm = function(){
var url = $location.absUrl() + "/addAppoinment";
alert(url);
var config = {
headers : {
'Content-Type': 'application/json;charset=utf-8;'
}
}
var data = {
type: $scope.type,
date: $scope.date,
time: $scope.time,
description: $scope.description
};
$http.post(url, data, config).then(function (response) {
$scope.postResultMessage = "Sucessful!";
}, function (response) {
$scope.postResultMessage = "Fail!";
});
$scope.type = "";
$scope.date = "";
$scope.time ="";
$scope.description ="";
}
});
When click the button type and description pass to controller. But date and time not. I can do this using
<input id="date-birth" class="form-control" type="date" ng-model="date">
this line. But I need to use data-plugin="datepicker" .
I'm new one for the angularjs and I try to many ways for solve this problem.
Please give me some answer this. Thanks in advance.

how to submit form value which have same name in angular js?

I have a multiple for filed which have a same name in array formate like
<input type='text' name="frm[]">. I want to submit this in AngularJS and get value in PHP.
my script:
<input type="text" name="textval" id="textval1" ng-model="data.textvalt[1]" >
<input type="text" name="textval" id="textval2"ng-model="data.textvalt[2]">
<input type="text" name="textval" id="textval3" ng-model="data.textvalt[3]">
Use Angular's $http service to post the data to your php file.
Check the below code
<html ng-app="submitExample">
<script type="text/javascript" src="lib\angular.js"></script>
<script type="text/javascript" src="index.js"></script>
<form ng-submit="submit()" ng-controller="FormController">
Enter text and hit enter:
<input type="text" name="textval" id="textval1" ng-model="data.textvalt[1]" >
<input type="text" name="textval" id="textval2"ng-model="data.textvalt[2]">
<input type="text" name="textval" id="textval3" ng-model="data.textvalt[3]">
<input type="submit" id="submit" value="Submit" />
</form>
<html>
var app = angular.module('submitExample', [])
app.controller('FormController', ['$scope','$http', function($scope,$http) {
$scope.data = {};
$scope.data.textvalt = new Array();
$scope.data.textvalt[1] = '';
$scope.data.textvalt[2] = '';
$scope.data.textvalt[3] = '';
$scope.submit = function() {
var configObject = {
method: 'POST',
url: 'index.php',
data: { textval1: $scope.data.textvalt[1] , textval2 : $scope.data.textvalt[2], textval3 : $scope.data.textvalt[3] }
}
$http(configObject).then
(function successCallback(response) {
console.log("posted sucuessfully");
},
function errorCallback(response) {
console.log("Failed");
});
};
}]);

How can log-in using $http.post?

Ionic Controller
.controller('LoginCtrl', function($scope, $ionicPopup, $state, $http) {
$scope.data = {};
$scope.login = function() {
$http.post('https://mywebsite/login', $scope.email) THIS PART IS TOTALLY WRONG
.success(function(data) {
$state.go('improvements');
}).error(function(data) {
console.log(data)
var alertPopup = $ionicPopup.alert({
title: 'Login failed!',
template: 'User/Password is Wrong'
});
});
}
})
I'm trying to login in a web using an ionic APP, so I used inspect element in form log-in from the website that i want login and I got this:
WEB that I want login
<form action="/login" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="✓"><input type="hidden" name="authenticity_token" value="+NAqH2wFj+OC3q5kX3UWLymVHDzpS9ei8a9/F5O8MM76EM6Fhf/RyOVRpCeYmGMtoxzB43Gf70WLbR+1EqD5xA==">
<label for="session_email">Email</label>
<input class="form-control" type="email" name="session[email]" id="session_email">
<label for="session_password">Password</label>
<input class="form-control" type="password" name="session[password]" id="session_password">
<label class="checkbox inline" for="session_remember_me">
<input name="session[remember_me]" type="hidden" value="0"><input type="checkbox" value="1" name="session[remember_me]" id="session_remember_me">
<span>Remember me on this computer</span>
</label>
<input type="submit" name="commit" value="Log in" class="btn btn-primary">
</form>
Anyone could help me ? and I'm so sorry for this newbie question
var params = {
utf8: "the utf8 value"'
authenticity_token : "token value",
session:{
email:"email#mail.com",
password : "apassword"
}
};
$http.post("https://mywebsite/login", params)
.success(function(data) {
$state.go('improvements');
}).error(function(data) {
console.log(data)
var alertPopup = $ionicPopup.alert({
title: 'Login failed!',
template: 'User/Password is Wrong'
});
});

angular form validation not working on form submitting

I'm new in angularJS. My form doesn't validate on submit. I use angular-validation module downloaded from bower. How can I validate form on submit button?
I use refrence from https://github.com/huei90/angular-validation/blob/master/API.md
My form is like that:
<div ng-controller="nameController">
<form name="myForm" ng-submit="submitForm()">
<label for="ud_fname"></label>
<input
type="text"
id="ud_fname"
name="ud_fname"
placeholder="First Name"
ng-model="form.ud_fname"
valid-method="blur"
validator="required"
required-error-message="Required"
>
<label for="ud_lname"></label>
<input
type="text"
id="ud_lname"
name="ud_lname"
placeholder="Last Name"
ng-model="form.ud_lname"
valid-method="blur"
validator="required"
required-error-message="Required"
>
<input type="submit" value="Add" class="pure-button" />
<input type="reset" value="Reset" class="pure-button" />
</form>
My Controler is like that:
app.controller('nameController', function ($scope, $http) {
// insert record
$scope.submitForm = function (){
var url= 'functions/insert.php';
var data = {
ud_fname: $scope.form.ud_fname,
ud_lname : $scope.form.ud_lname,
};
console.log(data);
$http({
url: url,
data: data,
method: 'post'
}).success(function (response){
console.log(response);
});
};
});
You need to validate on ng-submit & don't call an submitForm if its not valid form
ng-submit="myForm.$valid && submitForm()"
You need to validate the form in your controller as well. Also, it would be better if you pass the form (user) as a parameter. If you are writing unit tests (which you should), it would be easier to test your method easily in that case as there will be no coupling with $scope.
P.S. Migrate your code to controllerAs syntax, you won't regret it.
$scope.submitForm = function (user, isValid){
if (isValid) {
var url= 'functions/insert.php';
var data = {
ud_fname: user.ud_fname,
ud_lname : user.ud_lname,
};
console.log(data);
$http({
url: url,
data: data,
method: 'post'
}).success(function (response){
console.log(response);
});
}
};
And your form will become:-
<form name="myForm" ng-submit="submitForm(form, myForm.$valid)">
.....
</form>

Submit form with ng-submit and trigger synchronous post request

I have a form that I want to trigger validation on when the user clicks submit. If the validation fails, then suitable error messages are displayed. This much works.
However if the validation passes I want the form to submit a synchronous POST request with full page reload as if the action and method parameters were set as usual.
How does one achieve trigger the normal post action (not AJAX) from the ng-submit function on the AngularJS scope?
My form of course looks basically like the following:
<form id="myForm" name="myForm" ng-submit="formAction(this, models)">
...
<input type="submit" value="Submit">
</form>
The best I can think of is to mirror the contents of the form with another hidden form submitting that one, but there must be a better way!
TO CLARIFY: If validation passes, I need the form submission to essentially behave like a normal synchronous post form submission which lands the user at the page returned by the server from the post request.
http://plnkr.co/edit/cgWaiQH8pjAT2IRObNJy?p=preview
Please check this plunkr
Basically what I am doing is passing the $event object. form is the target of the event object, and we can submit it.
function Ctrl($scope) {
$scope.list = [];
$scope.text = 'hello';
$scope.submit = function($event) {
if ($scope.text) {
$scope.list.push(this.text);
if(this.text === 'valid'){
$event.target.submit();
}
$scope.text = '';
}
};
}
Try inside formAction after you've submitted the data:
$route.reload();
I dont think you need to do a full page refresh. You have a single page app I am assuming; use it. Try something like this:
<section class="contact">
<article>
<h1>Contact</h1>
<form role="form" name="contactForm" ng-submit="formSubmit(contactForm)">
<div class="form-group">
<input class="form-control" ng-model="name" name="name" id="name" type="text" placeholder="Name" required/>
</div>
<div class="form-group">
<input class="form-control" ng-model="email" name="email" id="email" type="email" placeholder="Email Address" required/>
</div>
<div class="form-group">
<textarea class="form-control" ng-model="message" name="message" id="message" rows="5"></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-lg">Send Message</button>
<a class="btn btn-default btn-lg" href='mailto:me#something.net'>Or email me</a>
</div>
</form>
</article>
'use strict';
MyApp.controller('ContactController', function ContactController ($scope, EmailService) {
$scope.formSubmit = function(form) {
EmailService.send(form).then(function(data) {
if(data.message.sent) {
$scope.resetForm();
alert("Message Sent");
}
else {
alert("Something went wrong. Try emailing me.");
}
});
}
$scope.resetForm = function() {
$scope.name = "";
$scope.email = "";
$scope.message = "";
}
});
MyApp.factory('AjaxService', function AjaxService ($q, $http) {
return {
http: function(ajaxParams) {
var deferred = $q.defer();
$http(ajaxParams)
.success(function (data, status, headers, config) {
deferred.resolve({
success: true,
status: status,
message: data
});
})
.error(function (data, status, headers, config) {
deferred.reject({
success: false,
status: status,
message: "Http Error"
});
});
return deferred.promise;
}
}
});
MyApp.factory('EmailService', function EmailService (AjaxService) {
return {
send: function(emailData) {
var ajaxParams = {
method: 'POST',
url: ''//where ever your form handler is,
data: {
name: emailData.name.$modelValue,
email: emailData.email.$modelValue,
message: emailData.message.$modelValue
},
cache: false
}
return AjaxService.http(ajaxParams);
}
}
});

Resources