Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Need examples for multiple value multi-option custom fields with AJAX #99

Open
MichaelPrecel opened this issue Dec 17, 2019 · 7 comments

Comments

@MichaelPrecel
Copy link

Hey there,

I'm trying to capture data from a form to multi-option custom fields with multiple inputs.

I have it all set up, but need examples to demonstrate pulling in multiple values and passing that through the 'CustomFields' array. The examples suggest repeating the array with the same 'Key' and different 'Values', eg

'CustomFields' => array(
                array(
                  'Key' => 'Interested',
                  'Value' => '1 Bedroom'
                ),
                array(
                  'Key' => 'Interested',
                  'Value' => '2 Bedroom'
                )
            ),

This works fine. However this doesn't show how to dynamically add these arrays into the 'CustomFields' array. For example by pulling the data in with AJAX, processing the JSON array into PHP and then adding to the 'CustomFields' array. Are you able to please help with this?

An example:

HTML

<fieldset class="reasons__panel interested__panel" id="interested__panel">
                <label class="checkbox__outer">1 Bedroom Home
                    <input class="interested__input"  type="checkbox" name="interested[]" value="1 Bedroom Home"><br>
                    <span class="checkmark"></span>
                </label>
                <label class="checkbox__outer">2 Bedroom Home
                    <input class="interested__input"  type="checkbox" name="interested[]" value="2 Bedroom Home"><br>
                    <span class="checkmark"></span>
                </label>
                <label class="checkbox__outer">3 Bedroom Home
                    <input class="interested__input"  type="checkbox" name="interested[]" value="3 Bedroom Home"><br>
                    <span class="checkmark"></span>
                </label>
                <label class="checkbox__outer">Cafes & Restaurants
                    <input class="interested__input"  type="checkbox" name="interested[]" value="Cafes & Restaurants"><br>
                    <span class="checkmark"></span>
                </label>
                <label class="checkbox__outer">Retail
                    <input class="interested__input"  type="checkbox" name="interested[]" value="Retail"><br>
                    <span class="checkmark"></span>
                </label>
                <label class="checkbox__outer">Office & Co — Working
                    <input class="interested__input"  type="checkbox" name="interested[]" value="Office & Co — Working"><br>
                    <span class="checkmark"></span>
                </label>
            </fieldset>

JQuery

// AJAX Submit form to CAMPAIGN MONITOR
        // Get data from form and store it
        var cmSignupName = $('#input--name').val();
        var cmSignupEmail = $('#input--email').val();
        var cmSignupPhone = $('#input--phone').val();
        var cmSignupPostcode = $('#input--postcode').val();
        var cmSignupInterested = [];
        $('.interested__input:checked').each(function(){
          var interested = $(this).val();
          cmSignupInterested.push(interested);
        });
        var cmSignupComments = $('#input--comments').val();

        // Create JSON variable of retrieved data
        var cmSignupData = {
          'name': cmSignupName,
          'email': cmSignupEmail,
          'phone': cmSignupPhone,
          'postcode': cmSignupPostcode,
          'Comments': cmSignupComments,
          'Interested': cmSignupInterested
        };


        // Send data to PHP script via AJAX
        $.ajax({
          url: $(this).attr('action') + '/cm',
          type: 'POST',
          dataType: 'json',
          data: cmSignupData, 
        });

I've attempted plenty of ways of achieving this in PHP, but I cannot get this to work. I am guessing a new array is needing to be stored in a variable and inputted as the 'CustomFields' value? The code below is terrible, but just for a demonstration of what I need to achieve.

PHP

$interested = json_decode( $_POST['Interested'] );
        $interested__array = array();

        foreach ( $interested as $item ) {
          array_push($interested__array, $item);
        }


        $result = $wrap->add(array(
            'EmailAddress' => $_POST['email'],
            'Name' => $_POST['name'],
            'CustomFields' => array(
                array(
                    'Key' => 'phone',
                    'Value' => $_POST['phone']
                ),
                array(
                    'Key' => 'postcode',
                    'Value' => $_POST['postcode']
                ),
                array(
                  'Key' => 'Comments',
                  'Value' => $_POST['Comments']
                ),
                $interested__array
            ),
            'ConsentToTrack' => 'yes',
            'Resubscribe' => true
        ));

Any and all help is much appreciated!

@troyrasiah
Copy link

I ripped this from my working code, hope it helps. Where $_POST['subscriptions'] is stored in the form like
name="subscriptions[checkbox1]"
name="subscriptions[checkbox2]"
etc

  if (array_key_exists('subscriptions', $_POST)) {
    foreach ($_POST['subscriptions'] as $subscriptionSegment) {
      array_push($addSubscriber['CustomFields'], array(
        'Key' => 'Pleasesendme',
        'Value' => $subscriptionSegment
      ));
    }
  } else {
    /* If nothing has been ticked you still need to send the array key as blank. Not sending it at all will make it use what's already in the record */
    array_push($addSubscriber['CustomFields'], array(
      'Key' => 'Pleasesendme',
      'Value' => ''
    ));
  }

@MichaelPrecel
Copy link
Author

Thanks so much for your help @troyrasiah.

Are you able to please provide the full PHP code block? As I'm a bit of a PHP newbie and unsure of how $addSubscriber fits in with the wrapper provided —

$result = $wrap->add(array(
  'EmailAddress' => $_POST['email'],
  'Name' => $_POST['name'],
  'CustomFields' => array(
    array(
      'Key' => 'phone',
      'Value' => $_POST['phone']
    ),
    array(
      'Key' => 'postcode',
      'Value' => $_POST['postcode']
    ),
    array(
      'Key' => 'Comments',
      'Value' => $_POST['Comments']
    )
  ),
  'ConsentToTrack' => 'yes',
  'Resubscribe' => true
));

@troyrasiah
Copy link

No problems, pretty much the same as what you have pasted. This is what else I have in addSubscribers

  $addSubscriber = array(
      'EmailAddress' => $_POST['email'],
      'Name' => $_POST['name'],
      'CustomFields' => array(
          array(
            'Key' => 'Postcode',
            'Value' => $_POST['postcode']
          )
      ),
      'ConsentToTrack' => 'yes',
      'Resubscribe' => true,
      'RestartSubscriptionBasedAutoresponders' => true
  );

  $result = $wrap->add($addSubscriber);

  if ($result->was_successful()) {
    /* Success Message */
  } else {
    print $result->response->Message;
  }

@MichaelPrecel
Copy link
Author

Thanks @troyrasiah, you're a serious lifesaver. This worked a treat.

For anyone else who may run into this problem, you can reference the full code below with HTML as above.

JQuery

// AJAX Submit form to CAMPAIGN MONITOR
        // Get data from form and store it
        var cmSignupName = $('#input--name').val();
        var cmSignupEmail = $('#input--email').val();
        var cmSignupPhone = $('#input--phone').val();
        var cmSignupPostcode = $('#input--postcode').val();
        var cmSignupComments = $('#input--comments').val();
        
        // Mutli-option Fields
        var cmSignupReasons = [];
        $('.reasons__input:checked').each(function(){
          var reason = $(this).val();
          cmSignupReasons.push(reason);
        });
        
        var cmSignupInterested = [];
        $('.interested__input:checked').each(function(){
          var interested = $(this).val();
          cmSignupInterested.push(interested);
        });

        // Create JSON variable of retreived data
        var cmSignupData = {
          'name': cmSignupName,
          'email': cmSignupEmail,
          'phone': cmSignupPhone,
          'postcode': cmSignupPostcode,
          'Comments': cmSignupComments,
          
          // Multi-option Fields
          'Referral': cmSignupReasons,
          'Interested': cmSignupInterested,
        };

        // console.log(cmSignupData);

        // Send data to PHP script via AJAX
        $.ajax({
          url: $(this).attr('action') + '/cm',
          type: 'POST',
          dataType: 'json',
          data: cmSignupData, 
        });

