0

As the subject says, I would like to use two line of SSJS code in a for loop like in the example:

VAR @listAddress, @nameChosen, @Counter, @i, @AddressRow, 
SET @listAddress = RetrieveSalesforceObjects('Object__c', 'Id, Name', 
                                                  'Name', '=', @nameChosen)

IF @Counter > 0 THEN
    FOR @i = 1 to @Counter DO
        SET @AddressRow = Row(@listAddress, @i)
        SET @fieldRetrieved = Field(@AddressRow, 'Field__c')
            <script language="javascript" runat="server">
                var str = Variable.getValue("@fieldRetrieved ");
                var obj = {field : str};
                listRecord.push(obj);
            </script>
      NEXT @i
 ENDIF

Is it possibile that I am getting an error because I can't mix AMPScript for loop and SSJS?

3

You're missing the core library and some AMPscript block tags. You'll need that to execute the proprietary functions:

<script language="javascript" runat="server">
    Platform.Load("Core","1.1.5");
</script>
%%[

VAR @listAddress, @nameChosen, @Counter, @i, @AddressRow, 
SET @listAddress = RetrieveSalesforceObjects('Object__c', 'Id, Name','Name', '=', @nameChosen)

IF @Counter > 0 THEN

    FOR @i = 1 to @Counter DO

        SET @AddressRow = Row(@listAddress, @i)
        SET @fieldRetrieved = Field(@AddressRow, 'Field__c')

        ]%%

        <script language="javascript" runat="server">

            try {

              var str = Variable.getValue("@fieldRetrieved ");
              var obj = {field : str};
              listRecord.push(obj);

            } catch (e) {

              Write("<br>e: " + Stringify(e));

            }
        </script>

        %%[

      NEXT @i

 ENDIF

]%%

Reference

  • 1
    I think you need to close the AMPScript block before opening the SSJS block. Then reopen the block once SSJS block is completed. E.g. add ]%% after 'Field__c') and add %%[ before NEXT @i. – Gortonington Nov 27 '18 at 14:40
  • Duh, you're right. Updated. – Adam Spriggs Nov 27 '18 at 16:44
  • As I commented earlier (and deleted because of a mirage), if i delete the script in the for loop the code works again, and I have no clue at this point – Federico Amici Nov 27 '18 at 18:21
  • You could try a try/catch block to see if you can identify the exception. That's a bonus of using SSJS. – Adam Spriggs Nov 27 '18 at 18:42
  • The problem is that if I remove the SSJS block (including %%[ and ]%%) the code works. The AMPScript is a part of else-branch that is not executed in a test of the page, but it still returns me 500 error if the SSJS is included, works if removed. – Federico Amici Nov 28 '18 at 9:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.