I followed the following tutorial (https://code.tutsplus.com/tutorials/laravel-4-a-start-at-a-restful-api-updated--net-29785) to create a REST API with Laravel. Here we're creating a new Url which gets two inputs: a url and description and stores it to a database.
public function store()
{
$url = new Url;
$url->url = Request::get('url');
$url->description = Request::get('description');
$url->user_id = Auth::user()->id;
$url->save();
return Response::json(array(
'error' => false,
'urls' => $urls->toArray()),
200
);
}
In trying to teach myself AngularJS, I've been trying to connect this REST API with an AngularJS front end. Here's my form:
<form data-ng-controller="formController">
<p>Store a URL To Read Later:</p>
<div class="form-group">
<input class="form-control" type="text" placeholder="Enter URL here" data-ng- model="newurl" />
</div>
<p>Description:</p>
<div class="form-group">
<input class="form-control" type="text" placeholder="Enter a brief description" data-ng-model="newdescription" />
</div>
<div class="form-group text-right">
<button class="btn btn-success" data-ng-click="submitUrl()">Add To List</button>
</div>
</form>
The data-ng-click is calling the submitUrl function which I have defined in the FormController.
function formController($scope, $http) {
$scope.submitUrl = function() {
var data = { 'url': $scope.newurl, 'description': $scope.newdescription };
$http.post("http://readitlater.loc/api/v1/url/", data )
}
}
I guess I'm puzzled as to how to get the input data to the public function store() and what kind of data it's expecting. Thanks for your time.
I figured it out. Rewriting like this, solved the problem.
function formController($scope, $http) {
$scope.submitUrl = function() {
var data = { 'url': $scope.newurl, 'description': $scope.newdescription };
$http({
method: 'POST',
url: 'http://readitlater.loc/api/v1/url/',
headers: { 'Content-Type' : 'application/x-www-form-urlencoded'},
data: $.param(data)
});
AngularJS sends POST requests with application/json type & JSON body by default. I'm not familiar with Laravel, but looks like using Input instead of Request is what you need: http://laravel.com/docs/4.2/requests#basic-input
Related
I am currently trying to set up a EasyPost API and I need to store some information contained in a response from a POST route. I would like to send the data from the response straight to the client for storage, but I am unable to find out where or how to send the information.
This is my form receiving the information:
<div ng-controller="easypostController as epc" class="col l6">
<!-- -->
<h2>Customer address</h2>
<form class="blue-grey darken-4">
<input ng-model="epc.address.name" placeholder="Name">
<input ng-model="epc.address.street1" placeholder="Street 1">
<input ng-model="epc.address.street2" placeholder="Street 2">
<input ng-model="epc.address.city" placeholder=" City">
<input ng-model="epc.address.state" placeholder="State">
<input ng-model="epc.address.zip" placeholder="Zip">
<input ng-model="epc.address.country" placeholder="Country">
<input ng-model="epc.address.phone" placeholder="Phone">
<a class="waves-effect waves-light btn" ng-click="epc.sendAddress()">Verify</a>
</form>
</div>
This is the controller passing the information from the form to the factory:
function easypostController(easypostFactory) {
var epc = this
epc.address = {}
epc.sendAddress = function() {
epc.resId = {}
easypostFactory.send(epc.address)
.then(function(res) {
console.log("Successfullly sent address epc")
// epc.resId = easypostFactory.resId
epc.address = {}
})
// console.log(epc.resId)
}
}
This is my factory that passes the information to the server:
address.send = function(address) {
return $http.post(addressUrl, address)
// epf.resId = address
console.log(address, "=====")
}
And this is where I am having issues, I am not able to get any res.send() function to send the response object back to the client side.
var address = easypost.Address.create(req.body, function(err, fromAddress) {
var verifiedAddress = {}
fromAddress.verify(function(err, response) {
console.log("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=")
if (err) {
console.log('Address is invalid.')
} else if (response.message !== undefined && response.message != null) {
console.log('Address is valid but has an issue:', response.message)
var verifiedAddress = response.address
} else {
verifiedAddress = response.address
console.log(verifiedAddress)
res.send(verifiedAddress)
}
})
})
The verifiedAddress is the correct object as logged by my server I am just unable to send the response object to the client. Any help would be greatly appreciated.
Thanks
rather than use angular js for frontend, try to use a simple html form. here is the example :
<form name="simple" action="someurl" method="post"> <input type="text" name="username"> </form>
And you can get the value of the input text by these codes :
router.post("someurl", function(req,res){ var username = req.body.username }) console.log(username)
Hope this will help you :)
I have enclosed my service function here. Iam trying to send a simple data to node backend but nothing happens. But at this API Endpoint the things works well its saving data in good shape(in postman). Iam sure iam wrong somewhere here in angular No Errors are triggering. No http request is raised.
App.service('UserServices', function($rootScope, $http) {
this.AddToInviteList = function(email, cb) {
var url = $rootScope.api_server_url + "/users/addtoinvitelist";
$http({
method: 'POST',
url: url,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
} // set the headers so angular passing info as form data (not request payload)
}).success(function(data) {
console.log("email is posted sucessfully" + data);
cb(data);
})
}
})
and my controller code is here,
App.controller('InviteController', function($scope, $rootScope, $routeParams, $location, UserServices) {
$scope.AddToInviteList = function(email) {
UserServices.AddToInviteList(email, function(dataresponse) {
console.log(dataresponse);
})
}
});
And my HTML View div is below.
<div class="tab-content">
<!--NEWSLETTER FORM-->
<div class="panel panel-minimalize">
<h2 class="signin-brand animated-hue"> <i class="fa fa-rocket"></i> MEDICOSHERE</h2>
<div class="panel-body bg-inverse ui-corner-all">
<form action="#">
<div class="form-group">
<label for="subcribeNewsletter" class="control-label">INVITE FORM<br> <small>We are happy to invite you to medicoshere, So please enter your email ID in the below form.</small></label>
<div class="input-group input-group-in input-group-sm">
<div class="input-group-addon"><i class="fa fa-envelope text-belpet"></i></div>
<input class="form-control" id="subcribeNewsletter" placeholder="johndoe#mail.com" ng-model="email" required>
<div class="input-group-btn">
<button type="submit" class="btn btn-default text-belpet" ng-click="AddToInviteList(email)"><strong>OK</strong></button>
</div>
</div>
</div><!-- /.form-group -->
</form><!-- /form -->
</div><!-- /.panel-body -->
</div><!-- /.panel -->
<!--/END NEWSLETTER FORM-->
</div><!-- /.cols -->
</main>
Will it would be nice to have a bit more of information regarding your problem but I already see some potential issues.
First of all I hope that App variable (App.service) is an instance of your angular's main module.
Also, I believe you must return the function in an object at the begging or end of your service declaration. That way it'll work as expected when calling it from your controller.
So I believe it should look something like this:
var App = angular.module('myApp');
App.service('UserServices', function($rootScope, $http) {
this.AddToInviteList = function(email, cb) {
var url = $rootScope.api_server_url + "/users/addtoinvitelist";
$http({
method: 'POST',
url: url,
headers: { 'Content-Type': 'application/x-www-form-urlencoded '
}
// set the headers so angular passing info as form data (not request payload) })
.success(function(data) {
console.log("email is posted sucessfully" + data);
cb(data);
})
}
return {
AddToInviteList:AddToInviteList
}
})
Sorry for the bad indentation :) writing from a smartphone.
Hope it helps!
EDIT
Also, are you sure you added the file to your index.html? :D
Another thing to check
You might want to check in your routing is OK. Perhaps you're not associating that view to the right controller. That or not including the service file could be one of the reasons you're not getting any errors.
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>
In my Angularjs MVC application i write code for lo-gin which accept values from two text boxes as user name & password
my Angularjs controller code is as which works fine but problem with view
$scope.Login = function Login(U_Name, U_PWD) {
//Defining the $http service for login the admin user
$http({
method: 'POST',
url: '/Admin/IsAuthenticate',
data: { User_Name: U_Name,
User_PWD: U_PWD }
}).success(function (result) {
if (result == true) {
alert('user is valid');
}
else {
alert('unauthorised access!');
}
})
.error(function (error) {
//Showing error message
$scope.status = 'Unable to connect' + error.message;
});
}
this code is executing on ng-click event but doesn't accept values from input boxes
my view code is as:
<div ng-app="angApp">
<div ng-controller="AdminCtrl">
<div class="admin-login">
<h2>using angularjs</h2>
<input type="text" id="txtUserAng" placeholder="User Name" ng-model="U_Name" />
<input type="password" id="txtPWDAng" placeholder="Password" ng-model="U_PWD" />
<input type="button" id="login" value="login" ng-click="Login()" />
</div>
</div>
</div>
Your problem is that you are not passing U_Name, U_PWD variable to Login function. You need to pass input values to your function.
There are 2 ways of achieving it.
First, Pass the model directly to function like
<input type="button" id="login" value="login" ng-click="Login(U_Name, U_PWD)" />
Second, Use $scope.U_Name and $scope.U_PWD
$scope.Login = function() {
var U_Name = $scope.U_Name,
U_PWD = $scope.U_PWD
}
In controller get this
this example without set login parametr
$scope.Login = function Login() {
var U_Name = $scope.U_Name;
var U_PWD = $scope.U_PWD;
console.log($scope.U_Name);
console.log($scope.U_PWD);
}
And you can set login function parrameters that model
<input type="button" id="login" value="login" ng-click="Login(U_Name, U_PWD)" />
use this
data:
{
User_Name: $scope.U_Name,
User_PWD: $scope.U_PWD
}
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);
}
}
});