Jump to content

Would like to include the IP address of the person filling out a form

Recommended Posts

Hello,

I'm using the contact form from squarespace. Fairly basic nothing special. I would like to be able to include the IP address of the person filling out the form though. I thought I could do this with a hidden field, but I don't see any way of populating the hidden with anything other then url parameters, which wouldn't be helpful here. 

Is there someway to include the IP address of the person filling out the contact form?

Link to comment

The following will require a business plan or above.

Add the following to Settings > Advanced > Code Injection > HEADER.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js" type="text/javascript"></script>

Add the following to Page Settings > Advanced > PAGE HEADER CODE INJECTION.

<script>

  $( ( ) => {
  
    /*
    
      based on code from
      < https://www.geeksforgeeks.org/how-to-get-client-ip-address-using-javascript/ >.
      
      Uses ipify API < https://www.ipify.org/ >.
      
      */
      
    /*
    
      Add "https://api.ipify.org?format=json" statement this will communicate with
      the ipify servers in order to retrieve the IP address $.getJSON will load
      JSON-encoded data from the server using a GET HTTP request
      
      */ 
      
    $.getJSON ( 'https://api.ipify.org?format=json', function ( data ) {
    
      // setting hidden ip address field with name SQF_IP_ADDRESS
      
      $( '[name="SQF_IP_ADDRESS"]' ).val ( data.ip );
      
      } );
      
    } );
    
  </script>

Add a hidden form field to your form named IP Address.

185423979_ScreenShot2020-09-30at6_53_37PM.png.1ee301805d6573c950876008e88c47c4.png

That should do the trick. I tested it out here on a v7.0 site but I think it should work on v7.1 as well.

Basically what this is doing is using Javascript/jQuery to go out and query the ipify api for the ip address of the client. Then stuff that number in the IP Address field.

Obviously you will need to test on your site.

Let us know how it goes.

Edited by creedon

Find my contributions useful? Please like, upvote, mark my answer as the best ( solution ), and see my profile. Thanks for your support! I am a Squarespace ( and other technological things ) consultant open for new projects.

Link to comment
  • 1 year later...
  • 1 month later...
On 10/1/2020 at 4:03 AM, creedon said:

The following will require a business plan or above.

Add the following to Settings > Advanced > Code Injection > HEADER.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js" type="text/javascript"></script>

Add the following to Page Settings > Advanced > PAGE HEADER CODE INJECTION.

<script>

  $( ( ) => {
  
    /*
    
      based on code from
      < https://www.geeksforgeeks.org/how-to-get-client-ip-address-using-javascript/ >.
      
      Uses ipify API < https://www.ipify.org/ >.
      
      */
      
    /*
    
      Add "https://api.ipify.org?format=json" statement this will communicate with
      the ipify servers in order to retrieve the IP address $.getJSON will load
      JSON-encoded data from the server using a GET HTTP request
      
      */ 
      
    $.getJSON ( 'https://api.ipify.org?format=json', function ( data ) {
    
      // setting hidden ip address field with name SQF_IP_ADDRESS
      
      $( '[name="SQF_IP_ADDRESS"]' ).val ( data.ip );
      
      } );
      
    } );
    
  </script>

Add a hidden form field to your form named IP Address.

185423979_ScreenShot2020-09-30at6_53_37PM.png.1ee301805d6573c950876008e88c47c4.png

That should do the trick. I tested it out here on a v7.0 site but I think it should work on v7.1 as well.

Basically what this is doing is using Javascript/jQuery to go out and query the ipify api for the ip address of the client. Then stuff that number in the IP Address field.

Obviously you will need to test on your site.

Let us know how it goes.

Hey @creedon! Your solution works like charm, I implemented it on my website. And this hidden IP field lands nicely also in Mailchimp as a separate field.

Do you know a way to automatically extract Country+City from this IP address? I'd love to add them as separate hidden fields as well.

Thanks!

Tom

 

Edited by TomWis
Link to comment

@TomWis

The way to do it is to use a geolocation service instead of an ip address service. Geolocation is basically doing the same thing as the ip address service but adds location information.

Ipify has one but there are several companies that provide this service.

Find my contributions useful? Please like, upvote, mark my answer as the best ( solution ), and see my profile. Thanks for your support! I am a Squarespace ( and other technological things ) consultant open for new projects.

