Table of Contents
Dynamically populating custom checkout field options
While Foxy provides the ability to define custom checkout fields to allow you to capture any details you need from the customer on the checkout - this requires that the options available are hard-coded on the page. Sometimes it may be easier to be able to populate the options for the customer to select dynamically from your own website.
To allow for that, you will need to add a little javascript to your checkout to perform the request dynamically, and also set up an endpoint on your website, which is secured with an SSL certificate, that can respond to the request.
Set up your endpoint
This is an example in PHP - but the same process can be applied in other languages too. The key is that JSON is returned, and headers are present giving authority for your Foxy store checkout to communicate with your endpoint:
<?php header('Content-Type:application/json;charset=utf-8'); header('X-Content-Type-Options: nosniff'); header('Access-Control-Allow-Origin: https://my-store.foxycart.com'); $resp = [ "options" => [ "Option 1", "Option 2", "Option 3" ] ]; echo json_encode($resp);
Note that you'll need to update the my-store.foxycart.com
above to be your own store's subdomain, and also update the $resp
object to return the results you're after. In practice, this would probably be from some sort of database on your side, or you would refactor this code into your own system.
Add custom javascript to the checkout
To perform the dynamic request to your server, you'll need to add a little bit of javascript to the page. You'll add this on your stores “configuration” page in the administration, enable the option labelled “Add custom header and footer code to your templates”, and paste the following into the “footer” textarea:
{% if context == "checkout" %} <script> $(function() { $.get("https://www.your-website.com/options.php", function(data) { FC.json.custom_options = data.options; FC.checkout.renderAdditionalFields(); }); }); </script> {% endif %}
You'll need to update the URL above to point to wherever your script is located from the first step.
Update custom checkout fields
Finally, also on the configuration in the admin, enable the “Add custom form fields to your checkout” option present. Here you'll add in any custom fields you want to provide. As a quick example of utilising the example response above in a select object, it would look like this:
{% if custom_options is defined %} <select name="size"> {% for option in custom_options %} <option value="{{ option }}" {% if size == option %}selected{% endif %}>{{ option }}</option> {% endfor %} </select> {% endif %}