accessing angularjs textbox value in a controller - html

I am trying to learn AngularJS and require help in passing user entered text box text value after button click to append to a string url value while calling the http service.
I'm trying to add in the following way but it is showing me a value of undefined while appending the URl with the user entered text from the text box.
Here is my HtmlPage1.html
<form ng-submit="abc(inputValue)">
<input type="text" name="name" ng-model="inputValue" />
<button type="submit">Test</button>
</form>
and my script file Script.js
var app = angular.module("repos", [])
.controller("reposController", function ($scope, $http, $log) {
$scope.inputValue = null;
$scope.abc = function (value) {
$scope.inputValue = value;
};
$http({
method:'GET',
url: 'https://api.github.com/users/'+$scope.inputValue+'/repos'
})
.then(function (response) {
$scope.repos = response.data;
$log.info(response);
});
});
Can anyone help me in this regard on how to get the right value that the user has entered to appended to the URL?
Thanks in advance.

Your get call is placed before you enter any value. In order to call the API with inputValue, place the get call inside the button click.
Also, you do not have to pass the inputValue into the function from HTML, Angular's 2 way binding will do the job for you.
Ex:
HTML
<form ng-submit="abc()">
<input type="text" name="name" ng-model="inputValue" />
<button type="submit">Test</button>
</form>
JS:
var app = angular.module("repos", [])
.controller("reposController", function ($scope, $http, $log) {
$scope.inputValue = null;
$scope.abc = function () {
$log.info($scope.inputValue) // you will have your updated value here
$http({
method:'GET',
url: 'https://api.github.com/users/'+$scope.inputValue+'/repos'
})
.then(function (response) {
$scope.repos = response.data;
$log.info(response);
});
});
};
I hope this helps.

Just remember that you have the code on your controller thanks to 2 way binding.
There you will set up an object for models. Ad later you can use them to submit data.
In order for you to understand what I am trying to explain I made an example, I hope it Helps
In your code:
Set the ng-model on the input tag
<input type="text" name="name" ng-model="vm.data.inputValue" />
On your controller make it available as in my example
vm.data ={};
Then use a function to send it using ng-click.
<button type="submit" ng-click="vm.submit()">Test</button>
I am sure there are more ways to do this.
I am not that good, explaining so I made an example, that I hope helps:
https://jsfiddle.net/moplin/r0vda86d/
my example is basically the same but I prefer not to use $scope.

Related

Submit a form with a hidden field that is a var from a calculation

I have a var that is the result of a math calculation which changes based on the users input. I'm trying to create a get-form in html that will send the results to a new page.
my result appears on the page as var newpayment
document.querySelectorAll("#cart span.newpayment")[0].innerHTML = newpayment.toFixed(2);
However the form does not show the result..
<form id="form1" method="get">
<input type="hidden" id="submit_total1" value=""
name="submit_total1">
<button id="select1">Select</button>
</form>
<script>
var form = document.getElementById("form1");
document.getElementById("form1").action = "/complete/file.php";
document.getElementById("select1").addEventListener("click", function ()
{
var submit_total1=newpayment;
form.submit();
});
</script>
Thanks for your help but I'm still not able to get it to work. I've also tried another method by setting the value after the form is rendered (see Below). The var "newpayment" is displayed on the page as the span class but it will not populate as the value in the form. Thank you in advance for any remedies.
`
<script>
function setVal(){
document.getElementById('id').value=newpayment;
}
</script>
<p >$<span class="newpayment">0.00</span></p>`

How do i get input form value without submitting it?

I want the input value from user without submitting any thing then i want to pass it through ajax method as parameter to action method. I tried many method but i could not found a solution.
Here is the code
<input type="text" id="task" name="task" value="" />
#Ajax.ActionLink("ADD TASK", "show_task",new {task=Request["task"]}, new AjaxOptions
{
HttpMethod = "POST",
UpdateTargetId = "print",
InsertionMode = InsertionMode.Replace
})
Here is the controller action method
public ActionResult show_task(string task)
{
var add_task = new tasks_table();
add_task.task = task;
add_task.id = 24;
add_task.f_id=10;
add_task.date_oftask=DateTime.Now;
db.tasks_table.Add(add_task);
db.SaveChanges();
var tasks = db.tasks_table.Include(t => t.user_detail);
return PartialView("render_tasks",tasks);
}
Since you want the current value of the textbox, you may better do it yourself with your own javascript code to make the ajax call, instead of relying on the Ajax.ActionLink helper method.
So change your Ajax.ActionLink call to a normal action link.
<input type="text" id="task" name="task" value="" />
#Html.ActionLink("Add Task","show_task", null, new {id="addTask"})
<div id="print"></div>
Now listen to the click event on this link, read the value of the text box and send that to your server. You may use jQuery $.post method to do so. In the response callback, you can update the print div's content with the response coming back from your server.
$(function(){
$("a#addTask").click(function(e){
e.preventDefault();
$.post($(this).attr("href"), { task:$("#task").val()},function(res){
$("#print").html(res);
});
});
});
You can use JavaScript focusOut function to send the value to controller.
by focusOut method, we get the value in input field instantly when we moved to next field.
$('#task').focusOut(function(){
Your ajax call method....
});
Hopes it helps.