Link to comment

I'd add that IP addresses are considered personally identifiable information (PII) by authorities in many territories. Regardless of your own opinions on this, if you considering logging IP addresses you may want to consider the legal implications and include details in your privacy policy.

I'm not a lawyer and this isn't legal advice, just a friendly discussion. 🙂

About me: I've been a SQSP User for 18 yrs. I was invited to join the Circle when it launched in 2016. I have been a Circle Leader since 2017. I don't work for Squarespace. I value honesty, transparency, diversity and good design ♥.
Work: I founded and run SF.DIGITAL, building Squarespace Extensions to supercharge your commerce website. 
Content: Views and opinions are my own. Links in my posts may refer to SF.DIGITAL products or may be affiliate links.
Forum advice is free. You can thank me by clicking one of the feedback emojis below. Coffee is optional.

Link to comment
18 hours ago, creedon said:

@TomWis

The way to do it is to use a geolocation service instead of an ip address service. Geolocation is basically doing the same thing as the ip address service but adds location information.

Ipify has one but there are several companies that provide this service.

Thanks @creedon. You don't plan to post similar step-by-step with code example, do you? 🙂Querrying for country+city seems more complex. Querrying for IP address was super-simple, because URL https://api.ipify.org simply returned ID address...

Link to comment
7 hours ago, TomWis said:

Querrying for country+city seems more complex.

I should have expounded more on using geolocation. The gross overview of using geo-location is as I mentioned you point to a different API and get different information back. But here's where I should have gone further.

Services that provide detailed geolocation generally don't give it away for free. It costs money to maintain those servers. They may have a free or low-cost tier for say 500 - 1000 hits. But here's the rub. They need a way to identify who you are as a user of their service so they can track and either cut you off or charge for your usage.

Let's look at ipify's implementation. They use a subscriber model and you generate a private API key to access their service. The key is meant to be used on a server where you have access to the back-end so you can load that key there and then use that server to do your geolocation bidding. I suspect most similar services do it the same way.

The issue for an SS site is we don't have access to the server back-end to do the above step. If you were to use the key in public facing code like I created above then anyone could use your key and you would be paying for their use. You don't want that!

Are there some ways you might be able to get what you want with an SS site? Possibly. But a solution wouldn't be a few lines of code like with the IP address above.

Also beware of any free geolocation services that don't require some kind of method to identify you. How can they have a quality data set, provide the servers, human power, and etc., for free?

Find my contributions useful? Please like, upvote, mark my answer as the best ( solution ), and see my profile. Thanks for your support! I am a Squarespace ( and other technological things ) consultant open for new projects.

Link to comment
  • 1 year later...

Dear @creedon, I tried using your tips (adding the 2 scripts) to get the user IP and load it into a hidden form field. But it doesn't seem to work. I tried it first on another website in preparation (and therefore TRIAL-mode), so I tried it on a hidden page on my BUSINESS-plan website too. 

Could you have a look at what is going wrong? I can't figure it out.

Thnx a lot in advance!
Stefan

https://www.zzesto.com/ip-form-test

Screenshot 2023-04-23 at 15.31.11.png

Screenshot 2023-04-23 at 15.31.22.png

Link to comment
6 hours ago, ZZESTO said:

Could you have a look at what is going wrong? I can't figure it out.

Neither can I. It all looks good from here.

ScreenShot2023-04-23at1_51_10PM.thumb.png.4cc3e8b5591d565cac7cda3668f31b7d.png

I also ran a test locally and all went as expected.

ScreenShot2023-04-23at1_52_56PM.thumb.png.c76c6feacdbcd1c721dd6bcf99b8b983.png

Let us know what you find out, when you do figure it out.

Find my contributions useful? Please like, upvote, mark my answer as the best ( solution ), and see my profile. Thanks for your support! I am a Squarespace ( and other technological things ) consultant open for new projects.

Link to comment

Hi Tom,

After looking at your answer.... I wondered what possibly could go wrong. And suddenly, it hit me, I was doing the testing from my Brave browser, that always has a Brave Shield up! Testing it from Safari and/or with the Shield de-activated resulted in a sweet success! Thanks for checking!

