AngularJS submit json - json

Here is a form with angularjs.
<!DOCTYPE html>
<html lang="en">
<head>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
</head>
<body>
<div ng-app="" ng-controller="formController">
<form novalidate>
First Name:<br>
<input type="text" ng-model="user.firstName"><br>
Last Name:<br>
<input type="text" ng-model="user.lastName">
<br><br>
<button ng-click="reset()">RESET</button>
</form>
<p>form = {{user }}</p>
</div>
<script>
function formController ($scope) {
$scope.master = {firstName:"John", lastName:"Doe"};
$scope.reset = function() {
$scope.user = angular.copy($scope.master);
};
$scope.reset();
}
</script>
</body>
I am not familiar with AngularJS, I found the expression {{user}} display as a json like format data which was binded to the textbox. I want to know is there any way to post {{user}} as json directly to the server side. I know I can easily post the form. But my purpose is the page may have a lot of textbox. I want to store it using json, just like {{user}} and submit as a combined one.
And I also want to know how to remove one value in the expression. i.e. the following code has two attribute firstName and lastName. Is there a way like remove(), after call it. I can remove one attribute in the correspond json data.
Thanks a lot

you can post your modal (user in this case) directly as JSON using $http .
In case all you text fields are saved in the user modal then u can remove one of the attributes by calling the below function before submitting the form
$scope.remove = function (user) {
delete $scope.user.firstName;//the output here is user with only lastname
}

Related

using a variable to populate the "mailto:" value using "form action"

Newbie question no.2, sorry in advance!
I have somehow managed to create a form with various selection boxes, one of which is the email that the form should send the email to (using mailto:). I've managed to get the value of the email field stored as a variable ("emailtouse"), and now I am trying to use the variable in the "mailto:" code but it's not having it, I either get blank or the variable name itself when I attempt the process.
Thanks
Ian
***variable setting within script in header***
var emailtouse = "mailto:"+emailgoto[value]
***form action***
<form action='+emailtouse+'?
cc=u16#myleague.co.uk&subject=Match%20Postponement/%20Cancellation%20Request" method="post"
enctype="text/plain">
Even if your variable is updated, the "action" is not updated after the variable changes, so it contains the original value, calculated upon rendering the page.
Please see the following CodePen example on how to update the form action before submit:
<form
id="form1"
onsubmit="return updateAction(this)"
action="javascript:;"
method="post">
<button type="submit">Do it!</button>
</form>
... and the JS to update the form action, and to test that it really worked:
let emailtouse = "testemail#somewhere.com";
function updateAction(element) {
element.action =
emailtouse +
"&cc=u16#myleague.co.uk&subject=Match%20Postponement/%20Cancellation%20Request";
checkIfItReallyWorks();
return false; // change to true to submit!!!
}
function checkIfItReallyWorks() {
let form = document.getElementById("form1");
alert(form.action);
}
The above code on CodePen: https://codepen.io/cjkpl/pen/vYxPJQd

Validate URL with AngularJS and HTML 5

