How to automatically submit a form in vue-cli? - forms

I want to submit a hidden form when the page loads. Since the form is hidden, I can’t use a submit button. So how can I automatically submit a form when the page loads in vuejs?
<template>
<div v-html="this.paymentResponse"></div>
</template>
<script>
import EventBus from '../../event-bus'
export default {
data() {
return {
paymentResponse: null
}
},
mounted() {
console.log('mounted')
this.$refs.submitBtn.click();
},
beforeCreate() {
EventBus.$on("payment", response => {
this.paymentResponse = response
})
}
}
</script>

You can trigger the submit button on mounted as follows:
new Vue({
el: '#sg1',
mounted(){
this.$refs.submitBtn.click();
},
methods:{
formSumitted(){
console.log("submitted");
}
}
})
<script src="https://unpkg.com/vue/dist/vue.min.js"></script>
<div id="sg1">
<form style="display:none" v-on:submit.prevent="formSumitted">
<button type="submit" ref="submitBtn">Submit</button>
</form>
</div>
UPDATE:
Since the form is passed and rendered using v-html, I don't think you can use ref. Therefore, you can replace it with the id and use vanillla Javascript function to click the button:
document.getElementById("submitBtn").click();

The vue components have a lifeCycle, you can use the methods "created" or "mounted" for submit your form at the begining, when your app start.
new Vue({
data: {
formData: 'some data'
},
created: function () {
// here your code for submit the form
}
})

Related

How to change the state of a vue when you click the check button

