If we need to save form data without page reload, generally we can use action function. When form is having some data and file and needed to save with action function (without reload page), then we needed to use two different Ajax call one is action function and another is VF Remoting.
Action function with <apex:inputFile> doesn’t work so we have to separate form data and <apex:inputFile>. For separation we can use <action:region>
to do separate form data from <apex:inputFile>. We have to create two separate function one for save form data and one is for save
file with @RemoteAction annotation. Here file is save in attachment and example with contact.
public void SaveData()
{
contact con=new contact();
con.FirstName=fname;
con.LastName=lname;
insert con;
conId=con.id;
fname=”;
lname=”;
}
Below written function will be called through VF Remoting, on complete of action function.Action function will called the SaveData() function.
@RemoteAction
public static void DoAttachment(id conId, string attachmentBody,string name)
{
system.debug(‘DoAttachment is called’);
system.debug(‘applicantId=>’+applicantId+’\n attachmentBody=>’+attachmentBody+’\n name=>’+name);
try
{
Blob attachedBody=EncodingUtil.base64Decode(attachmentBody);
Attachment attch=new Attachment();
attch.Body=attachedBody;
attch.Name=name;
attch.ParentId=conId;
insert attch;
}catch(Exception ex){
system.debug(ex.getLineNumber());
}
}
Calling RemoteAction function through VF Remoting is given below:-
function uploadAttachment(){
var attachmentBody = “”;
if(fileSize <= positionIndex + chunkSize) {
attachmentBody = attachment.substring(positionIndex);
doneUploading = true;
}
else {
attachmentBody = attachment.substring(positionIndex, positionIndex + chunkSize);
}
Visualforce.remoting.timeout = 120000;
var appid=$(“[id$=’appId’]”).val();
// Call the remote action to save attachment.
Visualforce.remoting.Manager.invokeAction(
‘{!$RemoteAction.TestVfRemoting.DoAttachment}’,
ConId,attachmentBody,fileName1,
function(result, event){
},
{escape: true}
);
}