Good morning all:
Looks like a very common question, but after googling for hours I am not able to figure this out: how to validate an URL including www without http.
These is what I did:
Used the input type url: it does not accept www.google.com;
Changed the input type to text and used ng-pattern: I still get the www.google.com invalid;
Changed different regex but still not working.
So when I click on the submit button, I show an alert if the form is invalid (true invalid, false valid). Here is my Plunker
Thanks for the help
Instead of binding the regex to scope, you could directly add the regex to ng-pattern attribute. Like this:
<input type="text" ng-pattern="/^(http[s]?:\/\/){0,1}(www\.){0,1}[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}[\.]{0,1}/" ng-model="website">
I have updated the plunkr. Please take a look at this. Plukr
The thing here is, if you want to bind ng-pattern from controller, your regex shouldn't contain the starting and ending /s. Like this:
$scope.regex = "^(http[s]?:\\/\\/){0,1}(www\\.){0,1}[a-zA-Z0-9\\.\\-]+\\.[a-zA-Z]{2,5}[\\.]{0,1}$"
But, if you directly specify pattern like ng-pattern="/^(http|https|...)$/", you need the extra /s as well.
working plunker
Try using the ng2-validation library. It can be used to perform most validations you should ever need. Angular2 custom validation, inspired by jQuery validation.
I think we can also use AngularJs builtin URL validator.
<script>
angular.module('urlExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.url = {
text: 'http://google.com'
};
}]);
</script>
<form name="myForm" ng-controller="ExampleController">
<label>URL:
<input type="url" name="input" ng-model="url.text" required>
<label>
<div role="alert">
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.url">
Not valid url!</span>
</div>
<tt>text = {{url.text}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
<tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
</form>
`
if (this.resource.url.match("^(https:\/\/|http:\/\/)")) {
if (this.resource.url.match("^(https:\/\/www\.|http:\/\/www\.)?([da-z.-]+)\\.([a-z.]{2,6})")) {
}
else
{
errorMessages.push("url is invalid");
}
}
else {
errorMessages.push("url is invalid");
}
`

Getting value of form textbox via Id on click of button

I would like to click a button and have it go to a link that concatenates mypage.html with the value entered in the search box, but it doesn't seem to recognize it as a variable. What can I do to get the value of the text box?
<html>
<form role="search" action="mypage.html/'#searchterm'">
<input type="text" placeholder="Search" id="searchterm">
<button type="submit">Search</button>
</form>
</html>
Change the form element to this:
<form role="search" id="myForm" action="mypage.html">
The javascript (this is jQuery) would be something like this:
$( "#myForm" ).submit(function( event ) {
// Get the search term
var searchTerm = $('#searchterm').val();
// Append the search term to the root URL
var url = "mypage.html/" + searchTerm;
// Redirect the page to the new URL
window.location.href = url;
// Prevents the default behavior of the form
event.preventDefault();
});
It depends on how you would like to achieve this, you can send it directly using PHP, or you can send it using javascript and AJAX to a PHP page. As you can see in this small tutorial you can send the value of the entered input. AJAX will avoid the page from being refreshed while you search the data, so it will look better. It all depends on what you would like to achieve.
Please take into account that the value of the input cannot be sent on the ¨action¨ property of the form.
Thanks to everyone who submitted answers, I actually figured this one out.
<html>
<input type="text" id="myInput">
<button onclick="go()">Click me</button>
<script>
function go(value)
{
window.open("mypage.html/" + document.getElementById('myInput').value)
}
</script>
</html>

show JSON in new window

I have a problem with json. I'd like to display the result of my form in the new browser window in JSON. (When user fills all fields in the form, button becomes enabled and shows JSON in specified format (I did it)). I translated it in JSON but dunno how to output it...I'm thinking of create new html page and do window.open on button on 1st page, but then it doesn't read data from 1st page which user entered. Or should I save it somehow in JSON file and then read it from other page?
For example:
<form name="form" ng-controller="MyCtrl">
<label> <b> * Date: </b> </label> <input type="datetime-local" ng-model="date" name="date" onkeyup="changeButtonStatus()" onchange="changeButtonStatus()" required> </input>
<button type="submit" id="btn" class="btn" disabled="disabled">Submit</button>
</form>
I have some form with date field and button:
I can easily get JSON of date field by {{date | json}} on the same page, but I just want to output it in new browser window. How can I do this? Please help me with some tips. Thanks.
If it's not too big you can send the information to the new window as a data URL.
The frame will be reused once it is open.
This might be a start, showing how to plug in the JSON data and break it up over multiple lines for display.
window.open('data:application/json,'
+JSON.stringify(location).replace(/([[{,])/g, "$1%0a"),
'jsonFrame',
'resizeable,top=100, left=100, height=200, width=300,status=1')
See MDN for all the details.
You should be able to get at the window.opener from the new window and parse values out of it. The following plunker shows storing data from the current scope in an accessible area when the controller's submit is clicked. From the new window it then parses the content from the opener into the window's scope for further processing.
http://plnkr.co/edit/OkKX5zxYVSoZ7w81WV8J?p=preview
You'll notice here too how to get an angular friendly way of calling the submission and the disabling of the button until ready.
Hope this helps.
How about to save your input data into a cookie on one page and then get it via JavaScript when you will open a new window?
I could prepare the code in jsFiddle, but seems like it does not import external resources at this moment. So I'll post it here:
page 1:
...
<form name="form" ng-controller="MyCtrl">
<label> <b> * Date: </b> </label> <input id="date" type="datetime-local" ng-model="date" name="date" onkeyup="changeButtonStatus()" onchange="changeButtonStatus()" required> </input>
<button id="btn" class="btn" >Submit</button>
</form>
<script type="text/javascript" src="https://raw.github.com/carhartl/jquery-cookie/master/jquery.cookie.js"></script>
<script type="text/javascript">
$('#btn').click( function() {
var cookie_value = $('#inut_test').val();
/*cookie_value should be your json string*/
$.cookie("json_cookie", cookie_value, { path: '/' });
window.open("http://localhost/page2");
return false;
});
</script>
...
page 2:
...
<a id="see-cookie" href="#">
click me!!!
</a>
<script type="text/javascript" src="https://raw.github.com/carhartl/jquery-cookie/master/jquery.cookie.js"></script>
<script type="text/javascript">
$('#see-cookie').live('click', function() {
alert($.cookie('json_cookie'));
return false;
});
</script>
...
Do not forget about { path: '/' } cookie property to set it for all site and about including jQuery cookie library into your page.

return variable from file executed from form action

Let's say that I have a file (file1.php) with a simple form with the action attribute:
echo'
<form action="foo.php" method="post">
Name: <input type="text" name="username" /><br />
Email: <input type="text" name="email" /><br />
<input type="submit" name="submit" value="Submit me!" />
</form>';
$another_var = $user_id+5;
Let's say the foo.php looks something like this:
$sql ... SELECT user_id, username... WHERE username = $_POST['username']; //or so
echo 'We got the user ID. it is in a variable!';
$user_id = $row['user_id'];
As you see, I need the variable $user_id made in foo.php actually to be used in the main file file1.php.
Is there any way to do this? I though that return $user_id would work but I was wrong :-/
Some notes to have into account:
in file1.php there are two forms: one to upload a file (example above) and another to save all the data into a database (that's the reason I need the variable name).
the example is just that, an example. I'm not really adding 5 to the variable requested, but I don't want to copy and paste 100 lines of code to overwhelm everybody.
the variable is also refreshed with javascript, So I see it there but I don't really know how to assign a javascript variable to a php variable (if possible).
THANKS!!!
Here's how I would do it.
The html:
<form id="form1" action="foo.php" method="post">
<!-- form elements -->
</form>
<form id="form2" action="bar.php" method = "post">
<input type="hidden" name="filename" value="" />
<!-- other form elements -->
</form>
The javascript
$('#form1').submit(function(){
var formdata = ''; //add the form data here
$.ajax({
url: "foo.php",
type: "POST",
data: formdata,
success : function(filename){
//php script returns filename
//we apply this filename as the value for the hidden field in form2
$('#form2 #filename').val(filename);
}
});
});
$('#form2').submit(function(){
//another ajax request to submit the second form
//when you are preparing the data, make sure you include the value of the field 'filename' as well
//the field 'filename' will have the actual filename returned by foo.php by this point
});
The PHP
foo.php
//receive file in foo.php
$filename = uniqid(); //i generally use uniqid() to generate unique filenames
//do whatever with you file
//move it to a directory, store file info in a DB etc.
//return the filename to the AJAX request
echo $filename;
bar.php
//this script is called when the second form is submitted.
//here you can access the filename generated by the first form
$filename = $_POST['filename'];
//do your stuff here
use the Jquery Form plugin to upload the file via Ajax
$(document).ready(function(){
$('yourform').submit(function(){ //the user has clicked on submit
//do your error checking and form validation here
if (!errors)
{
$('yourform').ajaxSubmit(function(data){ //submit the form using the form plugin
alert(data); //here data will be the filename returned by the first PHP script
});
}
});
});
As you'll notice, you haven't specified either the POST data or the URL of the PHP script. ajaxSubmit picks up the POST data from the form automatically and submits it to the URL specified in the action of the form
I can think of two ways off the top of my head.
1.
session_start();
$_SESSION['user'] = $row['user_id']
Then, you can refer to $_SESSION['user'] whenever until the session is destroyed.
Another way would be to include the file that defines $user_id (foo.php) into file1.php with:
include("file1.php");
It is probably easier to achieve this with sessions.
Actually, ONE MORE THING you could use is to pass the variable value through the URL if it isn't something that needs to be kept private.
echo "<a href='file1.php?userid=" .$userid. "' > LINK </a>";
or
<?php
echo "
<html>
<head>
<meta HTTP-EQUIV='REFRESH' content='0; url=file1.php?userid=" .$userid. "'>
</head>
</html>";
Then, on file1.php you would access that variable like this.
$userid = $_GET['userid'];
and you can use $userid as you please.