PHP

// Create Array
        $addSubscriber = array(
          'EmailAddress' => $_POST['email'],
          'Name' => $_POST['name'],
          'CustomFields' => array(
            array(
              'Key' => 'phone',
              'Value' => $_POST['phone']
            ),
            array(
              'Key' => 'postcode',
              'Value' => $_POST['postcode']
            ),
            array(
              'Key' => 'Comments',
              'Value' => $_POST['Comments']
            )
          ),
          'ConsentToTrack' => 'yes',
          'Resubscribe' => true
        );
  
        // Push Referral segments
        if (array_key_exists('Referral', $_POST)) {
          foreach ($_POST['Referral'] as $referralSegment) {
            array_push($addSubscriber['CustomFields'], array(
              'Key' => 'Referral',
              'Value' => $referralSegment
            ));
          }
        } else {
          /* If nothing has been ticked you still need to send the array key as blank. Not sending it at all will make it use what's already in the record */
          array_push($addSubscriber['CustomFields'], array(
            'Key' => 'Referral',
            'Value' => ''
          ));
        }

        // Push Interested segments
        if (array_key_exists('Interested', $_POST)) {
          foreach ($_POST['Interested'] as $interestedSegment) {
            array_push($addSubscriber['CustomFields'], array(
              'Key' => 'Interested',
              'Value' => $interestedSegment
            ));
          }
        } else {
          /* If nothing has been ticked you still need to send the array key as blank. Not sending it at all will make it use what's already in the record */
          array_push($addSubscriber['CustomFields'], array(
            'Key' => 'Interested',
            'Value' => ''
          ));
        }

        // Push the array to Campaign Monitor
        $result = $wrap->add($addSubscriber);

@v3nt
Copy link

v3nt commented Feb 28, 2020

I ripped this from my working code, hope it helps. Where $_POST['subscriptions'] is stored in the form like
name="subscriptions[checkbox1]"
name="subscriptions[checkbox2]"
etc

  if (array_key_exists('subscriptions', $_POST)) {
    foreach ($_POST['subscriptions'] as $subscriptionSegment) {
      array_push($addSubscriber['CustomFields'], array(
        'Key' => 'Pleasesendme',
        'Value' => $subscriptionSegment
      ));
    }
  } else {
    /* If nothing has been ticked you still need to send the array key as blank. Not sending it at all will make it use what's already in the record */
    array_push($addSubscriber['CustomFields'], array(
      'Key' => 'Pleasesendme',
      'Value' => ''
    ));
  }

do you need unique names for the checkbox options?

name="subscriptions[checkbox1]"
name="subscriptions[checkbox2]"

really stuck on this and tried multiple checkbox with same name

subscriptions
or
subscriptions[]

But just note getting through to CM.

@v3nt
Copy link

v3nt commented Feb 28, 2020

    var cmSignupInterested = [];
    $('.interested__input:checked').each(function(){
      var interested = $(this).val();
      cmSignupInterested.push(interested);
    });

@troyrasiah could you post your final markup for the html form element? Followed this to a T but rstuck and tried everything possible!

@troyrasiah
Copy link

So I have 2 checkboxes in my form. They have the html code as follows

<input class="formfield subscribe_cbx form-checkbox" type="checkbox" id="edit-subscriptions-education-news" name="subscriptions[Education News]" value="Education News"> <input class="formfield subscribe_cbx form-checkbox" type="checkbox" id="edit-subscriptions-slv-monthly" name="subscriptions[SLV Monthly]" value="SLV Monthly">

Which relates to the PHP from my previous post (Adds multiple elements to $addSubscriber['CustomFields'])

Any issues just give me a yell

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants