How to pass value of variables from visualforce to controller via javascript

Have you ever stuck at situation where you actually want to send or pass the values from visualforce to controller via javascript,well it sound little tricky but it easy to pass the value to the controller via javascript so in this tutorial we will see how to achieve this i will divide this tutorial in several section so we can easily understand how to pass or send value from visualforce to controller using javascript,so lets see how to do that.You can also look at my other post.

In a brief summary we will going to use ‘apex action function’ as intermediator between javascript and controller to pass the value , see below picture for more details.

so as you can see in the above picture the flow that’s how actually the value is been passed to the controller , now we will understand the process of doing this through code there are various way of transferring the value to controller so lets see in brief how to achieve that.

The above will create two text fields as ‘first name’ and ‘full name’ now when ever i enter my first name ‘Sudhir’ then after on change event it called a javascript and that javascript will transfer the value to the controller in controller my value get changed and by using render attribute the new value get reflected back to my page,so lets divide code in smaller section to make it more understandable , so we will go as per the flow diagram which you have shown above so see the below code which is

In the above code when ever you put any text in the field then during the on change event from null to string that will call the javascript function ‘doSearch‘ and in this do search we are passing the ‘ID’ of the input text field using ‘$Component‘. Now let see the javascript code.

In the above we would get the ID in the variable ‘idd‘ and then using javascript we would get the value and then pass the value to the apexactionfunction by enclosing the value in the val(), where val is the name of apexactionfunction , see the below code of the apexactionfunction.