Question: we're working on a local neighbourhood initiative to collect complaints of local people that experience heavy vibrations from the passing trains. We've got some 300 people signing up for a newsletter. I'd like to (where possible) link their address to their IP, so we know approximately where there complaints are originating from without them having to identify on every 'complaint' (which can happen multiple times per night).

I'm looking for some sort of logic like the following:

  1. send out an automated email to all people who signed up
  2. provide a 'complete your profile' link to a form on the website
  3. pre-populate the form with the email address and name (from url)
  4. fetch IP (as per above code) 
  5. and send all profile data + IP address back to a Google Sheet.

Would this be possible with Squarespace (form, pre-populating from a url ?email=blablabla&name=blebleble etc) and would this be possible with the Squarespace mailer (easy integration, but limited functionality in creating custom links) or do I need Mailchimp or Flodesk for that to work?

Appreciate your thoughts!
Stefan

 

Link to comment
10 hours ago, ZZESTO said:

I'd like to (where possible) link their address to their IP, so we know approximately where there complaints are originating from without them having to identify on every 'complaint'

This is difficult because of several issues.

IP addresses are often dynamic. So someone making a complaint at 1 AM will have one IP address may have another IP address when they make a complaint at 2:30 AM. At best you can only make a general guess about where a dynamic address is to within something like a ten block area.

You then have the issue of VPNs. You can be sitting in your home in the Pacific Northwest of the USA but your IP can appear as if you are in London.

You can try geolocation but these too are also subject to these basic issues of how IP addresses work.

If I were approaching this issue I think I'd be looking at using form auto-fill. Many browsers have auto-fill. If you went this route it would be passive on your part, well except for perhaps instructing users on it's use in their browsers. You could probably write some code that would do some kind of auto-fill that wouldn't depend on the browser/user behaviour.

Quote

