JJ Beck
JJ Beck

Reputation: 5283

Submit form in JQuery

In my Rails view, I have an HTML form

<form name="input">
Username: <input type="text" name="user"> <br/>
<input type="button" id="submit_form" value="Submit">
</form> 

When the submit button is clicked, I want to use JQuery to call the controller download, and also pass along the user parameter. (In routes.rb I specify match "download" => "Posts#download")

How should I use JQuery to do this?

$("#submit_form").click(function() {
  // what should I put here?
});

Upvotes: 1

Views: 1478

Answers (5)

Jaijaz
Jaijaz

Reputation: 134

If I understand correctly you are trying to submit the form through jQuery instead of the normal post process. I'd suggest using jQuery's form submit function

Basically you'll be looking for something like:

$("form").submit(function() {
  var data = $(this).serialize();
  $.ajax({
    url: "controller/action",
    type: "POST",
    data: data
    // plus anyother options you are wanting
  }).done(function() { 
    // a success function
  });
  return false;
  });

Hope that helps.

Upvotes: 0

imwill
imwill

Reputation: 598

You could do this:

/* attach a submit handler to the form */
  $("#submit_form").submit(function(event) {

    /* stop form from submitting normally */
    event.preventDefault(); 

    /* get some values from elements on the page: */
    var $form = $( this ),
        term = $form.find( 'input[name="user"]' ).val(),

    /* Send the data using post and fire some callback */
    $.post( "/download", { s: term },
      function( data ) {
       //some callback
      }
    );
  });

Source: Modified example from jQuery docs

Upvotes: 2

Leo Correa
Leo Correa

Reputation: 19789

jQuery provides a .submit() http://api.jquery.com/submit/

You don't need to bind to the click method of the input button as that submit button already knows to submit the form.

What you are looking for is

$("form[name='input']").submit(function(){
  //do something before function gets submitted
});

Inside that function you'll want an ajax call to your server and use preventDefault to cancel the original submit of the form.

Upvotes: 0

The Heatherleaf
The Heatherleaf

Reputation: 128

I'm not a Rails developer but can't you put the route in the forms action and then use submit, as follows:

<form name="input" action="/Download">

$("#submit_form").click(function() {
  $("#input").submit();
});

Upvotes: 0

Nikita U.
Nikita U.

Reputation: 3618

$("#submit_form").click(function() {
  // what should I put here?
  $('form[name="input"]').submit();
});

Or you can just set type="submit" to your input with id="submit_form" and don't set any handlers

Upvotes: 0

Related Questions