Take string from input and make an AJAX request in AngularJS - javascript

Here is my code :
http://jsfiddle.net/n8t2born/1/
there are 3 js files , and it works pretty much good when I use static URL (without inputCity variable inside) . How should I tell angular correctly to take that info from my input and put it into the link and show weather info for a particular city ?
This is my form:
<form class="form-container" ng-submit="Weather.getWeather(inputCity)">
<input class="input-field" type="text" ng-model="inputCity" placeholder="City">
<input class="button-style" type="submit" value="Show Weather">
</form>
and it is my angular.factory:
angular
.module('weather.factory', [])
.factory('Weather', [
'$http',
function($http) {
return {
getWeather : function(inputCity) {
return $http({
url: 'http://api.wunderground.com/api/KEY/conditions/q/' + inputCity + '.json',
method: 'GET'
})
}
}
}
]);

You should never call you service method from your controller which has promise, It should call from controller & then update you required location data in ajax sucess
HTML
<form class="form-container" ng-submit="submitForm(inputCity)">
<input class="input-field" type="text" ng-model="inputCity" placeholder="City">
<input class="button-style" type="submit" value="Show Weather">
</form>
Code
$scope.submitForm =function(inputCity){
Weather.getWeather(inputCity).success(function(){
//data updation will lie here
}).error(function(error){
//do error handling here
})
};

Related

using EmaiJS, error on service and template ID

I am currently experimenting with the EmailJS library, I have followed the documentation to what I thought was 100%, I placed the code in the script tag that is embedded in the head on the contact.html, when I send the form, I get a error in the console that says "unexcepted", I created a file called sendEmail.js and wired it to my contact.html, and tried it there, here is the issue:
I am being told that my service ID is incorrect, I went, updated it, and then was told my template ID is incorrect too, so I updated that, saved it and tried again, its still not working, please see attached screenshot of the details on my test emailJS account:
Service ID:
Service ID
Template ID:
Template ID
Here is my contact.html code:
This is my init method in the
<script type="text/javascript">
(function() {
emailjs.init("user_vanqZMkpPOADQP2iEpqKS");
})();
</script>
Here is my form code:
<form onsubmit="return sendMail(this);">
<input type="text" name="name" class="form-control" id="fullname" placeholder="Name" required/>
<input type="text" name="emailaddress" class="form-control" id="emailaddress" placeholder="Email" required/>
<textarea rows="5" name="projectsummary" class="form-control" id="projectsummary" placeholder="Project Description" required></textarea>
<button type="submit" class="btn btn-secondary center-block">Send Project Request</button>
</form>
Here is my sendEmail.js code:
// function has one one argument "contactForm"
function sendMail(contactForm) {
const templateParams = {
"from_name": contactForm.name.value,
"project_request": contactForm.projectsummary.value,
"from_email": contactForm.emailaddress.value
};
const serviceID = "service_golcdlt";
const templateID = "template_7qaoafp";
// Service ID, Template ID, template parameters
emailjs.send(serviceID, templateID, templateParams)
.then(
function(response) {
console.log("SUCCESS", response)
},
function(error) {
console.log("Error: Unable to send", error)
}
);
return false; // To block from loading a new page
};
What am I missing or doing wrong?

AngularJS post Data to nodeJs/Sequelize

