AngularJs is not responsive to sending POST requests with hidden <input> values

Within my web application, there are multiple forms on a single page. I am looking to utilize AngularJS to submit a specific form.

Each form requires a unique ID with a hidden value for submission. However, using value="UNIQUE_ID" in a hidden input field does not seem to function correctly in AngularJS.

Here is my HTML code:

<div ng-app>
    <div ng-controller="SearchCtrl">
        <form class="well form-search">
            <input type="text" ng-model="keywords" name="qaq_id" value="UNIQUE_ID">
<pre ng-model="result">

    {{result}}

</pre>
        <form>
    </div>
</div>

Below is the JavaScript script:

function SearchCtrl($scope, $http) {
$scope.url = 'qa/vote_up'; // The url of our search

// The function that will be executed on button click (ng-click="search()")
$scope.search = function() {

// Create the http post request
// the data holds the keywords
// The request is a JSON request.
$http.post($scope.url, { "data" : $scope.keywords}).
success(function(data, status) {
    $scope.status = status;
    $scope.data = data;
    $scope.result = data; // Show result from server in our <pre></pre> element
})
.
error(function(data, status) {
    $scope.data = data || "Request failed";
    $scope.status = status;         
});
};
}

Answer №1

One possible reason why your code may not be functioning correctly is due to the fact that $scope.keywords is a simple variable with a text value, rather than an Object as required. You can refer to http://docs.angularjs.org/api/ng.$http#Usage for more information.

AngularJS interacts with variables within its own scope, known as models. A form essentially provides a way to interact with these models, which can be sent through various methods. You can utilize a hidden field, but in angularJS, it may not even be necessary. The information just needs to be defined within the controller itself - either randomly generated for each instance or received from another source. Alternatively, you can define it within the controller upon loading. So, for the sake of clarity, if you define a formData variable within your formCtrl:

Your HTML:

<div ng-app>
    <div ng-controller="SearchCtrl">
        <form class="well form-search">
            <input type="text" ng-model="formData.title">
            <input type="textarea" ng-model="formData.body">
            <button ng-click="sendData()">Send!</button>
        </form>
<pre ng-model="result">

    {{result}}

</pre>

    </div>
</div>

And your controller:

function SearchCtrl($scope, $http) {
$scope.url = 'qa/vote_up'; // The url of our search

// There is a formData object for each instance of
// SearchCtrl, with an id defined randomly

// Code from http://stackoverflow.com/a/1349426/1794563

function makeid()
{
  var text = "";
  var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

  for( var i=0; i < 5; i++ )
    text += possible.charAt(Math.floor(Math.random() * possible.length));

  return text;
}

$scope.formData = {
  title: "",
  text: ""
};

$scope.formData.id = makeid();

// The function that will be executed on button click (ng-click="sendData()")
$scope.sendData = function() {

  // Create the http post request
  // the data holds the keywords
  // The request is a JSON request.
  $http.post($scope.url, { "data" : $scope.formData}).
  success(function(data, status) {
    $scope.status = status;
    $scope.data = data;
    $scope.result = data; // Show result from server in our <pre></pre> element
  })
  .
  error(function(data, status) {
    $scope.data = data || "Request failed";
    $scope.status = status;         
    });
  };
}

Also: If you wanted to set the unique id on the html itself, you could add an input type="hidden" and set it's ng-model attribute to formData.id, and whichever value you set it to, the model would have it binded. using a hidden input won't work, as the value attribute doesn't update the angularJS Model assigned via ng-model. Use ng-init instead, to set up the value:

HTML with 2 forms:

<div ng-controller="SearchCtrl" ng-init="formData.id='FORM1'">
  <form class="well form-search">
    <input type="text" ng-model="formData.title">
    <input type="textarea" ng-model="formData.body">
    <button ng-click="sendData()">Send!</button>
  </form>
</div>
<div ng-controller="SearchCtrl" ng-init="formData.id='FORM2'">
  <form class="well form-search">
    <input type="text" ng-model="formData.title">
    <input type="textarea" ng-model="formData.body">
    <button ng-click="sendData()">Send!</button>
  </form>
</div>

You can add a hidden field, but it accomplishes nothing - the ng-init attribute does everything you need.

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

Transfer a variable from one PHP page to another and navigate between the two pages

I am just starting to learn PHP and I have a scenario where I need to retrieve the last ID from the database. For each ID, I need to fetch the state and the associated link. If the state is equal to 1, then I need to extract some content from the link (whi ...

Having trouble compiling for IOS using a bare Expo app? You may encounter an error message that reads "Build input file cannot be found."

Encountering Error When Running react-native run-ios on Bare Expo App I am experiencing an issue while trying to run the 'react-native run-ios' command on my Bare expo app. The error message I am receiving is: "Build input file cannot be found: ...

js TouchEvent: When performing a pinch gesture with two fingers and lifting one of them up, how can you determine which finger was lifted?

I am currently working on a challenging touching gesture and have encountered the following issue: let cachedStartTouches: TouchList; let cachedMoveTouches: TouchList; function onStart(ev: TouchEvent) { // length equals 2 when two fingers pinch start ...

Guide on how to dynamically add AJAX JSON array response to an HTML table

Hey! I need some advice on how to dynamically append a JSON Array response to an HTML table after submitting a form using AJAX. Here's the scenario: This is my form : <form id="myForm" method="POST"> <input type=" ...

What are some tips for increasing your points on the journey using Here Maps?

While plotting a route, I noticed that the segments on highways are quite far apart. Is there a way to get a more detailed routing with finer points along the journey? $.ajax({ url: 'https://route.cit.api.here.com/routing/7.2/calculateroute ...

Implementing a FadeOut effect for the clicked link

When clicking on each link, I want the same link to fadeOut() after clicking on the ok button in the myalert() function. If clicked on cancel, it should not fadeOut(). How can I achieve this using the myalert() function? For example: http://jsfiddle.net/M ...

Preserving the background image on an html canvas along with the drawing on the canvas

Can users save both their drawings and the background image after completing them? var canvas = document.getElementById("canvas"); // This element is from the HTML var context = canvas.getContext("2d"); // Retrieve the canvas context canvas.style.ba ...

Retrieving JSON information from the server

I have been working with the knockout.js framework and adapted a basic contacts form example to suit my needs. I am able to successfully store values in my database, but I am encountering difficulties when trying to load values from the server. Despite h ...

What is the reason behind including a data string filled with a series of numbers accompanied by dashes in this ajax request?

I stumbled upon a website filled with engaging JavaScript games and was intrigued by how it saves high scores. The code snippet in question caught my attention: (new Request({ url: window.location.toString().split("#")[0], data: { ...

Check the schedule for any upcoming events

I am currently designing a website for a friend and I have a question regarding the functionality of the FullCalendar jQuery plugin. Is there a way to determine if there is an event scheduled for today using FullCalendar? If so, I would like to display t ...

What is the best method for converting an Object with 4 properties to an Object with only 3 properties?

I have a pair of objects: The first one is a role object with the following properties: Role { roleId: string; name: string; description: string; isModerator: string; } role = { roleId:"8e8be141-130d-4e5c-82d2-0a642d4b73e1", ...

Utilizing React to connect with Metamask and share the signer across various contracts

I'm currently working on a solution for sharing signers across multiple JavaScript files. In my walletConnect.js file, I successfully connect to Metamask and retrieve an ERC20 token contract. async function connect(){ try{ const accounts = awai ...

JavaScript Animation of Text

I have a challenge where I want to animate text's opacity in JavaScript after the user presses enter. However, I am struggling to achieve this with my current code. I can provide all of my code for you to review and help me understand why the animatio ...

Determine the difference between the final value and the second-to-last value within an array

Is there a way to retrieve documents from MongoDB by performing a calculation on two items stored in an array within each document? Specifically, I am interested in fetching all documents where the last item in an array is lower than the second-to-last it ...

jQuery failing to transmit JSON in AJAX POST call

I'm a bit perplexed at the moment, as I'm attempting to send data to my Node.js server using the code snippet below: $.ajax({type:'POST', url:'/map', data:'type=line&geometry='+str, succe ...

Can the console logs be disabled in "Fast Refresh" in NextJS?

When I'm running multiple tests, my browser's console gets cluttered with messages every time a file is saved. Is there a way to disable this feature? For example: [Fast Refresh] completed in 93ms hot-dev-client.js?1600:159 [Fast Refresh] rebuil ...

Troubleshooting the issue with default useAsDefault routing in Angular 2

I have implemented Angular 2 for routing and Node for local hosting. However, I encountered an issue where using 'useAsDefault:true' for my route caused the nav bar links to stop functioning properly. The URL would redirect to http://localhost/ ...

Launching an IONIC application within an iframe of a different framework

Is it feasible to display an Ionic app within an IFrame HTML element hosted on a server-based app? If so, how can I incorporate the necessary IONIC/Angular libraries into my framework? For instance, is it possible to render an Ionic app within the view of ...

Creating JavaScript functions that accept three inputs and perform an operation on them

Apologies in advance if there are any silly mistakes as I am new to Javascript. I want to add "salary", "pension", and "other" together, then display the result in an input field when a button is clicked. Not sure if I have used the correct tags in my cod ...

Using TypeScript controllers to inject $scope

Currently, I am in the process of creating my initial typescript controller and encountering a slight challenge in comprehending how to utilize $scope effectively in order to reference elements within various code blocks. Below is the relevant snippet of c ...