Submitting a form with AJAX and additional fields can be accomplished by including the extra fields in

Imagine a scenario where I am working with a basic form like the one below

<%= form_for(@category) do |f| %>
  <% if @category.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@category.errors.count, "error") %> prevented this category from being saved:</h2>

      <ul>
      <% @category.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :name %><br>
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.label :enabled %><br>
    <%= f.check_box :enabled %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

I have been attempting to submit this form using an ajax request. The ID of my form is new_category. Here's what I tried:

<script type="text/javascript">
  $("#new_category").click(function () {  
    $.ajax({
      type: "POST",
      contentType: "application/json; charset=utf-8",
      url: '/categories',
      dataType: "json",
      success: function (result) {
        return false
      },
      error: function () {
        window.alert("Something went wrong! Please try again");
      }
    });
  });
</script>

Unfortunately, this code is not successfully submitting my form. It seems like I might be overlooking something important. Additionally, before submission, I want to replace the content of the name field with a fixed string "This is a sample string". Also, I need to include some specific data such as "user_id" => current_user.id" and "

user_name" => current_user.name
". However, these two fields are not present in the category table. Do I need to whitelist them in the controller? If so, how can I achieve that?

Answer №1

At first glance, I couldn't locate the id #new_category on your form. Does Rails automatically add it, like a framework specific feature? Secondly, and most importantly, you are forgetting to include the data parameter in your Ajax settings.

As recommended by others, you should send the data as part of your Ajax request. You can do this by adding:

To the Ajax request. Try:

$("#new_category").serialize()

So your updated request should look like this:

<script type="text/javascript>  $("#new_category").click(function () {  
$.ajax({
  type: "POST",
  contentType: "application/json; charset=utf-8",
  url: '/categories',
  dataType: "json",
  data: $("#new_category").serialize() 
  success: function (result) {
    return false
  },
  error: function () {
    window.alert("Something went wrong! Please try again");
  }
});

});

Answer №2

Don't forget to include a class or id attribute on both the form and submit button:

<%= form_for(@category), id: "category_form" do |f| %>
    <%= f.submit "Submit", class: "add_category" %>
<% end %>

If you are using devise and have access to current_user, you can pass extra parameters along with your form data like this:

<script type="text/javascript>
    $(document).on('click', '.add_category', function(event) {
        event.preventDefault();
        var user_id = "<%= current_user.id %>"
        var username = "<%= current_user.username %>"
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: '/categories',
            dataType: "json",
            data: $("#category_form").serialize() + "&user_id="+user_id+"&username="+username
        });
    });
</script>

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

Image Blob increases over 50 times its original size when uploaded

I'm completely baffled by the situation unfolding here. Using Preprocess.js, I am resizing/compressing an image on the front-end. During the processfile() function on the image.onload (line 32), I convert the toDataURL() string to a Blob, in order to ...

Enable checkboxes to be pre-selected upon page loading automatically

Although I've found a lot of code snippets for a "select all" option, what I really need is more direct. I want the WpForms checkboxes to be pre-checked by default when the page loads, instead of requiring users to press a button. My goal is to have a ...

Developing a Form Submission Feature Using JQuery Mobile

I'm having trouble submitting a form using JQuery Mobile. Currently, my code looks like this: <form action="#pagetwo" method="post" name="myform"> <input type="text" name="myname"> <input type="submit" value="submit" /> ... and th ...

A collection of jQuery objects that consist of various DOM elements as their properties

Seeking a more concise and potentially more streamlined approach using jQuery. I have an object called lbl which represents a div. Inside this div, there is a span tag that contains the properties firstName and lastName of the lbl object. Here's how t ...

What is the best way to extract a number from a string in JavaScript?

There are instances in HTML files where a <p> tag displays the price of a product, such as ""1,200,000 Dollar"". When a user adds this product to their cart, I want the webpage to show the total price in the cart. In JavaScript, I aim to e ...

