tony tony - 5 months ago 8
Javascript Question

Looking for a way to pass an object array from one embedded script to another

The object array is built here in the first script..."order_items". I want to pass it into the second script so I can loop through values and build a pixel to render to my screen. I'm stuck trying to pass the array.

@for (int i = 0; i < OrderItemsReceived.Count; i++)
{
<script type="text/javascript" id="pepper" data-search="order_items">
var order_items = [{
'name':ProductName',
'sku': SKU',
'price': UnitPrice.ToString().Replace(",", "")',
'quantity': Quantity.ToString()'
}]
</script>
}

<script type="text/javascript">
var script_tag = document.getElementById('pepper');
var order_items = script_tag.getAttribute("data-search");

var order_id = @Model.OrderId;
var pixel_html = '';
var integration = 'DYNAMIC';
var program_id = 7302;


if (order_id && order_items) {
jQuery.each( order_items, function (i, order_item) {
pixel_html += '&' + 'ITEM_ID' + i + '=' + order_item.sku +
'&' + 'ITEM_PRICE' + i + '=' + order_item.price +
'&' + 'QUANTITY' + i + '=' + order_item.quantity;
});

if (pixel_html) {
pixel_html = '<iframe src="https://t.pikespeak.com/track?' +
'INT=' + integration +
'&' + 'PROGRAM_ID' + '=' + program_id +
'&' + 'ORDER_ID' + '=' + order_id +
pixel_html +
'" width="1" height="1" frameborder="0"></iframe>';
}
}
$('body').append(pixel_html);
</script>

Answer

this is how I solved the problem.

<<script type="text/javascript" id="pepper" data-search="order_items">
    alert("hello");
    var order_items = @Html.Raw(Json.Encode(Model.OrderItemsReceived.OrderItemsReceived));
    var order = [];
    var order_listItems = [];
    for (var i = 0; i < order_items.length; i++){
        var orderList = order_items[i];
        order = [{
            'sku': orderList.SKU,
            'price': orderList.UnitPrice,
            'quantity': orderList.Quantity
        }]
        order_listItems.push(order);
    }

>

I chose to go ahead with a json object because my array would be constructed of key, value pairs. Once I realized that required the scope of the variable was no longer a big issue.