Techdocs
Search…
Dynamically sending the cart content
If you're on a site where the cart-content are not accessible when the page is rendered, you might need to fetch the cart content over AJAX/CORS and send that information to Nosto.
The example below illustrates how to fetch the fresh cart-content over CORS, leverage that to render the cart-tagging and then use the API to sent that information to Nosto.
This example uses advances constructs, leverages CORS, browser modules and may not have compatibility on older browsers.
1
function lineItemToHtml(item) {
2
return `
3
<div class="line_item">
4
<span class="product_id">${item.product_id}</span>
5
<span class="sku_id">${item.sku_id}</span>
6
<span class="quantity">${item.quantity}</span>
7
<span class="name">${item.name}</span>
8
<span class="unit_price">${item.unit_price}</span>
9
<span class="price_currency_code">${item.currency}</span>
10
</div>
11
`
12
}
13
14
function cartToHtml(cart) {
15
return `
16
<div class="nosto_cart" style="display:none">
17
${cart.items.map((item) => lineItemToHtml(item))}
18
</div>
19
`
20
}
21
22
/**
23
* This example fetches cart content from an external endpoint, uses
24
* that information to render the cart-tagging and then reloads the
25
* recommendations if needed.
26
*
27
* This snippet is written under the assumption that the data returned
28
* by the endpoint resembles the following
29
* {
30
* items: [
31
* product_id: "product_id",
32
* sku_id: "sku_id",
33
* quantity: "quantity",
34
* name: "name",
35
* unit_price: "unit_price",
36
* currency: "currency"
37
* ]
38
* }
39
*/
40
export default function() {
41
nostojs(api => {
42
fetch("https://www.example.com/cart")
43
.then(response => {
44
const tagging = cartToHtml(response.json())
45
46
document.querySelectorAll('.nosto_cart')
47
.forEach(element => element.remove());
48
document.body.append(tagging)
49
50
api.resendCartTagging();
51
})
52
})
53
}
Copied!
Last modified 9mo ago
Copy link