Would this be possible with Squarespace (form, pre-populating from a url ?

If you mean would it be possible to hit a URL on an SS site that has a form on its page and pick up and populate fields on the form from parameters from the URL, then yes. This would take custom code.

Find my contributions useful? Please like, upvote, mark my answer as the best ( solution ), and see my profile. Thanks for your support! I am a Squarespace ( and other technological things ) consultant open for new projects.

Link to comment
  • 3 weeks later...
2 hours ago, Elletra said:

I followed your instructions and it didn't work. Can you possibly see what could be the issue?

The issue is that SS is currently updating the form blocks and a lot of code written before now, is broken. In addition the current implementation is difficult to work with so reimplementing reworked custom code is slow and difficult. I have no timeline for a new version of this custom code.

I can only suggest that you follow this thread and watch for any potential updates.

Find my contributions useful? Please like, upvote, mark my answer as the best ( solution ), and see my profile. Thanks for your support! I am a Squarespace ( and other technological things ) consultant open for new projects.

Link to comment

Yeah unfortunately at the moment the Squarespace form, wipe out any value you inject in the hidden field as soon as you type something in the form itself.

Not sure if a bug or a "by design" decision to force using the hidden field only with value coming from the query string in the URL (as for their official doc https://support.squarespace.com/hc/en-us/articles/206543997-Tracking-form-block-referral-sources )

 

Anyway if and ever this will work again, here's an example of code that doesn't use jQuery and extract basic info from the geolocation API:

<script>
  document.addEventListener('DOMContentLoaded', function() {
    fetch('https://ipapi.co/json/')
        .then(function (response) {
            response.json().then(jsonData => {
                if (document.getElementsByName("SQF_YourHiddenFieldName").length != 0) {
                    //set ip address for form submission
                    document.getElementsByName("SQF_YourHiddenFieldName")[0].value = jsonData.ip + " | " + jsonData.city +
                        " | " + jsonData.country_name + " | " + jsonData.org;
                }
            });
        })
    }, false);
</script>

You can put that in the Footer or maybe just in the "contact us" page.

If you are on Squarespace 7 and not 7.1 you might need to wrap your code in window.Squarespace.onInitialize(Y, function () {...});

instead of 

document.addEventListener('DOMContentLoaded', function() {...}, false);

 

Hope it helps.

Link to comment
  • 1 month later...
On 5/13/2023 at 3:12 PM, Accelerate said:

Yeah unfortunately at the moment the Squarespace form, wipe out any value you inject in the hidden field as soon as you type something in the form itself.

Not sure if a bug or a "by design" decision to force using the hidden field only with value coming from the query string in the URL (as for their official doc https://support.squarespace.com/hc/en-us/articles/206543997-Tracking-form-block-referral-sources )

 

Anyway if and ever this will work again, here's an example of code that doesn't use jQuery and extract basic info from the geolocation API:

<script>
  document.addEventListener('DOMContentLoaded', function() {
    fetch('https://ipapi.co/json/')
        .then(function (response) {
            response.json().then(jsonData => {
                if (document.getElementsByName("SQF_YourHiddenFieldName").length != 0) {
                    //set ip address for form submission
                    document.getElementsByName("SQF_YourHiddenFieldName")[0].value = jsonData.ip + " | " + jsonData.city +
                        " | " + jsonData.country_name + " | " + jsonData.org;
                }
            });
        })
    }, false);
</script>

You can put that in the Footer or maybe just in the "contact us" page.

If you are on Squarespace 7 and not 7.1 you might need to wrap your code in window.Squarespace.onInitialize(Y, function () {...});

instead of 

document.addEventListener('DOMContentLoaded', function() {...}, false);

 

Hope it helps.

You can try my solution below which can help to modify the hidden field value on demand,

 Call the geoIP callback with my solution can help persist the value and send it along with the submission

BeyondSpace - Squarespace Website Developer

🖼️ Lightbox Studio (Enable Pinch/Zoom on lightbox)
🗓️ Delivery Date Picker (Squarespace Date format)
💫 Animated Buttons (Referral URL)
🥳 Sparkplugin Customisations Browsers (Browse +100 Spark plugin customisations)
🥳 Elfsight Template Browsers (Browse +1000 Elfsight widget Templates)

If you find my answer useful, let's leave a like or upvote so others with the same issue can find their solution. Thank you!

 

Link to comment

I forked @creedon answer to solve the latest issue with localized form block

Please make sure the consistent of the hidden field name in the form block and in the custom code injection

nit: you can change the field name if you want, just remember to update the variable

<script>
/*
* @beyondspace: Append visitor IP to sqs form submission
* Squarespace Forum: 14-June-2023
*/
window.addEventListener("load", (event) => {
    const hiddenFieldKey = 'SQF_IP_ADDRESS';
    const formBlocks = document.querySelectorAll('.sqs-block-form');
  
    formBlocks.forEach(async (block) => {
        const contextElement = block.querySelector("[id*=form-context-]");
        const context = JSON.parse(contextElement.innerHTML);
        
        const hiddenField = context.formFields.filter((field) => {
            return field.key === hiddenFieldKey
        })[0];
        if (hiddenField) {
            try {
              const response = await fetch('https://api.ipify.org?format=json');
              if (!response.ok) {
                throw new Error(`HTTP error! Status: ${response.status}`);
              }
              const data = await response.json();
              const ipAddress = data.ip;

              const hiddenFieldIndex = context.formFields.indexOf(hiddenField)
              const latestContext = JSON.parse(contextElement.innerHTML);
              latestContext.formFields[hiddenFieldIndex].value = ipAddress;
              contextElement.innerHTML = JSON.stringify(latestContext);

              Squarespace.initializeFormBlocks(Y, Y)
            } catch (error) {
              console.error('Error:', error.message);
            }
        }
    })
});
</script>

 

PS: this is relevant with the submission page hidden field, so in case you have similar inquiry

 

image.png

BeyondSpace - Squarespace Website Developer

🖼️ Lightbox Studio (Enable Pinch/Zoom on lightbox)
🗓️ Delivery Date Picker (Squarespace Date format)
💫 Animated Buttons (Referral URL)
🥳 Sparkplugin Customisations Browsers (Browse +100 Spark plugin customisations)
🥳 Elfsight Template Browsers (Browse +1000 Elfsight widget Templates)

If you find my answer useful, let's leave a like or upvote so others with the same issue can find their solution. Thank you!

 

Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

×
×
  • Create New...

Squarespace Webinars

Free online sessions where you’ll learn the basics and refine your Squarespace skills.

Hire a Designer

Stand out online with the help of an experienced designer or developer.