I am creating an e-commerce web site with Nodejs/Sequelize and AngularJs.
I am actually got this starter AngularJS starter.
In my project I got 2 folders :
Client (which contains AngularJS starter folders)
Server (which contains my server.js
I would like to register a user, I got my "registeredView.html" with a form :
<form ng-submit="submit()">
<input type="text" name=firstname ng-model="user.firstname" placeholder="firstname" required=" ">
<input type="text" name="lastname" ng-model="user.lastname" placeholder="lastname" required=" ">
<input type="email" name="email" ng-model="user.email" placeholder="Email Address" required=" ">
<input type="password" name="password" ng-model="user.password" placeholder="Password" required=" ">
<input type="password" name="confirm_password" ng-model="user.confirm_password" placeholder="Password Confirmation" required=" ">
<input type="submit" value="Register">
</form>
For now, I could get those datas in my "RegisteredController" thanks to the $scope.user but I don't know how to send those data to my server.
I am using express module so I tried with $http.post like this :
.controller('RegisteredController', ['$scope', function ($scope, $http) {
$scope.submit = function () {
$http.post('/registered', $scope.user)
then(function (response) {
console.log("posted")
}).catch(function (response) {
console.error(response)
})
}
}]);
And on my "server.js" I tried to get this post like this :
app.get('/registered', function (req, res) {
console.log(req.body)
res.end();
});
But it dont works..
What I wrong ? Some Advice ?
I need your helps guys please :)
As discussed in the comments there are 3 immediately apparent issues:
Your server is expecting a get, not a post, change app.get('/registered'...) to app.post('/registered'...).
You're missing a dot here: $http.post('/registered', $scope.user)then(function (response) {, between the closing ) and then.
You need to mark your $http to be injected, as with $scope - change ['$scope', function ($scope, $http) to ['$scope', '$http', function ($scope, $http).
To be able to do something with your posted data you should check out body parser. After requiring it you can do the following - app.use(bodyParser.json()). Then you should have access to req.body which should contain your user parsed as a javascript object.

Convert HTML form into Angular POST request

I have this form in HTML and I am trying to convert it into a POST request using a frontend framework (either AngularJS or Angular2). The purpose of this form is to allow a client to subscribe to my wordpress blog. I am trying to convert it from PHP to Angular2 (if someone knows how to convert it to AngularJS I can convert to Angular2 from there). How would I do this? What would have to be in the body of the POST request vs query strings? I am having trouble understanding exactly what role each part of this form plays in the POST request.
EDIT: Just to clarify, I know how to use AngularJS and Angular2 and how to use the HTTP service in both of them. I am wondering how to convert the form into the body/query strings of the request.
<form action="/blog/" class="form-inline" role="form" method="POST" accept-charset="utf-8" id="subscribe-blog">
<!-- add hidden inputs for wordpress jetpack widget -->
<input type="hidden" name="action" value="subscribe" />
<input type="hidden" name="source" value="http://www.mywebsite.com/blog/" />
<input type="hidden" name="sub-type" value="widget" />
<input type="hidden" name="redirect_fragment" value="blog_subscription-2" />
<label class="sr-only" for="exampleInputEmail">Email address</label>
<input type="email" class="form-control wide" id="exampleInputEmail" placeholder="Enter email address">
<button type="submit" name="jetpack_subscriptions_widget" class="btn btn-submit">Subscribe</button>
</form>
Would something along the lines of this be correct?
postForm() {
var body = {
action: 'subscribe',
source: 'http://www.mywebsite.com/blog/',
sub-type: 'widget',
redirect_fragment: 'blog_subscription-2',
email: 'clientEmailAddress#gmail.com', // don't think this is right
// not sure what to do with `jetpack_subscriptions_widget` attribute on the submit button either
};
return this.http.post(`http://www.mywebsite.com/blog/`, body)
.map(res => res.json())
.toPromise()
.then(data => {
return data;
});
}
You need to include angular.min.js and script.js
html
<body ng-app="myApp" ng-controller="myCtrl">
<input type="text" ng-model="name" />
<input type="submit" value="Send" ng-click="send(name)"/>
</body>
angular js code:
script.js
angular.module('myApp', [])
.controller('myCtrl', ['$scope', '$http', funtion($scope, $http){
$scope.name = ""; // intially the input field is empty. As you type in the input field, the value will be updated here.
$scope.send = function(name){
alert(name);
var url = $scope.name; // try to enter an url
$http.get(url).then(function Success(res){
// here you can do anything with res
}, function Error(err){
alert(error);
})
}
}]);
Using angular, you split the application in parts:
view (html)
process some validations, etc (controller)
and do some model logic processing (service).
If you want to make the http request completely with angular to an endpoint (backend service, REST, or any other), usually in this case:
You use ng-model for each input field you need to send in the request, something like <input type="text" ng-model="val">. In your case your html would be something like:
html
<form ng-submit="send()" class="form-inline" role="form" accept-charset="utf-8" id="subscribe-blog">
<!--no need of 'action' attribute in the form since the post will be done using angular-->
<!-- add hidden inputs for wordpress jetpack widget -->
<input type="hidden" name="action" value="subscribe" ng-model="subscribe"/>
<input type="hidden" name="source" value="http://www.mywebsite.com/blog/" ng-model="source"/>
<input type="hidden" name="sub-type" value="widget" ng-model="widget" />
<input type="hidden" name="redirect_fragment" value="blog_subscription-2" ng-model="redirect_fragment"/>
<label class="sr-only" for="exampleInputEmail">Email address</label>
<input type="email" class="form-control wide" id="exampleInputEmail" placeholder="Enter email address" ng-model="email">
<button type="submit" name="jetpack_subscriptions_widget" class="btn btn-submit">Subscribe</button>
</form>
Then in your controller you can process all your ng-model if needed and then pass those values to a (angular) service like this
//....angular controller
function send(){
//..collect params using the ng-models
var params = [];
params['email'] = $scope.email; //here you define 'email' as the name of the param received by the webservice as input !!!
myService.sendValues(params).then(function(data){
})
}
...where you would finally send the values to the php service like code below:
//... angular service
function sendValues(params){
var url = "miendpointurl/subscribe";
//... at this pont in params you have all those params you named like 'email', 'subscribe' and so on
return $http.post(url, params).then(function(response){
return response.data;
},
function(responseOnError){
return responseOnError.data;
}
}
Angular will interact with the php service transparently to you and will give you back the server response.

POST is not getting current values from angular

In my view there are two forms (one is visible, second one is hidden). First one as action calls submit1() function in controller, that in turn will invoke document.getElementById('form2').submit(); Second form action has method POST that directly calls php.
Now I cannot get why if my submit1() looks like this:
function submit1()
{
// doesnt matter
$scope.first = 'this is my string'; // here I'm modifying variable from $scope1 that is directly in form2
document.getElementById('form2').submit(); // problem here!
// doesn't matter
}
It does not work as expected.
Basically, when form2 is sent, it still has a default value (not changed one).
Looks like it would not really change variable outside the scope of function submit1() or like POST would not accept this change. Anyone can tell me why it is like that?
Moreover I was previously using $http post method instead document.getElement().submit() and it works fine. So this seems to be weird.
I would appreciate any help in this matter.
Thank you!
Edit1: (adding more code to properly define what is a problem):
view:
<div class="container">
<div ng-hide="true" >
<form action="./order2.php" id="form2" method="POST">
<input type="text" name="username" value="{{username}}"/>
<input type="text" name="phone" value="{{phone}}"/>
<input type="text" name="address" value="{{address}}"/>
<input type="text" name="price" value="{{totalPrice}}"/>
<input type="text" name="email" value="{{email}}"/>
<input type="text" name="message" value="{{text}}"/>
<input type="submit"/>
</form>
</div>
<form novalidate id="contact-form" name="contactForm">
<a class="btn btn-success" ng-click="submit1()" href>
<i class="fa fa-check-circle-o fa-lg"></i>
{{ 'ID_ORDER_BUTTON' | translate:$root.currentLang }}
</a>
</form>
</div>
Controller:
Appcontrollers.controller('controller1', function($scope, $http, $rootScope, $timeout, $routeParams, $window, $location, databaseService, translationService, cartService, leatherService, $location) {
$scope.text="";
$scope.email="11111#2222.com";
$scope.price=0;
$scope.address= "add";
$scope.phone="1213131";
$scope.username="usera";
$scope.submit1 = function() {
$scope.price=999999999; // this looks like doesn't have effect.
document.getElementById('form2').submit();
}
}

Django submit form without page refresh

I'm using Django-Angular and trying to post a form and obtain data in back-end..I'm able to achieve this but found that the page is reloading while saving the form. How can we achieve the same without page render?
forms.py
def home(request):
if 'application/json' in request.META['CONTENT_TYPE']:
print 'hi'
print request.body
return render(request, 'home.html', {})
home.html
<form name="indexForm" ng-submit="submitForm()">
<div class="form-group">
<label>File Path</label>
<input type="text" name="path" class="form-control" ng-model="file.path">
</div>
<div class="form-group">
<label>File Name</label>
<input type="text" name="file_name" class="form-control" ng-model="file.file_name">
</div>
<div class="form-group">
<label>ext</label>
<input type="text" name="ext" class="form-control" ng-model="file.ext">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
script
$scope.submitForm = function() {
console.log('from submit')
$http({
url: 'http://127.0.0.1:8000/',
data: $scope.file,
method: 'POST',
headers: {
'X-CSRFToken': $cookies['csrftoken']}
})
}
Please let me know code above is correct way of posting data? How can we post data from angular to backend(django) without page refresh
Thanks in advance...Any help is much appreciated
In your home request you should not render the page again, but rather return a string or some JSON to the client. If you are using a newish version of django you can do something like this:
from django.http import JsonResponse
def home(request):
if 'application/json' in request.META['CONTENT_TYPE']:
print 'hi'
print request.body
return JsonResponse({'foo':'bar'})
return render(request, 'home.html', {})
Replace type="submit with type="button". Then you can just call any method in the backend with ng-click="ctrl.foo()"
At least that is what I have been doing so far. Looking at the docs however indicates that is not the issue.

Categories