Pawan Pawan - 7 months ago 18
Javascript Question

Yii2: Auto save form on navigate to another tab in a form

I'd say I want to submit each tabs content (form values) when another tab is selected. That way the user navigate between tabs without having to reload the whole form. And the values are saved even if partially filled to the database

I think this can done using jquery or javascript like clicking on the tab will imitate the clicking on save button simultaneously.

I have also tried this code but it's not working? The id of the tab is #ui-id-3 and id of save button is #save1.

<script>
$('#ui-id-3').click(function(){
$('#save1').click();
return false;
});
</script>


What I am doing wrong here?

With suggest modification:

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(function() {
$("#ui-id-3").click(function(){
autoSave();
return false;
});
});

function autoSave(){
var formData = $("#w0").serialize();
$.ajax({
type:"POST",
url:"/hospitalerp/web/index.php?r=daily-ward-entry%2Fcreate",
data:formData,//only input
success: function(response){
$( "#recordID" ).val( response);
}
});


}
</script>

Answer

Here is a simple solution but you have have to modify according to you needs

Step one :

Create a hidden field with for ID field we will store database record Id in it you can name/id input as recordID so we can reference it in our jQuery Code

<input type="hidden" name="recordID" id="recordID" value="0" />

Step two :

Create a server page which will server for Database Insertion/Updation you can called it autoSave.php this page will receive complete form and if recordID <=0 then it will insert into db and return the newly inserted ID else it will update table where Id = recordID

Step 3 :

Jquery Code which will call autoSavePage upon Tab Click.

$(function() {
  $(".tabs").click(function(){
    autoSave();
    return false;
  });
});

function autoSave(){
      var formData = $("#formID").serialize();
      $.ajax({
        type:"POST",
        url:"autoSave.php",
        data:formData,//only input
        success: function(response){
            $( "#recordID" ).val( response);  
        }
    });
    
            
  }
Html Form ID should be formID

<form id="formID" method="POST" action="autoSave.php">..

This is the idea when ever anyone click on any tab a ajax call will be generate to save the form rest you have to modify according to your code as you have not submitted any code thats why i have make a generic example

Hope this will Help!