Using Angular JS to submit forms on a regular basis

My HTML form is set up within an Angular controller with inputs, action, and other elements already defined. The only issue I'm facing is that the form does not have a traditional submit button. Instead, there is a separate button on the page outside of the form that needs to initiate the submission process when clicked. Essentially, I want the external button to function as a standard submit button.

For instance (using a simplified version of my current setup),

<div ng-controller='sendFormController">
    <form name='my_form' action='/path/to/form_handler.php' method="POST">
        <input type="text" name="form_data" />
    </form>

    <button ng-click='submitForm()">Send Data</button>
</div>

I've searched for a solution to this dilemma, but the options I found seem a bit like hacks in my opinion, including:

  • Using a hidden submit button and triggering it with the external button.
  • Writing code that performs $http.post(), etc. when the external button is clicked. I prefer not to duplicate actions and parameters in the function.

I believe there must be a straightforward way in Angular to simply execute the form submission, yet I couldn't find it in the documentation. Can someone guide me towards the solution I'm missing?

Answer №1

Inside the sendFormController,

$scope.submitForm = function() {
    document.getElementById('my_form').submit(); //trigger form submission on button click
}

Additionally, there is a form defined as follows:

<form name='my_form' id='my_form' action='/path/to/form_handler.php' method="POST">

Answer №2

In my opinion, approaching this task in an Angular manner would yield better results:

app.controller('sendFormController', function($scope) {
       $scope.model = { 
          form_data: ''
       };

       $scope.submitForm = function () {
          $http({
              url: '/path/to/form_handler.php',
              method: "POST",
              data: $.param($scope.model),
              headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
              }
          });
        };
});

HTML:

<div ng-controller='sendFormController">    
    <input type="text" ng-model="model.form_data" />  

    <button ng-click='submitForm()">Send Data</button>
</div>

Answer №3

For best results, follow these guidelines:

     <form onsubmit='this.submit()' name='my_form' action='/path/to/form_handler.php' method="POST">

You can also consider an alternative approach like this:

     <form #form (submit)='form.submit()' name='my_form' action='/path/to/form_handler.php' method="POST">

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

pm2 initiates two identical processes using distinct versions

I am currently using pm2 version 4.2.3 Upon executing the command: pm2 start node launchers/engine_launcher.js --name "engine", it initiates the following processes: id │ name │ namespace │ version │ mode │ pid - ...

Unexpected event triggering

I have come across a snippet of code that allows me to retrieve URL query strings var QueryURL = function () { var query_url = {}; var query = window.location.search.substring(1); var vars = query.split("&"); for (var i=0;i< ...

What is the best way to convert the javascript code into clojurescript?

Looking to utilize capacitor/app in order to determine the state (background or active) of my iOS app. My project is built on Clojurescript, so I need to convert the following javascript code into a clojurescript equivalent. Javascript import { App } fro ...

``There seems to be an issue with the Express app when trying to access it

I have set up an express app that I want other devices on the same WIFI network to access without requiring internet connectivity. The main computer hosting the app is assigned with a fixed IP address: 192.168.1.60 In my server.js file, I have included t ...

Is it necessary to specify the JavaScript version for Firefox? (UPDATE: How can I enable `let` in FF version 44 and below)

Our recent deployment of JavaScript includes the use of the let statement. This feature is not supported in Firefox browsers prior to version 44, unless JavaScript1.7 or JavaScript1.8 is explicitly declared. I am concerned about the potential risks of usi ...

Browsing through a collection of JSON objects with a user interface

I need a way to filter and display a list of Dogs based on a search query. I initially stored the data in an array within the state, but with an increasing number of entries, I've decided to switch to JSON format for better management. However, I&apo ...

Obtaining a string from a regular expression does not function as anticipated

Currently, I am in the midst of a project that requires me to identify specific HTML tags and replace them with others. To accomplish this task, I am utilizing JavaScript, and the code snippet looks like this: // html to update html = '<div cla ...

retrieveValue() for SelectionDropdown

I have a simple task - I just need to retrieve the name of the Company and store it in the database. Initially, I was able to achieve this using plain text and the code snippet below: sport: this.refs.company.getValue(), which worked perfectly. However, ...

Can you provide guidance on displaying flash messages in my template using Express.js?

app.get('/',function(req,res){ res.render('home'); // Ensure the template has access to the flash message }); app.get('/go',function(req,res){ req.flash("info", "You have gone to GO and got redirected back home!"); ...

Deciding whether an array forms a chain of factors

I am curious about the reasons why this code is failing some of the tests provided. It deliberately avoids using any ES6 code. Here is the given prompt: *A factor chain can be defined as an array where each preceding element serves as a factor for the su ...

Use AJAX to send a form submission along with an anchor tag

I've been facing a challenge trying to make this work, but unfortunately, I haven't had any success. Typically, all my forms include a submit input, and I handle AJAX submission in the following manner: <script> $("input#submit").click(fun ...

Utilizing express.js to access an HTML document

var express = require("express"); var fs = require('fs'); var sys = require('sys'); var app = express(); app.use(express.logger()); app.get('/', function(req, res){ fs.readFile('/views/index.html'); }); ap ...

Is there a way to display a message box on initial page load only, using JavaScript or jQuery?

I am looking to display a message box only once when a webpage first loads, and then not show it again if the user refreshes the page. The message should appear regardless of whether the user is logged in or not. Is using cookies the only option for achie ...

Stop unauthorized access to php files when submitting a contact form

I have implemented a contact form on my HTML page that sends an email via a PHP script upon submission. However, when the form is submitted, the PHP script opens in a new page instead of staying on the current page where the form resides. I have tried usin ...

Can the value of the currently selected option in a select box be obtained without needing to submit the form?

I'm currently working on a project and facing a roadblock with the following task: My goal is to extract the selected value from a dropdown menu and utilize it in my PHP script. The challenge here lies in capturing the chosen option without requirin ...

Issue: React-Firebase-Hooks failing to retrieve dataHaving trouble with React-F

I've been utilizing the React-Firebase-Hooks package in my project, but I'm encountering some difficulties with its usage. In the code snippet below, the user.data().username is displayed correctly. However, when I try to use it within useState, ...

Loop through images in a file directory

Just starting out with Angular and I'm looking to create an ng-repeat of images that are stored in a folder. Each image has its own unique name, so I'm not sure how to approach setting the ngSrc for all of them. Appreciate any help or advice on ...

What is the best way to extract specific values from one JSON object and transfer them to another using lodash?

//I have a pair of objects var obj1={ "name":"mayur", "age":23 } var obj2={ "name":"keyur", "age":29, "limit":54, "surname":"godhani" } //I am familiar with one approach var j1 = {name: 'Varun', age: 24}; var j2 = {code: &ap ...

Retrieve a specific key value from a dictionary within a Flask function by employing JavaScript

I'm currently working on a feature where a user can input something in a search field, and upon submitting, the script should send a request to a Flask function using JavaScript. The response data should then be loaded accordingly. However, I've ...

Retrieve the native interface from the Puppeteer browser/page context

Can a native interface be obtained from the Browser or Page instance to verify if an object is an instanceof this interface? For example, in a testing scenario with jest (where CanvasRenderingContext2D is not available due to being a Node context rather t ...