How to create a submit button with ui-sref in angular

I have a multi-step form, each step having a btn-link to move to the next step. I achieve this with angular routes in this way:
<button ui-sref="next.step" class="btn btn-link"></button>
In one of the steps in the middle of the whole form I need to submit the data, so I need the already described button to submit the form as well and only if the form could be submitted then move to the next step.
I tried doing this but it is not working because it redirects to the next step without taking care about the form
<button ui-sref="next.step2" type="submit" class="btn btn-link"></button>
How can I achieve this using angular?
you don't need to use ui-sref for your next button instead use $state service from your controller as shown below
HTML Code
<form ng-submit="onFormSubmission($event)">
<button type="submit" class="btn btn-link"></button>
</form>
Controller
var successCallback = function(response) {
//process response
$state.go("next.step2");
}
$scope.onFormSubmission = function($event) {
var data = getFormData();
$http.post('/someUrl', data, config).then(successCallback, errorCallback);
}
Use ng-submit to submit the form and show some loading message as form is getting saved, use $http to post the data and on-success take user to next route using $state.go.
<script>
angular.module('submitExample', [])
.controller('ExampleController', ['$scope', '$state', function($scope, $state) {
$scope.list = [];
$scope.text = 'hello';
$scope.submit = function() {
$http.get('/aveData', config).then(function(response){
$state.go('next.step2')
}, function(){
alert('error saving data');
});
};
}]);
</script>
<form ng-submit="submit()" ng-controller="ExampleController">
Enter text and hit enter:
<input type="text" ng-model="text" name="text" />
<input type="submit" id="submit" value="Submit" />
</form>

passing data with JSON

