Code snippet demonstrating how to pass JavaScript variables to AMPscript using AJAX!
Approach 1
======================================
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Passing JavaScript Variables to AMPscript with AJAX</title>
<script src="https://lnkd.in/g93GJP9a"></script>
</head>
<body>
<button id="sendData">Send Data</button>
<script>
$(document).ready(function(){
$('
#sendData').click(function(){
var jsVariable = "Your JavaScript Value";
$.ajax({
type: "POST",
url: "ampscript_processor_page.html",
data: { jsVariable: jsVariable },
success: function(response){
console.log("Data sent successfully.");
},
error: function(xhr, status, error){
console.error("Error:", error);
}
});
});
});
</script>
</body>
</html>
Approach 2
======================================
<script runat="server">
Platform.Load("Core", "1");
// Set your SSJS variable
var ssjsVariable = "Hello from SSJS!";
</script>
<!-- Output the SSJS variable into a hidden HTML element -->
<div id="ssjsVar" style="display:none;">
<script runat="server">
Platform.Load("Core", "1");Write(ssjsVariable);
</script>
</div>
<script>
// Read the value from the hidden div
var jsVariable = document.getElementById("ssjsVar").innerText;
// Output the JavaScript variable to verify
console.log(jsVariable); // This will output: Hello from SSJS!
</script>