I need to track purchase event for Google Analytics Ecommerce using gtag.js
. For doing that I need to put these sample js code on target page:
gtag('event', 'purchase', {
'transaction_id': '1234',
'value': 19.90,
'items': [
{
'id': '12345',
'name': 'AwesomeT-Shirt',
},
]
});
The problem is that I don't have a target page. I have only a page with AJAX form that could return required values from PHP through created JSON object with array of these values:
//php
$ecomm = array(
'transaction_id'=>$orderID,
'value'=>$order_amount,
'id'=>$productID,
'name'=>$product_name
);
echo json_encode($ecomm);
It is working fine. Console in Chrome shows all of required values:
$.ajax({
type: "POST",
url: "...",
data: query,
dataType: 'json',
success: function(data){
console.log(data.transaction_id);
console.log(data.value);
console.log(data.id);
console.log(data.name);
}
});
How to modify last js code for replace these:
console.log(data.transaction_id);
console.log(data.value);
console.log(data.id);
console.log(data.name);
to these with proper values:
gtag('event', 'purchase', {
'transaction_id': '2074',
'value': 19.90,
'items': [
{
'id': '295',
'name': 'AwesomeT-Shirt',
},
]
});
Thanks.