What I want to be abl
e to do is passing the form data to a php file and then having the results passed back into app so that the user isnt directly accessing the php file at any point.
This is what I came up with but I cant get it too pass the data. I used chrome with -disable-web-security. It always returns false so I guess the data isnt being passed to the php file. Any help would be great. Also. when it forwards to the results page, it goes blank after a few seconds. thank you.
HTML
<form id="form" method="POST" data-ajax="false" data-transition="pop" data-direction="reverse">
<fieldset>
<label for="name" class="ui-hidden-accessible">Name</label>
<input type="text" name="name" id="name" value="" class="required" placeholder="Name"/>
<label for="email" class="ui-hidden-accessible">E-Mail</label>
<input type="email" name="email" id="email" value="" class="required" placeholder="E-Mail"/>
<label for="memory" class="ui-hidden-accessible">Memory</label>
<textarea name="memory" name="memory" id="memory" class="required" placeholder="Your Memory..."></textarea>
<label for="submit" class="ui-hidden-accessible">Submit</label>
<input type="submit" name="submit" id="submit" value="SEND">
</fieldset>
</form>
JS
$(document).on('pagebeforeshow', '#formPage', function(){
$(document).on('click', '#submit', function() { // catch the form's submit event
if($('#name').val().length > 0 && $('#email').val().length > 0 && $('#memory').val().length > 0){
var that = $(this),
contents = that.serialize();
// Send data to server through ajax call
// action is functionality we want to call and outputJSON is our data
$.ajax({
url: 'http://www....',
dataType: 'json',
type: 'post',
data: contents,
async: true,
beforeSend: function() {
// This callback function will trigger before data is sent
$.mobile.showPageLoadingMsg(true); // This will show ajax spinner
},
complete: function() {
// This callback function will trigger on data sent/received complete
$.mobile.hidePageLoadingMsg(); // This will hide ajax spinner
},
success: function(data) {
console.log(data);
},
error: function (request,error) {
// This callback function will trigger on unsuccessful action
alert('Network error has occurred please try again!');
}
});
} else {
alert('Please fill all nececery fields');
}
return false; // cancel original event to prevent form submitting
});
});
PHP
header('Content-type: text/javascript');
$json = array(
'success' => false,
'result' => 0
);
if(isset($_POST['name'], $_POST['email'], $_POST['memory'])){
$name = $_POST['name'];
$email = $_POST['email'];
$memory = $_POST['memory'];
$json['success'] = true;
$json['result'] = $name;
}
echo json_encode($json);
You are not serializing the form data correctly and the result is that the contents variable is empty.
Change this code:
var that = $(this),
contents = that.serialize();
To this:
//var that = $(this), // <-- delete this line
contents = $('#form').serialize();
YOU ALSO NEED TO FIX ..
You haven't realized it yet but you have created a multiple click binding issue by placing your click handler in the bagebeforeshow event. In order to prevent that from occuring you need to
Change this code:
$(document).on('pagebeforeshow', '#formPage', function(){
To this:
$(document).on('pageinit', '#formPage', function(){
This way your $(document).on('click', '#submit', function() { is only ever bound once regardless of how many times a user leaves and returns to the '#formPage' page
EDITED
No, the data submitted to your backend PHP program via ajax is not json encoded. It is standard HTTP POST data and is accessed via $_POST (or $_REQUEST).
I have your code (with the changes I outlined in my answer above) working on my server. I have placed the two files I setup to test your code in a pastbin for your reference:
The php file:
(edit the path to the included javascript file for your environment)
sandbox_ajax_form.php
The javascript file:
(edit the path that the form data is sent to)
sandbox_ajax_form.js

How to send form field value to a REST service using JSON or AJAX

I have a form field (email signup) on the site, and the email provider wants me to submit it to their REST web service and get a response. I've never used JSON or AJAX before so floundering!
The HTML:
<form>
<input type="hidden" name="gid" value="12345678">
<input type="hidden" name="user.CustomAttribute.NewsletterPopUp" value="Global">
<input type="hidden" name="user.CustomAttribute.NewsletterOptIn" value="True">" value="True">
<input type="text" name="uemail" class="email_input_field" value="please enter your email" size="30" maxlength="64" onFocus="clearText(this)">
<input type="submit" name="signup" value="signup" class="email_submit_button">
</form>
Currently, using Javascript and using window.location to visit the URL (which creates the action instead of posting it) they want it converted to a form post action with XML response. What happens now:
$(".email_submit_button").click(function(){
var uemail = $('.email_input_field').val();
window.location = "http://example.com/automated/action.jsp?action=register&errorPage=/automated/action.jsp&gid=12345678&uemail="+uemail+"&user.CustomAttribute.NewsletterPopUp=Global&user.CustomAttribute.NewsletterOptIn=True";
return false;
}
});
I see you'r using jQuery so you can use the $.post to post to the server like this:
var url = "http://example.com/automated/action.jsp"
var data ={
"gid": form.gid,
"action": register,
"uemail": form.uemail,
"errorPage": "/automated/action.jsp",
"user.CustomAttribute.NewsletterOptIn": user.CustomAttribute.NewsletterOptIn,
"user.CustomAttribute.NewsletterPopUp": user.CustomAttribute.NewsletterPopUp
};
var success_func = function(data){
//do what you want with the returned data
};
$.post(url, data, success_func);
Documentation for $.post.
Or you can use the pure longer Ajax version it's mentioned in the documentation of the $.post.
EDIT:
I forget you can't do xhttpresuext to a different domain you need to use JSONP, here's a link to another SO post explaining everything by detail
Hope this help.
$(".email_submit_button").submit(function(e) {
// stop form from submitting
e.preventDefault();
// Grab all values
var uemail = $('.email_input_field').val();
// make a POST ajax call
$.ajax({
type: "POST",
url: "YOUR URL", // set your URL here
data: {
uemail: uemail // send along this data (can add more data separated by comma)
},
beforeSend: function ( xhr ) {
// maybe tell the user that the request is being processed
$("#status").show().html("<img src='images/preloader.gif' width='32' height='32' alt='processing...'>");
}
}).done(function( response ) {
// do something with the received data/response
//$("#status").html(response);
});
});
Not sure if ".email_submit_button" is the class given to the submit button or the form.. you need to use the id or class given to the form and not the submit button.. hope this helps