Adding contact to list with AJAX

Hi,

I’m trying to work out how to add a contact to a list on my account through AJAX. Are there any simple examples of this?

I’ve tried this: API Examples Using contact_sync, but all I get back is ‘Nothing was returned. Do you have a connection to Email Marketing server?’.

The only data that is going to be passed to the CRM is the email address (it’s a newsletter list).

Any help on this would be really appreciated.

Thanks

1 Like

Hi… assuming you are using jQuery… have you use type:“POST” ?

Hey @themarketingcampaig1,

@Viktor_Iwan is correct, in order to add a contact to your list using ajax you can do it a couple of ways. If you are using jQuery it might look something like this:


var apiUrl = "http://account.api-us1.com"; // get this from settings
var apiString = apiUrl + "/admin/api.php";
var apiKey = ""; // WARNING! probably want to keep this off of client-side calls!

var contact = {
  "api_action": "contact_sync",
  "api_key": apiKey,
  "email": "test@example.com",
  "first_name": "Test", // optional
  "last_name": "User" // optional
  //  additional fields from http://www.activecampaign.com/api/example.php?call=contact_sync
};

$.post(apiString, contact, (response) => {
  console.log("Response: ", response);
});

Hi jskole,

Thanks for your response.

What’s the best way of hiding the apikey variable from public viewing? Is it to run this in PHP over javascript?

Thanks

Ahhh good question @themarketingcampaig1,

I probably should have thought about that a bit better. If you are only subscribing a contact to your list, and keeping the api key safe is a concern, it probably isnt the best idea to use the contact_sync API endpoint.

There are a few ways to do it, the one is you could send a POST request via AJAX to your own PHP server/script for processing on the server, and then make the contact_sync call serverside.

I’ll talk to the devs and see what else they recommend.

Hi Jskole,

Thanks for your quick response.

Using PHP would help as I am currently using a local development nad cross origin is making the javascript method impossible.

I have been trying to wrap my head around using the PHP method displayed in the API Docs, but beyond setting variables and working with WordPress me and PHP have never gotten on. I really appreciated any help you can give me on this.

Thanks

One option that is always available, is to use the form html that is provided from the form builder, and strip out all the included javascript. You can then intercept the form submit event, do whatever data processing you need to do, and then submit the data via ajax. That should solve CORS issues and the API key security issues.

Check out this post for some guidance - Two-step forms

That looks relatively simple, but how much of the form html needs to remain, as I need to restructure it to something like this:

Sign-up

If it were me, I would build the form using just the email field (minimum necessary field) using the form builder and then pull just the html from that and handle the submission via event.preventDefault() and AJAX.

I would keep all of the form HTML it is there to help prevent against bots etc.

Of course you could also use a form-builder plugin like Gravity Forms or Contact Forms 7 etc if you are on WordPress. I am not familiar with the details of how those work though.

I’ll have a wrestle with this tomorrow and see how successful I am. Thanks for all your helpful suggestions! I think in the end I’d rather try and get the PHP method working, as it is the most flexible and secure (I think).

Thanks

Hi,

Sorry to revive this old thread but I think I’ve almost got this working, but not quite. I’m using the ActiveCampaign PHP function library and basing this on the examples found here: https://github.com/ActiveCampaign/activecampaign-api-php/blob/master/examples.php.

At this point it is only returning the failed response, but not sure if this is a problem with my javascript or the PHP.

Here’s my current code:

HTML FORM

<form method="post" action="/wp-content/themes/tmcc/ActiveCampaign-mailer.php" class="tmcc-component-form">
    <div class="row">
        <div class="col-xs-6">
            <input id="name" name="name" class="tmcc-component-form__input" type="text" placeholder="Full Name*">
        </div>
        <div class="col-xs-6">
            <input id="organization" name="organization" class="tmcc-component-form__input" type="text" placeholder="Organisation">
        </div>
    </div>
    <div class="row">
        <div class="col-xs-6">
            <input id="email" name="email" class="tmcc-component-form__input" type="text" placeholder="Email Address*">
        </div>
        <div class="col-xs-6">
            <input id="telephone" name="telephone" class="tmcc-component-form__input" type="text" placeholder="Telephone">
        </div>
    </div>
    <div class="row tmcc-component-form__form-group">
        <div class="col-xs-12">
            <textarea id="message" name="message" class="tmcc-component-form__input" placeholder="How can we help?*"></textarea>
        </div>
    </div>
    <button class="tmcc-component-form__submit-button">Submit</button>
</form>

JAVASCRIPT/JQUERY

var form = 'form.tmcc-component-form';
$(form).submit(function(event) {
    event.preventDefault();
    var formData = $(form).serialize();
    $.ajax({
        type: 'POST',
        url: $(form).attr('action'),
        data: formData,
        success: function(data) {
            $(form).html("<p><strong>Thankyou for contacting us. We'll be in touch as soon as we can.</strong></p>");
        },
        error: function(data, status, error) {
            console.log(data);
            console.log(status);
            console.log(error);
        }
    })
});

PHP FORM SUBMISSION (API URL and KEY taken out for privacy, but are used properly in my local dev)

<?php

    require_once("./ActiveCampaign_API/ActiveCampaign.class.php");
  	$ac = new ActiveCampaign("API URL", "API KEY");

    // Data to submit
    $contact = array(
      "name"          => $_POST['name'],
      "organization"  => $_POST['organization'],
      "email"         => $_POST['email'],
      "telephone"     => $_POST['telephone'],
      "message"       => $_POST['message'],
      "p[7]"          => 7,
      "status[7]"     => 1
    );

    // Submit Data
    $contact_sync = $ac->api("contact/sync", $contact);

    // request success or failure response
    if (!(int)$contact_sync->success) {
      http_response_code(500);
    }

?>

Would appreciate any further assistance on this.

Thanks