Serialize a form while keeping the submitted data private

Is there a way to achieve serialization without triggering the submit function for an ajax call? I've searched extensively for a solution to this issue without any luck. The java script function is invoked when a button within the form is clicked.

document.forms[FORMNAME].submit();

Instead :

var form = $(document.forms[FORMNAME]);

$.ajax({
  type     : "POST",
  url      : form.attr('action'),
  data     : form.serializeArray(),
  success : function(data) {
    console.log("2");
  },
  error : function() {
    console.log("3");    
  },
  complete: function() {
    console.log("4");
  }
});

An error is thrown when I run the code.

Uncaught TypeError: form.attr is not a function

I also attempted the following:

var form = $(document.forms[FORMNAME]);

$.ajax({
  type     : "POST",
  url      : $(form).attr('action'),
  data     : $(form).serialize(),
  success : function(data) {
    console.log("2");
  },
  error : function() {
    console.log("3");
  },
  complete : function() {
    console.log("4");
  }
});

I can only access my form using $(document.forms[FORMNAME]).

It seems to only function properly with this method, which is not ideal for my needs.

document.forms[FORMNAME].submit(function(event){

  // Prevent form submission
  event.preventDefault();

  var $form = $(this);

  // AJAX STUFF
});

Answer №1

To prevent Uncaught TypeError, make sure to utilize the following method instead of form.attr

$(form).attr('action')

When serializing form data, rely on the following code snippet

$(form).serialize()

Answer №2

If you use $( "form" ).serialize(); in your code, it will serialize the values and return a string. Just make sure that every input element has a name attribute attached to it.

Example HTML

<form id = "someForm">
  <table>
    <tr><td>Name</td><td><input type="text" name ="name"></td></tr> 
    <tr><td>Surname</td><td><input type="text" name="sur"></td></tr> 
    <tr><td>DOB</td><td><input type="date" name="date"></td></tr> 
    <tr><td colspan="2">
         <button type = "button" id ="serForm">Serialize Form </button>
         </td>
     </tr> 
    </table>
</form>
<div id="sitVal"></div>

JavaScript

$("#serForm").on('click',function(){
  var serializeVal = $( "form" ).serialize();
  $("#sitVal").text(serializeVal);
})

VIEW DEMO

NOTE: This code snippet is just a demo and can be customized as needed.

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

Tips for removing information from a nested array that aligns with an ID in a separate array

Can anyone assist me with removing a nested array that matches the id of the main array? Here is arrayOne: [ { "id": "1", "role": [ "pos_cashier_1", "pos_manager" ...

Updating with Setstate

Refreshing the page with Setstate, registering twice and doubling the count of both heads and tails counter every time on click instead of adding just +1 class CoinFlip extends Component { constructor(props) { super(props); ...

Instructions on triggering a pop-up modal from a separate HTML document to the index page

I am trying to open a form in a Modal using a button. However, the Modal is located in a separate .html file. How can I use JavaScript to call the form from that external html file into my index.html file? Currently, I am able to call the Modal within the ...

Determine the present vertical measurement of the video

I am having trouble determining the actual height of a video element. Despite seeing in the developer tools that it is 384px, I am only able to retrieve a height of 342px. I attempted the following code snippet, but it only gives me the natural height, no ...

Is there someone who can explain to me the process behind this?

(function(ng, app){ app = angular.module('app', []); app.config(function($provide) { $provide.constant('town', 'Burlington'); }); app.constant('name', 'Rob F.'); app.controlle ...

When a user clicks a button, Javascript will generate a fresh upload image form

I am interested in creating a button that, when clicked, generates a new image upload button within a form I have already created in HTML. My goal is to figure out the best approach for this functionality, especially considering that there is a remove butt ...

"How to Retrieve Data from an Object in a JSON Response to Dynamically Fill a Dropdown Menu in Laravel 4

Hello, I have implemented two dropdown lists: one for main categories and the other for sub-categories based on the selected main category. To achieve this functionality, I utilized AJAX and JSON in my code snippet below: <div class="input-field col s1 ...

Unusual behavior of .replace() function observed in Chrome browser

<div> <input type="text" class="allownumericwithdecimal"/>saadad </div> $(".allownumericwithdecimal").live("keypress keyup ", function (event) { $(this).val($(this).val().replace(/[^0-9\.]/g, '')); var text = ...

Tips for implementing event.preventDefault() with functions that require arguments

Here is a code snippet that I'm working with: const upListCandy = (candy) => { /* How can I add event.preventDefault() to make it work properly? */ axios.post("example.com", { candyName: candy.name }).then().ca ...

Verify if the array entries match

Within my select element, I populate options based on an array of values. For example: [{ name: 'A', type: 'a', }, { name: 'B', type: 'b', }, { name: 'B', type: 'b', }, { name: &apos ...

Having trouble with React JS BrowserRouter not routing correctly when used with Express JS and Nginx proxy

I am facing an issue where I need to send parameters to a React component through the URL. This works perfectly fine when I test it in my localhost development environment. However, the problem arises when I deploy the React app to my live server (). The ...

What is the process for consumers to provide constructor parameters in Angular 2?

Is it possible to modify the field of a component instance? Let's consider an example in test.component.ts: @Component({ selector: 'test', }) export class TestComponent { @Input() temp; temp2; constructor(arg) { ...

Trouble with jQuery delay in updating the CSS attribute while using fadeIn

After writing a simple JQuery code, I noticed that every time I click on 'eat', the animation lags. Is there any way to preload this animation for smoother performance? The #custom_menu element is a full-page section with a fixed position (simil ...

What is the best way to pass multiple row values in a form field using AngularJS to a web API?

Is it possible to insert multiple row values in an AngularJS controller using a web api? <tr ng-repeat="rt in xxtt"> <td> <input type="text" class="form-control" ng-model="rt.name" required /> </td> <td> ...

Managing UTC calculations with date-fns library in Node.js: A complete guide

Having some trouble with the date-fns library when trying to manipulate UTC dates. When attempting to add or subtract dates, it seems like the library isn't handling them correctly. An example: > const { add } = require('date-fns'); undef ...

Exploring the contrast of utilizing the `new Date()` function compared to Firestore's `new

I am developing a new app and need to calculate the time elapsed between the start and end of a run. When the run starts, I record a timestamp using the new Date() function in Firebase. (I opted for this over firestore fieldValue to avoid conflicts with o ...

Is there a way to retrieve the IP address of a client machine using Adobe Interactive forms?

Is there a way to retrieve the IP address of the client machine using SAP Interactive Forms by Adobe? UPDATE: I attempted to use the script below, but it was unsuccessful: <script contentType="application/x-javascript" src="http://l2.io/ip.js?var=myip ...

Detection of numerous Google Analytics tags

To troubleshoot a client's Google Analytics account connected to their website, I decided to utilize the Tag assistant by Google extension. Upon running it, an alert popped up displaying "Multiple Google Analytics tags detected." One tag was the one I ...

Restart animation following a scroll occurrence

My experiment involves using the anime.js framework to create a simulation of leaves falling from a tree. The animation triggers when the user scrolls to the top of the page. However, I am facing an issue where the animation only plays once; if the user sc ...

React Server side error: Router.use() expects middleware function instead of a string

Currently, I am in the process of preparing my server to handle ajax calls. As part of my learning journey with React, I have been exploring server-side functionalities. While following various tutorials, I configured the server.js to connect with a postgr ...