currently, I'm learning rails then I come up to the point to use jquery to send ajax for the form, I know about the ujs but I don't want to use it. I want to use the pure javascript or jquery for learning purpose ( understanding it ). So, I have this problem that when I click the submit the button it become disable and also when I use this way
$( function( ) {
var form = $( '#new_post' );
var formData = $( form ).serialize();
$( form ).submit( function( event ) {
$.ajax( {
type: 'POST',
url: $( this ).attr( 'action' ),
dataType: 'json',
data: formData
} ).done( function ( response ) {
console.log( response );
} )
event.preventDefault();
} )
} );
the serialize formData
is empty but when I tried this way
$( function( ) {
var form = $( '#new_post' );
$( form ).submit( function( event ) {
$.ajax( {
type: 'POST',
url: $( this ).attr( 'action' ),
dataType: 'json',
data: $( form ).serialize()
} ).done( function ( response ) {
console.log( response );
} )
event.preventDefault();
} )
} );
which is I call directly the $( form ).serialize()
inside the ajax. I don't understand what's the difference but I tried to do some research already and I can't find the answer.
By the way, this the rails form.
<%= form_for( post ) do |f| %>
<div class="field">
<%= f.label :title %>
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :content %>
<%= f.text_area :content %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
Change your code like this:
$( function( ) {
var form = $( '#new_post' );
// Directly use the variable created above
form.submit( function( event ) {
event.preventDefault();
$.ajax( {
type: 'POST',
url: form.attr( 'action' ),
dataType: 'json',
data: form.serialize()
} ).done( function ( response ) {
console.log( response );
} )
} )
} );
The below code will not work:
$( function( ) {
var form = $( '#new_post' );
//formData is empty when the page loads and the same value is getting assigned inside the ajax call which is wrong.
//Therefore the best way is to directly get the data while submitting the form.
var formData = form.serialize();
form.submit( function( event ) {
event.preventDefault();
$.ajax( {
type: 'POST',
url: form.attr( 'action' ),
dataType: 'json',
//Here formData is empty
data: formData
} ).done( function ( response ) {
console.log( response );
} )
} )
} );
I know already why. lol
$( function( ) {
var form = $( '#new_post' );
form.submit( function( event ) {
var formData = form.serialize();
event.preventDefault();
$.ajax( {
type: 'POST',
url: form.attr( 'action' ),
dataType: 'json',
data: formData
} ).done( function ( response ) {
console.log( response );
} )
} )
} );
the var formData = form.serialize();
should be inside the submit event, so that it have the data inputted by the user.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.