Convert HTML form into Angular POST request - javascript

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.

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?

Laravel Query Ajax Update

Hello someone can you explain me how to update with Ajax!!
I use laravel
I want html and ajax only
My routes
Route::post('/post/homepage', 'AdminController#HomePage');
First, you should name your route:
Route::post('/post/homepage', 'AdminController#HomePage')->name('post.create');
Then, create your HTML form :
<form id="myForm">
{{csrf_field()}}
<label for="name">Article Name :</label>
<input id="name" name="articleName" type="text" required>
<button type="submit">Save</button>
</form>
Note: {{csrf_field()}} will generate the Form CSRF field. Or you can use instead :
<input type="hidden" name="csrf_token" value="{{csrf_token()}}">
I'll use jQuery to handle ajax:
<script type="text/javascript">
$(document).ready(function (){
$('#myForm').submit(function (e) {
e.preventDefault(); //Do not submit the form
var dataflow=$(this).serialize(); //Get the inputs value
$.post('{{route('post.create')}}', dataflow, function (data){ //post.create is the route name
//The request is done, do something with the server response
});
});
});
</script>

I can't access ng-model from a controller [AngularJS]

I'm developing an e-commerce site for learnign purposes.
HTML:
<div class="container">
<form class="log-in-form" ng-controller="ControllerLogin">
<div class="form-group">
<label for="loginEmail">Email address</label>
<input type="email" class="form-control" id="loginEmail" placeholder="Email" ng-model="email">
</div>
<div class="form-group">
<label for="loginPass">Password</label>
<input type="password" class="form-control" id="loginPass" placeholder="Password" ng-model="password">
</div>
<button class="btn btn-default" ng-click="authenticate()">Login</button>
</form>
</div>
Angular javascript
app.controller('ControllerLogin', ['$scope', '$http', 'ServiceLogin', function ($scope, $http, ServiceLogin) {
$scope.authenticate = function () {
console.log($scope.email);
ServiceLogin.auth($scope.email, $scope.password)
.success(function (data) {
alert(data);
});
}
}]);
Every time I console.log the $scope.email, or password. It throws an error of undefined. I'm just starting on angular and I don't know why is not getting the models, I thinks my code is correct. Any help you can give I will be gratefull.
From Angular site:
Note that novalidate is used to disable browser's native form validation.
The value of ngModel won't be set unless it passes validation for the input field. For example: inputs of type email must have a value in the form of user#domain.
Reference: https://docs.angularjs.org/guide/forms
So the reason it may be blank is that it's not a valid email.
You can look at their demo for the email type and see it in action.
I recommend adding:
{{email}}
<br>
{{password}}
somewhere in your html within the controller's HTML scope for your own debugging.
Good luck.

Take string from input and make an AJAX request in AngularJS

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
})
};

How can I pass in this data into a form submit call (similar to data parameter for an ajax post)?

I have the following code that submits data to an asp.net-mvc controller action via jquery ajax
var queryString = "name=Joe&age=22&weight=200";
$.ajax({
url: '/MyController/Generate',
type: 'post',
data: queryString,
dataType: 'json'
});
this works fine and binds to the controller action parameter
public ActionResult Generate(MyParams p)
{
Console.Write(p.name);
Console.Write(p.age);
Console.Write(p.weight);
}
The issue now is that I need to change this from ajax to being a regular form post (I need to use regular form post as I am now returning a file from the controller action). I am trying to figure out how I can get that same querystring variable to get submitted as part of a regular form post (non ajax).
Is this possible?
try with html.beginform
#using (Html.BeginForm("Generate", "MyController","name=Joe&age=22&weight=200", FormMethod.Post, new { id = "frmMyForm" }))
{
// Your form elements
}
If you want that data to be fixed you can make a form like this:
<form action="/MyController/Generate" method="post">
<input type="hidden" name="name" value="Joe" />
<input type="hidden" name="age" value="22" />
<input type="hidden" name="weight" value="200" />
<input type="submit" />
</form>
Otherwise, if you want the data to be editable, it goes like this:
<form action="/MyController/Generate" method="post">
<input type="text" name="name" />
<input type="number" name="age" />
<input type="number" name="weight" />
<input type="submit" />
</form>

Categories