I am creating a Todo Application using Vue.js, Express.js, and MongoDB.
I want to change the state of the fields that appear as v-for through the checkbox.
The code I want is to change the state of the text when the checkbox is checked and to show another element with v-if.
Here is the code I wrote: But it does not work.
If I have the wrong code, please help me.
List Component
<template>
<div class="todos">
<div v-for="todo in todos" v-bind:key="todo._id" class="todo">
<div>
<input type="checkbox" v-model="todo.done" v-on:click="completeTodo(todo)">
<del v-if="todo.done">{{todo.title}}</del>
<strong v-else>{{todo.title}}</strong>
</div>
</div>
</div>
</template>
<script>
export default {
data () {
return {
todos: {}
}
},
created () {
this.$http.get('/api/todos')
.then((response) => {
this.todos= response.data
})
},
methods: {
completeTodo (todo) {
todo.done = !todo.done
}
}
}
</script>
You don't need v-on:click="completeTodo(todo)". v-model is already doing the trick for you. Also, the todos in your code should be defined and instantiated as array not an object.
v-model is used for two way data binding. That means, whatever data you pass from your code will be bound to the checkbox value in this case and whenever a change is made from UI and value of checkbox is altered by user, that will be captured in v-model variable. v-model is a combo of :value prop and #change event in case of checkbox, hence, it is able to update data in both the ways.
Please refer this snippet.
var app = new Vue({
el: '#app',
data: {
todos: [
{
id: 1,
title: 'Study',
done: false
},
{
id: 2,
title: 'Work',
done: false
},
{
id: 3,
title: 'Play',
done: false
}
]
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div class="todos">
<div v-for="todo in todos" :key="todo.id">
<div>
<input type="checkbox" v-model="todo.done"/>
<del v-if="todo.done">{{todo.title}}</del>
<strong v-else>{{todo.title}}</strong>
</div>
</div>
</div>
</div>

Can I use Axios with ReactJS in a static page?

I want to create a contact form for my react app, which is a static app (I have no back-end at all, only front-end). I'm trying to do this with a POST request to a certain API, and I found that Axios may be helpful. I want to do something like when the user clicks the Submit button, it calls a function that does all the validations on the form, and then submit the data via a POST action with Axios.
Is this possible, or am I wrong with my approach? Thanks in advance.
Yes, you can. What you'll want to do is listen for the onSubmit event of your form and send the POST request in that listener. You can do the validation inside that method as well.
handleSubmit(e) {
// Stop browser from submitting the form.
e.preventDefault();
// Validate here or directly when setting state.
// ...
// Then send a POST request to your endpoint.
axios
.post('https://your-form.com/endpoint', {
// Your data goes here.
firstName: this.state.firstName,
lastName: this.state.lastName
})
.then(function(response) {
// Done!
console.log(response);
})
}
// In the render method: listen for the submit event.
<form onSubmit={this.handleSubmit} />
Here's a working example:
class Example extends React.Component {
constructor() {
super();
this.state = {
firstName: '',
lastName: ''
};
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChange = this.handleChange.bind(this);
}
handleSubmit(e) {
// Stop browser from submitting the form.
e.preventDefault();
// Validate here or directly when setting state.
// Then send a POST request to your endpoint.
axios
.post('https://reqres.in/api/users', {
firstName: this.state.firstName,
lastName: this.state.lastName
})
.then(function(response) {
console.log(response);
})
.catch(function(error) {
console.log(error);
});
}
handleChange(e) {
this.setState({
[e.target.name]: e.target.value
});
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<input
type="text"
name="firstName"
value={this.state.firstName}
onChange={this.handleChange}
/>
<input
type="text"
name="lastName"
value={this.state.lastName}
onChange={this.handleChange}
/>
<input type="submit" />
</form>
);
}
}
ReactDOM.render(<Example />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.16.2/axios.min.js"></script>
<div id="root"></div>

AngularJS form doesn't send data

Running into a weird problem with Angular forms (running 1.2 rc.2). If I leave the form without a name and prepend each model with a common name, the form sends fine. If I remove the prepended name from each model and give the form that name, the submit action doesn't bind the data and the form tries to send an empty request payload.
This model works fine, except Angular's form validation doesn't instantiate
<form ng-submit="sendForm()">
<input type="text" ng-model="my_form.fullname">
<button type="submit">Submit</button>
<form>
.
app.controller("MyCtrl", function($scope, $http) {
$scope.sendForm = function() {
$http({ method:'POST', url: '...', data: $scope.my_form; })
.then(function(result) { alert("The form was sent"); },
function(reason) { alert("There was a problem"); });
}
}
So now if I add a name attribute to my form and remove it from the models, the form tries to send empty data...
<form name="my_form" ng-submit="sendForm()">
<input type="text" ng-model="fullname">
<button type="submit">Submit</button>
<form>
It seems like my_form no longer exists. In fact, if I don't initialize $scope.my_form = {} on the controller the form won't even send an empty object.
Any advice on how to get the second method to work?
When you give the form a name, that name becomes a variable with meta-data about the fields... dirty flags, errors, etc. It doesn't actually hold the data.
So, when you set ng-model to fullname, the value isn't being set on the my_form object, it is being set directly on your $scope.
Personally, I prefer to do it this way:
<form name="my_form" ng-submit="sendForm(formData)">
<input type="text" ng-model="formData.fullname">
<button type="submit" ng-disabled="my_form.$invalid">Submit</button>
<form>
Then your code looks like this:
app.controller("MyCtrl", function($scope, $http) {
$scope.sendForm = function(formData) {
$http({
method:'POST',
url: '...',
data: formData
})
.then(
function(result) {
alert("The form was sent");
},
function(reason) {
alert("There was a problem");
}
);
}
}

How to get input value in Ember.js app?

What's the best solution of getting input value from Ember.TextField, after the button has been submitted?
Assume I have simple app for sending messages. I specified a view which represents input form where the user enters his message:
App.TextView = Ember.View.extend({
templateName: 'text',
submit: function(event) {
console.log(event);
}
});
Then, there is Handlebars template for this view:
<script type="text/x-handlebars" data-template-name="text">
<h1>Send the message:</h1>
<div class="send_form">
{{view Ember.TextField}}
<button type="submit">Done</button>
</div>
</script>
Basically, I need just one thing. When the user clicks on the button, I need to be notified (in the submit function or anywhere else in my app) and I need to grab the value from the TextField. How can I achieve that?
You could for example bind the value of the text field to a message property in the view.
Perhaps there is other solution, but I think this quite simple: http://jsfiddle.net/Sly7/vfaF3/
<script type="text/x-handlebars">
{{view App.TextView}}
</script>
<script type="text/x-handlebars" data-template-name="text">
<h1>Send the message:</h1>
<div class="send_form">
{{view Ember.TextField value=view.message}}
<button type="submit" {{action "submit" target=view}}>Done</button>
</div>
</script>​
App = Ember.Application.create({});
App.TextView = Ember.View.extend({
templateName: 'text',
message: '',
actions: {
submit: function(event) {
console.log(this.get('message'));
}
}
});

jQuery formular onEnter

I have a form with two input fields, one text and one send button. I want to submit via jQuery .ajax() without reloading the document.
It works as long as the button is clicked, but not when you press return/enter, then it submits without ajax methodology. I tried onEnter() or onSubmit(), but that didn't work either.
These are the code bits:
//HTML
<div id="search_form">
<form method="POST" action="search.php">
<input id="search_text" type="text" name="query"/>
<input id="search_button" type="button" value="send"/>
</form>
</div>
<div id="results"></div>
//Javascript
jQuery(function(){
$("#search_button").click(function(){
var query = "query="+$("input[name=query]").val();
$.ajax({
type: "GET",
url: "request.php",
data:query,
cache:false,
success: function(result){
$('#results').fadeIn();
},
error:function(xhr,err){
alert("readyState: "+xhr.readyState+"\nstatus: "+xhr.status);
alert("responseText: "+xhr.responseText);
}
});
});
});
Instead of a click on the button, rig up to the submit event on the <form>, like this:
$(function() {
$("#myFormId").submit(function() {
$.ajax({
type: "GET",
url: "request.php",
data: $(this).serialize(),
cache: false,
success: function(result){
$('#results').fadeIn();
},
error:function(xhr,err){
alert("readyState: "+xhr.readyState+"\nstatus: "+xhr.status);
alert("responseText: "+xhr.responseText);
}
});
return false;
});
});