hengsokly
hengsokly

Reputation: 116

save data immediately after losing focus the textfield in rails

I want to save data that has many fields in the form in rails. Actually, I am afraid that when I am filling data to the form, those data may be lost accidentally, so I want to save those data one by one after I lose focus from the text field. I wonder weather there is any gem or ways to do that.

Upvotes: 2

Views: 3068

Answers (4)

Manish Puri
Manish Puri

Reputation: 422

Ajax is the answer. But think about the performance. if you send a request after every attribute looses focus, it will send multiple request to database and server..

Upvotes: 1

Dol
Dol

Reputation: 964

Use the jQuery blur function and as @Rab Nawaz said, AJAX to submit the data.

Here is a working example of blur, an explanation and documentation

So something like:

$("input").blur(function(){
  $("form.form_class").submit();
});

Just make sure that the form is set up properly for AJAX.

Or if you're looking for a gem, you could try this one. Never used it but it looks kind of cool. Hope it helps.

Upvotes: 3

HungryCoder
HungryCoder

Reputation: 7616

For sending new data to server, you don't need any Gem. You can simply use jQuery (of course you can use gem for jQuery). Just hook your update code to your field's blur event.

$(document).on('blur', 'input[type=text]', function(e){
  post_data = {}; //prepare your data here
  $.post(UPDATE_URL, post_data, function(response_data){
     console.log(data)
  })
})

Now when you edit a text field (you can add other fields in the query if you want), it will send the updated DATA to the server. You should put in UPDATE_URL so that you can use it. However, you also need the csrf_token_name and value for making post request. Add those to post_data. If you can't find how, I may probably help you.

Upvotes: 0

Related Questions