AJAX - SpamBlock Pixel and Forms Integration
Learn how to integrate SpamBlock Pixel and Forms solution with AJAX form submissions using Fetch, Axios, jQuery, or XHR. Complete examples with error handling and best practices.
Overview
This guide shows how to integrate both the SpamBlock Pixel and SpamBlock Forms solution with AJAX form submissions using various HTTP client libraries. The SpamBlock Pixel intercepts form submissions, scores them at the edge, and only fires the spamblock:allowed event for legitimate submissions. The examples below demonstrate submitting to SpamBlock Forms endpoints, our hosted form solution that works seamlessly with the Pixel.
Note: While the SpamBlock Pixel works with any backend endpoint, these examples specifically demonstrate using both the Pixel and SpamBlock Forms together. The SpamBlock Forms endpoint (
https://api.spamblock.io/f/{form_id}) provides a complete hosted form solution. Learn more about Forms or use your own backend endpoint with the Pixel.
Basic Examples
Choose the HTTP client that best fits your project:
Fetch API
Native browser API, no dependencies required. Best for modern projects.
<!-- Load SpamBlock Pixel -->
<script src="https://pixel.spamblock.io/latest.js" defer></script>
<form id="contact-form" action="#" method="POST">
<label for="name">Name</label>
<input id="name" name="name" type="text" required />
<label for="email">Email Address</label>
<input id="email" name="email" type="email" required />
<label for="message">Message</label>
<textarea id="message" name="message" required></textarea>
<button type="submit">Send</button>
</form>
<script>
// Wait for the page to load
window.addEventListener("DOMContentLoaded", function() {
const form = document.getElementById("contact-form");
// Listen for allowed submissions from SpamBlock
form.addEventListener("spamblock:allowed", async function(event) {
event.preventDefault();
const formData = new FormData(event.target);
try {
const response = await fetch("https://api.spamblock.io/f/{form_id}", {
method: "POST",
body: formData
});
if (response.ok) {
alert("Submission successful!");
form.reset();
} else {
alert("There was an error submitting the form.");
}
} catch (error) {
alert("Network error. Please try again.");
}
});
});
</script>
When to Use:
- You want zero external dependencies
- You're building for modern browsers
- You prefer native browser APIs
Axios
Popular HTTP client with advanced features like interceptors and automatic JSON transformation.
<!-- Load SpamBlock Pixel -->
<script src="https://pixel.spamblock.io/latest.js" defer></script>
<!-- Load Axios from CDN -->
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<form id="contact-form" action="#" method="POST">
<label for="name">Name</label>
<input id="name" name="name" type="text" required />
<label for="email">Email Address</label>
<input id="email" name="email" type="email" required />
<label for="message">Message</label>
<textarea id="message" name="message" required></textarea>
<button type="submit">Send</button>
</form>
<script>
// Wait for the page to load
window.addEventListener("DOMContentLoaded", function() {
const form = document.getElementById("contact-form");
// Listen for allowed submissions from SpamBlock
form.addEventListener("spamblock:allowed", async function(event) {
event.preventDefault();
const formData = new FormData(event.target);
try {
const response = await axios.post(
"https://api.spamblock.io/f/{form_id}",
formData,
{
headers: {
"Content-Type": "multipart/form-data",
},
}
);
if (response.status === 200) {
alert("Submission successful!");
form.reset();
} else {
alert("There was an error submitting the form.");
}
} catch (error) {
if (error.response) {
// Server responded with error status
console.error("Error:", error.response.status, error.response.data);
alert("There was an error submitting the form.");
} else if (error.request) {
// Request made but no response received
console.error("Network error:", error.request);
alert("Network error. Please try again.");
} else {
// Something else happened
console.error("Error:", error.message);
alert("An unexpected error occurred.");
}
}
});
});
</script>
When to Use:
- You're already using Axios in your project
- You need advanced HTTP client features (interceptors, request/response transformation)
- You want consistent error handling across your application
- You prefer Promise-based APIs over Fetch
jQuery
Simplified API with cross-browser compatibility. Great for legacy projects.
<!-- Load SpamBlock Pixel -->
<script src="https://pixel.spamblock.io/latest.js" defer></script>
<!-- Load jQuery from CDN -->
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<form id="contact-form" action="#" method="POST">
<label for="name">Name</label>
<input id="name" name="name" type="text" required />
<label for="email">Email Address</label>
<input id="email" name="email" type="email" required />
<label for="message">Message</label>
<textarea id="message" name="message" required></textarea>
<button type="submit">Send</button>
</form>
<script>
$(document).ready(function() {
// Listen for allowed submissions from SpamBlock
$("#contact-form").on("spamblock:allowed", function(event) {
event.preventDefault();
const formData = new FormData(this);
$.ajax({
url: "https://api.spamblock.io/f/{form_id}",
type: "POST",
data: formData,
processData: false,
contentType: false,
success: function(response) {
alert("Submission successful!");
$("#contact-form")[0].reset();
},
error: function(xhr, status, error) {
if (xhr.status === 0) {
alert("Network error. Please check your connection.");
} else {
alert("There was an error submitting the form.");
}
console.error("Error:", status, error);
},
});
});
});
</script>
When to Use:
- You're already using jQuery in your project
- You prefer jQuery's simplified API over native JavaScript
- You need cross-browser compatibility without polyfills
- You want to leverage jQuery's utility functions
Important Notes:
- When using FormData, set
processData: falseandcontentType: false - In the event handler,
thisrefers to the form element
XMLHttpRequest (XHR)
Native JavaScript API with fine-grained control. No dependencies required.
<!-- Load SpamBlock Pixel -->
<script src="https://pixel.spamblock.io/latest.js" defer></script>
<form id="contact-form" action="#" method="POST">
<label for="name">Name</label>
<input id="name" name="name" type="text" required />
<label for="email">Email Address</label>
<input id="email" name="email" type="email" required />
<label for="message">Message</label>
<textarea id="message" name="message" required></textarea>
<button type="submit">Send</button>
</form>
<script>
// Wait for the page to load
window.addEventListener("DOMContentLoaded", function() {
const form = document.getElementById("contact-form");
// Listen for allowed submissions from SpamBlock
form.addEventListener("spamblock:allowed", function(event) {
event.preventDefault();
const formData = new FormData(event.target);
const xhr = new XMLHttpRequest();
// Handle successful response
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 300) {
alert("Submission successful!");
form.reset();
} else {
alert("There was an error submitting the form.");
}
};
// Handle network errors
xhr.onerror = function() {
alert("Network error. Please try again.");
};
// Handle timeout
xhr.ontimeout = function() {
alert("Request timed out. Please try again.");
};
// Configure and send request
xhr.open("POST", "https://api.spamblock.io/f/{form_id}");
xhr.timeout = 10000; // 10 second timeout
xhr.send(formData);
});
});
</script>
When to Use:
- You want zero external dependencies
- You need fine-grained control over the HTTP request
- You're working in environments where Fetch API isn't available
- You prefer callback-based APIs
- You need to support older browsers
Important Notes:
- XHR doesn't throw on HTTP errors, check
xhr.statusmanually - Always implement
onerrorandontimeouthandlers - Set a reasonable timeout to prevent hanging requests
How It Works
The spam handling flow is consistent across all examples:
- User submits form
- SpamBlock Pixel intercepts submission
- Submission scored at the edge
- If spam: submission blocked,
spamblock:allowedevent not fired - If allowed:
spamblock:allowedevent fired - Your code handles the allowed submission
Common Mistakes
- Not waiting for pixel - Make sure the pixel script loads before form submission
- Ignoring events - Listen for
spamblock:allowedevent to know when submission is safe - Missing error handling - Always handle network errors and API failures
- Not preventing default - Always call
event.preventDefault()in the event handler - Incorrect FormData handling - When using FormData with jQuery, set
processData: falseandcontentType: false
Learn More
- Pixel Getting Started - Learn the basics of SpamBlock Pixel
- Forms Getting Started - Explore our hosted form solution