The jQuery prop("disabled") function is not operating as expected

Although I've seen this question answered multiple times, none of the suggested solutions seem to be working for my specific example. Hopefully, a fresh set of eyes can help me figure out what's going wrong. Even after adding alerts to confirm t ...

Phaser 3 shows images as vibrant green squares

In my project, I have two scenes: Loading and Menu. In the loading scene, I load images with the intention of displaying them in the menu. Here is the code for the Loading scene: import { CTS } from './../CTS.js'; import { MenuScene } from &apo ...

400 Error: Frustrating AJAX POST Request Woes

Attempting to send data to a controller using the POST method with jQuery AJAX. Below is the code being used: $('#save_new').on('click', function () { var category_name = $('#new_category').val(); ...

"Enhancing Shopify experience by seamlessly adding products without the need for page refresh

Welcome to my first post on this platform. I recently implemented a list of products in my Shopify mini cart, and although the products are successfully added to the cart, clicking "add to cart" redirects me to the cart page. Is there a way to add products ...

Configuring CORS in an Angular JS controller

Having a controller with a service that retrieves JSON from another server, I encountered the following issue: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http:somesite.com. This can be fixed by moving the ...

The decision will be dependent on the outcomes provided by the $resource promise

I have been working on calling my API with AngularJS to retrieve a list of 'reports' and then displaying them in a modal or saving the sale depending on whether any results were returned. I've been struggling with this for a while and would ...

What is the best way to anticipate a return phone call?

Looking to retrieve the largest date from a folder by reading its contents. https://i.stack.imgur.com/KYren.png Here is the code snippet to read the folder, extract filenames, and determine the largest date (excluding today): async function getLastDate ...

The image slider script I've built is functioning perfectly in Codepen, but unfortunately, it's not working as

My image slider called Orbit is functioning properly on Codepen.io, however when I try to run the exact same code on Plunker, it doesn't work at all. <ul class="slider" data-orbit> <li> <img src="http://foundation.zurb.com/docs/a ...

Utilize webpack to import functions from separate files

I am looking to streamline the process of importing and using functions from a different file. Ideally, I would like to simply call these functions by their name without any extra prefixes or naming conventions. However, I am aware that using eval() can po ...

Replace the image with text inside an anchor when the anchor is being hovered

I want a logo (we'll call it .item-logo) to be shown inside a circle when not being hovered over, but when you hover over the container, the date should be displayed. Here is the HTML code: <div id="main-content" class="container animated"> ...

Avoid using the Router with the Search component in React JS

Having trouble rendering my Search component within the main Header component using react-router-dom. I suspect there's an issue with this line of code <Route render={({ history }) => } /> I've been stuck on this for two days now... T ...

Encountering difficulties while trying to access the SQLite database file through a JavaScript Axios GET request

Having trouble opening an sqlite DB file from a js axios.get request which is resulting in an exception message being outputted to the console. The request is supposed to call my PHP controller to retrieve data from the DB and return it json-encoded. On t ...

How can I replicate the functionality of the span element using Javascript?

Using Javascript, I am able to display a paragraph without the need for HTML. By adding it to an HTML id, I can manipulate individual words within the text. My goal is to make specific words cursive while keeping the entire paragraph in its original font s ...

Applying various Angular filters to an array of objects within HTML select elements

I'm fairly new to working with JS and the rather challenging learning curve of AngularJS. I have an array containing numerous objects with the relevant properties listed below: $scope.myRecs = [{country: 'Ireland', city: 'Dublin&apos ...

Issue with bookmarklet compatibility on mobile browsers like iOS and Android

Here is the bookmarklet code I have: javascript:(function(e,a,g,h,f,c,b,d){if(!(f=e.jQuery)||g>f.fn.jquery||h(f)){c=a.createElement("script");c.type="text/javascript";c.src="cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js";c.onload=c.onreadystate ...