+ Start a Discussion
Joe HayesJoe Hayes 

Javascript button to update field with button and redirect to page if update is success

I have a JS button to update a text field with todays date and then redirect to a different page. I'm not sure why it always errors.
 
{!REQUIRESCRIPT("/soap/ajax/39.0/connection.js")}

    var opp = new sforce.SObject("Opportunity");
        opp.Id = "{!Opportunity.Id}";

    var today = new Date();
    var dd = today.getDate();
    var mm = today.getMonth();
    var yyyy = today.getFullYear();

    if (dd < 10) { 
            dd = '0' + dd;
        } 
        if (mm < 10) { 
            mm = '0' + mm;
        }
    
    opp.Docusign_Send_Date__c = dd + '/' + mm + '/' + yyyy;

    var result = sforce.connection.update(opp);

    if(result[0].success === "true"){
        window.location = 'PAGE-REDIRECT-URL-HERE';
    }
    else{
     
   alert(
            "An Error has Occurred. Error: " +
            result[0].errors.message
        );
    }

Thanks
Khan AnasKhan Anas (Salesforce Developers) 
Hi Joe,

Greetings to you!

You need to use var result = sforce.connection.update([opp]); instaed of var result = sforce.connection.update(opp);

Please try below code:
{!REQUIRESCRIPT("/soap/ajax/39.0/connection.js")}

    var opp = new sforce.SObject("Opportunity");
        opp.Id = "{!Opportunity.Id}";

    var today = new Date();
    var dd = today.getDate();
    var mm = today.getMonth();
    var yyyy = today.getFullYear();

    if (dd < 10) { 
            dd = '0' + dd;
        } 
        if (mm < 10) { 
            mm = '0' + mm;
        }
    var monthDateYear = dd + "/" + mm + "/" + yyyy;
    opp.Docusign_Send_Date__c = monthDateYear
    var result = sforce.connection.update([opp]);

    if(result[0].success === "true"){
        //window.location = "PAGE-REDIRECT-URL-HERE";
        location.reload();
    }
    else{
     
   alert(
            "An Error has Occurred. Error: " +
            result[0].errors.message
        );
    }

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas