user1670773
user1670773

Reputation:

Rails 4: passing custom data and form data in ajax call

I am trying to submit a simple form using ajax call this way

$('#save-artificial-form').click(function () {
  var fd = $('#categories-form').serialize();
  console.log(fd);
  var url = "/categories";
  $.ajax({
    type: 'POST',
    url: url,
    data: $('#categories-form').serialize(),
    success: function() {
      return true;
    }
  });

It works perfectly fine and save form data. But I want to add one more data category_type but I don't know how to do this. I want something like this

data: $('#categories-form').serialize(), category_type: "advanced"

How can I do this? It is okay if category_type is added/pushed in the fd variable above.

code in my form

<%= form_for(@category, :html => {:id => "categories-form", class: "form-alt"}) do |f| %>
  <% if @category.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@category.errors.count, "error") %> prohibited 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 style="margin: 6px 0px 0 0 !important;">
      <%= link_to "This is test", 'javascript:void(0)', id: "save-artificial-form", :rel => "tooltip", :title => "save" %>
    </div>
<% end %>

Upvotes: 0

Views: 587

Answers (1)

Erick Eduardo Garcia
Erick Eduardo Garcia

Reputation: 1157

Option 1:

Use a hidden field and it will be added automatically to the serialized string

<%= f.hidden_field :category_type, value: 'advanced' %>

Option 2:

Concat the missing value to the serialized string ie. "param=value"+ "&missing_data=bar"

data: $('#categories-form').serialize() + '&category_type=advanced'

Upvotes: 1

Related Questions