Reputation: 107
Is there any way to submit the form to server for an AJAX response without reloading the page. I am able to do this with submit button. But how can I do that when a link is clicked.
I came to know about a javascript method to do this,
var form = document.getElementById('myForm');
form.submit();
But the above code reloads the page. I came to know that we can do this with jquery but how?
Please Note that I am developing my application in Ruby on Rails 3.0.4 and I am using the rails AJAX like this.
<%= form_for @search, :remote => true, :url => request_path, :html => {:method => :get, :id => :my_form} do |f| %>
Any help would be appreciated.
Upvotes: 3
Views: 15524
Reputation: 107
I got it working by just using this code. No need to define a function inside submit.
$('#myform').submit();
Upvotes: -1
Reputation: 413
I know i am a bit late to the party, as an alternative to the above anwsers, you could use the jQuery Form plugin for easy ajax form updating.
If you used it, the most simple version of your JS code would look like this.
$('#myform').ajaxForm(function() {
success: alert('success');
});
There are many more options you can use to configure it how you like.
The url that the form is submitted to is the same as the action
attribute of your form.
This can also be changed.
From my exprecience you do not need to preventDefault()
the submit either, it does it for you.
Anyways, this is another alternative to your problem, if you find it convenient.
Upvotes: 2
Reputation: 22329
You can use .post() to do an ajax post.
Taken from the documentation:
$.ajax({
type: 'POST',
url: url,
data: data,
success: success,
dataType: dataType
});
You could also use .submit()
Taken from documentation:
$('#target').submit(function() {
alert('Handler for .submit() called.');
return false;
});
Now when the form is submitted, the message is alerted. This happens prior to the actual submission, so we can cancel the submit action by calling .preventDefault() on the event object or by returning false from our handler.
You can combine the 2 as shown by Raminson
:
$('#target').submit(function() {
.preventDefault()
$.ajax({
type: 'POST',
url: url,
data: data,
success: success,
dataType: dataType
});
});
Upvotes: 3
Reputation: 2250
If the problem is your page reloading with form.submit() try:
var form = document.getElementById('myForm');
form.submit(function(e){
e.preventDefault();
//an ajax post as in François Wahl answer
});
Upvotes: 1
Reputation: 144679
You can use the preventDefault()
method of event
object :
$('#myForm').submit(function(event){
event.preventDefault();
$.ajax({
...
});
})
If this method is called, the default action of the event will not be triggered.
Upvotes: 10