Reputation: 11
My understanding of meteor is ajax is not needed for form submission, however I am wondering how I take care of Template.form.event
submit form event and do a POST rest submit in the javascript so the page does not continue on to the action destination it just sends the data and stays on the page. How do I do POST in javascript without ajax. I assume there is a obvious answer, just can't seem to think of it. Do I need to install a rest package.
I dont want the form action to be ran, but passed into javascript and sent via POST, without refreshing the page in METEOR.
Here is the form
<form accept-charset="UTF-8" action="https://formkeep.com/f/randomnumbers" method="POST" id="contact-form">
<input type="hidden" name="utf8" value="✓">
<input type="text" placeholder="Name">
<input type="phone" placeholder="Phone Number">
<input type="email" placeholder="Your Email">
</form>
Upvotes: 1
Views: 828
Reputation: 22696
You're right in assuming that you don't need to use AJAX to perform a form request submission, you should use Meteor DDP protocol instead, by using a Meteor method.
First, define your Meteor method to perform the action required, here is an example :
Meteor.methods({
addContact: function(contact){
check(contact, {
name: String,
phoneNumber: String,
email: String
});
//
return Contacts.insert(contact);
}
});
This method simply adds a contact to a collection after checking the argument has the correct format.
Next you need to call this method in your form submission event handler like this :
Template.myForm.events({
"submit": function(event, template){
// prevent default form submission handler : which is
// performing an HTTP POST request that will reload the page
event.preventDefault();
// construct the contact object that will be passed to the method
var contact = {
// assuming each input fields have ids attribute
name: template.$("#name").val(),
phoneNumber: template.$("#phoneNumber").val(),
email: template.$("#email").val(),
};
// perform the server-side asynchronous call
Meteor.call("addContact",contact);
}
});
Upvotes: 1