This is my partial view -
<form action="" ng-controller="Ctrl as forgot" name="forgotForm" ng-submit="forgotForm.$valid && forgot.sendPost()">
<div class="form-group row">
<label for="email" class="col-sm-2 form-control-label">Email address</label>
<div class="col-sm-9">
<input type="email" ng-model="forgot.emailData" class="form-control" id="email" name="email" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,3}$" placeholder="Email Address" required/>
</div>
</div>
<div class="form-group row">
<div>
<button class="btn btn-info submitButton">Submit</button>
</div>
</div>
</form>
This is a method in my controller -
self.sendPost = function() {
console.log(self.emailData); //the value I entered in the input box
$http.get("https://api?email=rq895#msstae.edu")
.success(function(data, response, headers, config) {
console.log("Success Data " + response);
})
.error(function(data, response, headers, config) {
console.debug("Returned Data ");
});
};
For example, if I enter the value abc#abc.com in the input box, I see that the actual value I enter in the form has been sent to the api (The value of self.emailData). I get a response of 200.
Following are the problems I am having,
1) Why is self.emailData being sent when I am clearly specifying the email address to be sent to be rq895#msstae.edu
2) Since I get a response of 200, why is the success callback not being fired.
Success and error are deprecated. Try refactoring your code to something like:
self.sendPost = function() {
console.log(self.emailData); //the value I entered in the input box
$http.get("https://api?email=rq895#msstae.edu")
.then(function successCallback(response) {
console.log(response)
}, function errorCallback(response) {
console.debug(response);
});
};
First Tip :
Please dont have the business logic in the controllers. Move it in services and inject the service in the controller.
As per your answer try using then with success and error handlers. AN example of it is given beloe
$http.get(URL).then(successCallback, errorCallback);
function successCallback(){
}
function errorCallback(){
}
Hope this be of some help.
Happy Learning :)
Related
I have been battling with what is wrong on this code since. It so happens that the form is not submitting on this button. The button is of type button and not in the form tag.
$("#step1Btn").click(function () {
var userForm = $("form[name='step1Form']");
if (userForm.valid()) {
userForm.submit(function () {
console.log('submitted o!')
$("#spin1").show();
$("form[name='step1Form'] > span").remove();
$('input[name="emailInput"]').prop('name', "id")
$('input[name="fullNameInput"]').prop('name', "full-name")
$('input[name="phoneInput"]').prop('name', "phone-number")
$.ajax({
type: 'POST',
url: "api/v1/user?" + $(this).serialize(),
success: (result) => {
localStorage.setItem('user', JSON.stringify(result))
localStorage.setItem('authToken', result.authToken);
$("form[name='step1Form'] > span").remove()
$('#step1, #step2').toggle();
$('#step1Title, #step2Title').toggle();
},
error: function (request, exception, errorThrown) {
$("form[name='step1Form'] > span").remove();
$("form[name='step1Form']").prepend('<span class=\'error\'><p>' + request.responseJSON.message + '</p></span>')
},
})
});
} else {
return false;
}
});
Below is the complete form
<div id="step1" class="col-12 col-md-6">
<form name="step1Form">
<div class="home-icon d-flex justify-content-center align-items-center flex-column">
<img src="images/new-icons/user.png" alt="User Registration logo" height="80" />
<p class="my-3">User Registration</p>
</div>
<div class="form-group">
<label for="fullNameInput">Contact full name</label>
<input name="fullNameInput" class="form-control custom-input" placeholder="First name Last name" id="fullNameInput">
</div>
<div class="form-group">
<label for="emailInput">Contact email address</label>
<input name="emailInput" type="email" placeholder="example#email.com" class="form-control custom-input" id="emailInput">
</div>
<div class="form-group">
<label for="confirmEmailInput">Confirm contact email address</label>
<input name="confirmEmailInput" type="email" placeholder="example#email.com" class="form-control custom-input"
id="confirmEmailInput">
</div>
<div class="form-group">
<label for="phone">Contact phone number</label>
<input name="phoneInput" placeholder="08012345678" class="form-control custom-input" id="phone">
</div>
</form>
<button type="button" class="btn red-btn user-btn custom-btn" id="step1Btn">Next<i id="spin1" class="fa fa-spinner fa-spin"></i></button>
</div>
So I would like to see where I went wrong. I am able to log and see output whenever i place a console.log in between the if(userForm.valid) and the userForm.submit().
But as soon as i place it in the userform.submit() I do not get any value back. Like, the form is totally not submitting. I dont know if its because of how I made my Ajax call.. Please Help
You're putting Ajax inside of a submit....
$("#step1Btn").click(function () {
....
if (userForm.valid()) {
userForm.submit(function () {
....
$.ajax({ ....
Which makes no sense since Ajax replaces the actual submit. By doing this you are effectively sending it through validation again; I can't see the .validate() method, but suspect that you are simply using the default option, which would be yet another regular submit... you're probably stuck in a loop going nowhere.
The best place for your Ajax would be inside the submitHandler of the .validate() method.
If your button is outside of the form, you capture the click and manually trigger a submit, which then lets the validation plugin take over the rest.
$("#step1Btn").click(function () { // click of external button
$("form[name='step1Form']").submit(); // trigger validation & submission
});
$("form[name='step1Form']").validate({ // initialize plugin
submitHandler: function(form) { // fires when valid
// YOUR AJAX GOES INSIDE HERE
return false;
},
// other options, rules, etc.
});
Read the documentation for the submitHandler.
I am trying to send data from a Angularjs app to php in order to insert it into mysql db .
I have the index.html that contains the script,getUser_api.php page and insert.php page
I hav not error in console but I failed insert into mysql db.
So Is there any way to ensure if json data has been transmitted or nor
var app = angular.module("app",['ui.router']);
app.controller("insertCtrl", function($scope,$rootScope, $http) {
$scope.insert = function() {
$http.post(
"getUser_api.php", {
'Customer_Name': $scope.Customer_Name,
'Cust_mail': $scope.Cust_mail,
'Cust_Address': $scope.Cust_Address
}) ;
}
});
My insert.php page
<div class="well col-xs-8 col-xs-offset-2" style="margin-top: 10%" ng-controller="insertCtrl">
<form>
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" ng-model="Customer_Name">
</div>
<div class="form-group">
<label> mail</label>
<input type="text" class="form-control" ng-model="Cust_mail">
</div>
<div class="form-group">
<label>Address</label>
<input type="text" class="form-control" ng-model="Cust_Address">
</div>
</form>
<button class="btn-block btn-info" ng-click="insert()">Insert</button>
</div>
getUser_api
<?php
include('config.php');
$result=mysql_query('select * from customers');
$data['results']=array();
while($row=mysql_fetch_assoc($result)){
array_push($data['results'],$row);
}
if(count($data['results'])>0)
$data['status']='OK';
else
$data['status']='Z-Result';
echo json_encode($data);
?>
If you want to check manually, you can check it in the browser - developer tools in XHR tab.
In case if you want to catch error in the js end you can do:
var dataToSend = {
'Customer_Name': $scope.Customer_Name,
'Cust_mail': $scope.Cust_mail,
'Cust_Address': $scope.Cust_Address
};
var req = {
method: 'POST',
url: 'getUser_api.php',
data: JSON.parse(JSON.stringify(dataToSend))
};
$http(req).then(function (response) {
//handle success
}, function (error) {
//handle error
});
How to check manually in browser:
Open Chrome and press F12 for developer options
Click on Network
Click on XHR
Now in your html page click on the button which will call your inser method.
Your request will be displayed like following
Click on the request sent
Click headers
You will be able to see your Json in Request payload
I am stuck with angular's all type of $http requests I am trying to hit the rest API with $http but my code ran through it and do not show any call in chrome network tab. I am using python simplehttpserver for my project execution.
Below is the code of the service I am trying to hit
HTML CODE
<form class="form-horizontal" method="post" ng-submit="loginModel.login()">
<div class="form-group">
<div class="col-md-12">
<input type="text" class="form-control" placeholder="Username" ng-model="loginModel.username"/>
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<input type="password" class="form-control" placeholder="Password" ng-model="loginModel.password"/>
</div>
</div>
<div class="form-group">
<div class="col-md-6">
Forgot your password?
</div>
<div class="col-md-6">
<button type="submit" class="btn btn-info btn-block">Log In</button>
</div>
</div>
</form>
Controller Code
module.exports = function ($scope,$rootScope,$state,crudFactory,$http,$resource) {
var vm = this;
vm.login = login;
function login() {
var userDetail = {
username:vm.username,
password:vm.password
};
$http({
method: 'POST',
url:'http:example.com',
data:userDetail,
}).then(function (response) {
console.log(response)
}, function (response) {
});
}
I have inject $http in my controller and have also tried to hit the API with $resource but nothing is happening when i hit the service on click event.
I have tried this with core javascript and it works fine but why its not working $http or $resouce
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://www.example.com/", false);
xhr.send();
console.log(xhr.status);
Please help me on this
Thanks
It looks like your URL is not formatted correctly, and you aren't doing anything in the event of an error.
$http({
method: 'POST',
url:'http://example.com',
data:userDetail,
}).then(function (response) {
console.log(response)
}, function (response) {
console.log('error response', response);
});
This will at least show something in the console if there is an error.
If the url change still isn't working, check your browser developer console's network tab to see if the request is being made and if so, if it is timing out (stuck in pending state)
I have a login form which uses angularjs. I want to send the entered credentials to default AuthController in Laravel 5. the problem I have is that server returns 422 Unprocessable Entity and says in response : email field is required.
HTML :
<form class="login-form" ng-controller="LoginController" name="loginForm" novalidate>
<input type="hidden" name="_token" ng-model="_token" value="<?php echo csrf_token(); ?>">
<h3 class="form-title">
Login
</h3>
<div ng-show="msg" class="alert alert-danger ng-cloak">
<button class="close" data-close="alert"></button>
<span ng-repeat="m in msgs">
#{{m}}
</span>
</div>
<div class="form-group" ng-class="{'has-error' : loginForm.$submitted && loginForm.username.$error.required}">
<!--ie8, ie9 does not support html5 placeholder, so we just show field title for that-->
<label class="control-label visible-ie8 visible-ie9">
Username
</label>
<input ng-required="true" class="form-control form-control-solid placeholder-no-fix ltr" type="text" autocomplete="off" ng-model="username" name="username"/>
<span ng-show="loginForm.$submitted && loginForm.username.$error.required" class="help-block help-block-error ng-cloak">
Error Text
</span>
</div>
<div class="form-group" ng-class="{'has-error' : loginForm.$submitted && loginForm.password.$error.required}">
<label class="control-label visible-ie8 visible-ie9">
Password
</label>
<a href="javascript:;" id="forget-password" class="forget-password">
Text
</a>
<input ng-required="true" class="form-control form-control-solid placeholder-no-fix ltr" type="password" autocomplete="off" ng-model="password" name="password"/>
<span ng-show="loginForm.$submitted && loginForm.password.$error.required" class="help-block help-block-error ng-cloak">
Text
</span>
</div>
<div class="form-actions">
<button ng-click="login(loginForm.$valid,'.login-btn')" type="submit" data-loading-text="waiting" class="btn btn-success uppercase login-btn">ورود</button>
<label class="rememberme check pull-right">
<input type="checkbox" name="remember" ng-model="remember" value="1"/>
remember me
</label>
</div>
</form>
JS Controller :
this.msgs = '';
$scope.login = function (isValid, btn) {
if(isValid) {
$(btn).button('loading');
$scope.msgs = '';
data = {
username : $scope.username,
password : $scope.password,
_token : $scope._token
};
if($scope.remember)
data.remember = $scope.remember;
$http.post('/auth/login', data)
.success(function (data, status, headers, config) {
$(btn).button('reset');
$scope.msgs = '';
})
.error(function (data, status, headers, config) {
$(btn).button('reset');
// Handle login errors here
$scope.msgs = data;
});
}
};
How to fix the issue with default laravel controller while using username as identification?
If you want them to login with username instead of email, it should be as simple as setting the username property on your AuthController class
class AuthController extends Controller {
protected $username = 'username';
}
The reason is that AuthController uses the AuthenticatesUsers trait, which checks if the $username property is set and if not, defaults to 'email'
If you want them to have the option to login with username or email then that's another story. I wrote a blog post about it.
As per documentation, 422 error message is a semantic error.
The 422 (Unprocessable Entity) status code means the server
understands the content type of the request entity (hence a
415(Unsupported Media Type) status code is inappropriate), and the
syntax of the request entity is correct (thus a 400 (Bad Request)
status code is inappropriate) but was unable to process the contained
instructions. For example, this error condition may occur if an XML
request body contains well-formed (i.e., syntactically correct), but
semantically erroneous, XML instructions.
And in Laravel documentation, it says the by default, the email field is used as the "username":
By default, the auth.basic middleware will use the email column on the
user record as the "username".
I suggest you to edit the auth.basic parameter in middleware config in order to use "username" as the main username.
Because you're passing only the username and password (and remember) fields.
You probably need for an email key in the data object!
var data = { email: 'superman#gmail.com', username: 'SuperMan', password: 'ASDASD', rememberMe: true};
I have a controller that for some reason is submitting a form twice via a get request in AngularJs. I can see in my database that the form is being submitted twice, and also in the console network tab, it is logging the two submission, however, the first submission has the "Request Method" of OPTIONS, and the 2nd is GET. I think this may be a clue. I'm a bit confused, because i'm not passing in any 'options' into the get method, just the URL I am submitting to.
Html:
<div class="row">
<div ng-controller="groupEditCtrl">
<form class="span11" name="" novalidate ng-submit="createArtifact()">
<legend>Create a new group</legend>
<div class="row">
<div class="span5">
<div class="control-group">
<div class="controls">
<input name="text" type="text" placeholder="Group Name" required ng-model="artifact.group_name" />
</div>
</div>
</div>
<div class="span5">
<p>
<small>What your artifact will look like:</small><br />
{{artifact.group_name}}
</p>
</div>
</div>
<input name="token" type="hidden" required ng-model="window.token" />
<div class="control-group">
<div class="controls controls-row">
<button type="submit" class="btn" value="Submit" title="Submit">
<span>Submit</span>
</button>
</div>
</div>
</form>
</div>
</div>
Controller:
'use strict';
function groupEditCtrl($scope, $http, $routeParams, $cookie) {
$scope.createArtifact = function(){
var requestURL = window.base_url + "/Group/CreateGroup?callback=JSON_CALLBACK&token=" + window.token + "&group_name=" + $scope.artifact.group_name;
$http.get( requestURL ).
success(function(data, status, headers, config) {
console.log('You have successfully submitted a Cause/CreateCause');
}).
error(function(data,status,headers,config){
console.log('You have FAILED submitting a Cause/CreateCause');
});
}
};
A HTTP Options request is asking the server for the allowed methods that it can communicate with the server upon (amongst other things) so it's a normal thing to happen.
The Options request shouldn't change anything in your backend but it may well be logged as you're seeing. Double check that it isn't changing anything (and if it is then your backend may be configured wrong, and you should ask another question if it is!).
There's nothing wrong with your angular setup/use regarding the OPTIONS then GET.
For me headers: {'Content-Type': undefined} Work, And I don't see it call twice again.
$http.post("index.php", {id : $scope.A},{
headers: {'Content-Type': undefined}})
.success(function (response) {
$scope.OK = response.POLL;
}
}
Turns out this was an issue with the custom api being built that I wasn't aware of.