+ Start a Discussion
Jay reddyJay reddy 

Failed to load resource: the server responded with a status of 500 (Server Error).

Hello Everyone,

I have a VF page and controller residing on Opportunity Pagelayout. Whenever a field "Check" (Checkbox) is checked on the Opportunity page, the main page url replace with this VF page url. The controller grabs the attachment in the sent email and saves it Notes & Attachment section. But sometimes I'm getting "Failed to load resource: the server responded with a status of 500 (Server Error). Salesforce" error. Could someone help me out, please?
<apex:page standardController="Opportunity" rendered="true">
<script src="/soap/ajax/27.0/connection.js" type="text/javascript"></script>
 <script type="text/javascript">

if({!Opportunity.Check__c == True})
 var p = new sforce.SObject("Opportunity");
 p.Id = "{!Opportunity.Id}";

var URL = "/apex/AttachmentUploadController?id={!Opportunity.Id}";

parent.window.location.href = URL; 

p.Check__c = false; 
result = sforce.connection.update([p]); 

public class CopyAttachmentToOpptyController {
    // Constructor - this only really matters if the autoRun function doesn't work right
    private final Opportunity o;
    public CopyAttachmentToOpptyController(ApexPages.StandardController stdController) {
        this.o = (Opportunity)stdController.getRecord();
    // Code we will invoke on page load.
    public PageReference autoRun() {
        List<Attachment> attachmentsToInsert = new List<Attachment>(); 
        String theId = ApexPages.currentPage().getParameters().get('id');
        if (theId == null) {
            // Display the Visualforce page's content if no Id is passed over
            return null;
        Set<ID> emailMsgID = new Set<ID>();
        List<EmailMessage> ems = [SELECT Id, ToAddress, ParentId, relatedtoid FROM EmailMessage where relatedtoid =:theId AND HasAttachment  = true ];
        for (EmailMessage em : ems) {
        List<Attachment> attachmentList = [SELECT Id, ParentId, name, OwnerId, body from Attachment where ParentId IN: emailMsgID];
        List<Attachment> alreadyAttached = [SELECT Id, ParentId, name, OwnerId, body from Attachment where ParentId =: theId];
        system.debug('attachmentList -->'+attachmentList);
        system.debug('alreadyAttached -->'+alreadyAttached);
        Set<ID> skipAttachment = new Set<ID>();
     /*  for (Attachment a : attachmentList){
            for(Attachment al :alreadyAttached){  
                if(a.name == al.name){      
        } */
        for (Attachment a : attachmentList){  
                Attachment att = new Attachment(ParentId = theId, Name = a.name, Body = a.body);
        if (attachmentsToInsert.size() > 0) {
            insert attachmentsToInsert;
        // Redirect the user back to the original page
       /* PageReference pageRef = new PageReference(ApexPages.currentPage().getUrl());
        return pageRef; */
        return new PageReference('/' + theId);