function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
tsalbtsalb 

Javascript - after document submit completion via post, invoke method to insert record?

Currently, when a button is clicked to upload file , the object record is created first - then through actionFunction oncomplete, the document is submitted to amazon S3. I need this to be reversed... submit completion first - then create the file. I've tried to play with jQuery because research indicated it might be applicable to this problem. But...after 5 hours of being unsuccessful (i'm completely new to javascript and jQuery, and was hoping for some guidance here) - i'm looking for some advice.

 

This is the relevant code, untouched (working as is). I can post my jQuery edits if anyone requests, but i'm not sure if it's even the viable option and i'm sure something is wrong there as well.

 

Is there a javascript function (i've googled, and no examples ive found help) that invokes a method in salesforce, AFTER the document submission? not onsubmit, must be after a successful "upload"

 

   <apex:pageMessages id="pageErrors"></apex:pageMessages>
   
    <form name="s3Form" action="https://s3.amazonaws.com/mycompanybucket" method="post" enctype="multipart/form-data">   
        
        <input type="hidden" name="key"/> 
        <input type="hidden" name="AWSAccessKeyId" value="{!key}"/> 
        <input type="hidden" name="policy" value="{!policy}"/>
        <input type="hidden" name="signature" value="{!signedPolicy}"/> 
        <input type="hidden" name="acl" value="private"/> 
        <input type="hidden" name="x-amz-meta-FileId" value="{!File__c.id}"/>
        <input type="hidden" name="x-amz-meta-OrderId" value="{!OrderId}"/>
        <input type="hidden" name="x-amz-meta-CustomerId" value="{!CustomerId}"/>     
        <input type="hidden" name="success_action_redirect" value="{!serverUrl}{!OrderId}"/>           
        
        <apex:pageBlock title="New File Upload" mode="maindetail" tabStyle="File__c">
        
            <apex:pageBlockSection title="File Information" columns="2" collapsible="false" showHeader="false"> 
                                                                       
                <apex:pageBlockSectionItem >
                    <apex:outputLabel value="Select File" for="selectFile"/>            
                    <input id="selectedFile" type="file" size="25" name="file" onChange="setFileName(this.value)"/>                
                </apex:pageBlockSectionItem>    

                <apex:pageBlockSectionItem >
                    <apex:outputLabel value="Select File" for="fType"/>                            
                    <select id="fType" onChange="setFileType(this.value)">
                        <option value="--None--">--None--</option>
                        <option value="Valuation">Valuation</option>
                        <option value="Data Sheet">Data Sheet</option>
                        <option value="Invoice">Invoice</option>
                        <option value="Review">Review</option>
                        <option value="Other">Other</option>
                    </select>                          
                </apex:pageBlockSectionItem>                                        
                           
            </apex:pageBlockSection>

            <apex:pageBlockButtons location="bottom">
                <input class="btn" type="button" value="Upload File" onClick="checkFile();return false;"/>                
                <input class="btn" type="button" value="Cancel" onClick="cancelFile();return false;"/>
                <input class="btn" type="button" value="Complete Order" onClick="completeFile();return false;"/>
            </apex:pageBlockButtons>          

        </apex:pageBlock>
       
    </form> 
    
     <apex:form id="sfForm">
     
        <apex:inputHidden id="hiddenServerURL"  value="{!serverURL}"/>
        <apex:inputHidden id="fileName" value="{!fileName}"/>
        <apex:inputHidden id="contentType" value="{!contentType}"/>
        <apex:inputHidden id="fileType" value="{!fileType}"/>
        <apex:actionFunction name="insertFile" action="{!insertFile}" oncomplete="submitFile();return false;"/>
        <apex:actionFunction name="completeOrder" action="{!completeOrder}"/>

        
        <script type="text/javascript">
        var sendFile = false;
        document.getElementById('{!$Component.hiddenServerURL}').value = '{!$Api.Enterprise_Server_URL_140}';       
        function setFileName(file) {
            var f = file.replace(/\\/g, "");
            f = f.replace(/C\:fakepath/g, ""); <!--Required for IE8-->
            document.s3Form.key.value = "{!CustomerName}/{!OrderName}/" + f;
            document.getElementById('{!$Component.fileName}').value = f;
            suffix = f.lastIndexOf(".") + 1;
            contentType = f.slice(suffix);
            document.getElementById('{!$Component.contentType}').value = contentType;
        }
        function setFileType(type) {
            document.getElementById('{!$Component.fileType}').value = type;
        }
        function checkFile() {
            if (document.s3Form.file.value=="") {
                alert("Please, select a file.");
                return false;
            } 
            else if (document.s3Form.fType.value=="--None--") {
                alert("Please, select a file type.");
                return false;
            }
            else {     
            	alert("Uploading...Please click OK and wait for page to refresh.");        
              	insertFile();
               	sendFile = true;
            }
        }
        function submitFile() {
            if(sendFile = false) {
            return false;
            }
            else {
            document.s3Form.submit();
            }
        } 


insertFile() Method on extension:

//SF File insert on an object (passed from page)
    public PageReference insertFile() {
        this.file.Name = fileName;
        this.file.Type__c = fileType;
        this.file.Content__c = contentType;
        insert this.file;
        return null;
    }

 

jshimkoskijshimkoski

If you're using jQuery, it sounds like you'd need an ajax return... Check out:

 

jQuery.ajax(): http://api.jquery.com/jQuery.ajax/

or

jQuery.post(): http://api.jquery.com/jQuery.post/

or

jQuery.get(): http://api.jquery.com/jQuery.get/

 

I personally would use jQuery.ajax();

 

To get a callback on successful completion do something like this:

 

$.ajax({
  url: "test.html",
  context: document.body,
  success: function(){
    alert("This will popup after the ajax stuff was processed!");
  }
});

 

tsalbtsalb

I'm not sure how to integrate Jquery in with the Javascript above? I tried this - but it doesn't work - and I can't find an examples to wrap my head around...help =(

 

	<script type="text/javascript">
        
  	$(document).ready(function() {
	
		$("p").click(function() {
		 alert("Hello world!");
		});

        var ProgressImage = document.getElementById('{!$Resource.ajaxloader}');
        document.getElementById('{!$Component.hiddenServerURL}').value = '{!$Api.Enterprise_Server_URL_140}';       
        function setFileName(file) {
            var f = file.replace(/\\/g, "");
            f = f.replace(/C\:fakepath/g, ""); <!--Required for IE8-->
            document.s3Form.key.value = "{!CustomerName}/{!OrderName}/" + f;
            document.getElementById('{!$Component.fileName}').value = f;
            suffix = f.lastIndexOf(".") + 1;
            contentType = f.slice(suffix);
            document.getElementById('{!$Component.contentType}').value = contentType;
        }
        function setFileType(type) {
            document.getElementById('{!$Component.fileType}').value = type;
        }
        function checkFile() {
            if (document.s3Form.file.value=="") {
                alert("Please, select a file.");
                return false;
            } 
            else if (document.s3Form.fType.value=="--None--") {
                alert("Please, select a file type.");
                return false;
            }
            else if (document.s3Form.file.value.length > 79) {
                alert("Filename is over 80 characters, please shorten the Filename and try again.");
                return false;
            } 
            else {     
            	loadSubmit();       
              	submitFile();
            }
            
           	$.ajax({
   			  type: "POST",
   			  url: "https://s3.amazonaws.com/mycompanybucket",
   			  complete: insertFile
			});
        }
        function submitFile()
            document.s3Form.submit();
        }
        function loadSubmit() {
			document.getElementById("progress").style.visibility = "visible";
			setTimeout(function(){ProgressImage.src=ProgressImage.src},100);
			return true;
		}    
        function cancelFile() {  
            window.location.href = "{!$Setup.companyInfo__c.company__c}";
        }
        function completeFile() {
            completeOrder();
        }
 	
  	});   
    </script>

 

jshimkoskijshimkoski

I can see a couple of issues straight off the bat.

 

I'm not sure if you omitted the function from the code you posted, but $.ajax is calling the insertFile function on complete but insertFile does not exist in the code you posted. In addition, if you are trying to send data via ajax, that isn't really how you'd go about it.

 

I would use the $.ajax() function to replace the functionality of the form's submit... something like:

 

$("form").submit(){
    // Get the form's data
    var formData = $(this).serialize();

    // Send an ajax post request to the url for processing
    // Upon successful transmission of data, alert "Data saved to server"
    $.ajax({
        type: "POST",
        url: "https://s3.amazonaws.com/mycompanybucket",
        data: formData,
        success: function(msg) {
            alert("Data saved to server! The server returned: " + msg);
        }
    });

    // Cancel form's default action
    return false;
});

 

The code above is not tested and is probably not the best way of doing things but I hope it helps.

 

Be sure to read the jQuery documentation at jquery.com. If you want to use their library, that is the best place to go for reference.