In search of a method to transfer an array of objects from one embedded script to another

In this initial script, an object array called "order_items" is being constructed. The goal is to transfer this array to a second script for the purpose of iterating through its values and generating a pixel to be displayed on the screen. However, there seems to be difficulty in passing 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 №1

Here is my approach to solving 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 opted for a json object because I needed key-value pairs in my array construction. Once I realized this, the variable scope was no longer an issue.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can you suggest a solution for fixing this error in Angular Js?

I recently started learning Angular JS and encountered some issues while trying to implement routing. Click here for the error message <!DOCTYPE html> Main <a href="#!london">City 1</a> <a href="#!paris">City 2& ...

Customizing object components in Three.js using GLTF format

I am currently working on a project that involves showcasing 3D renders of iron doors using gltf models in three.js. The final result should resemble the image found here: iron door example. I am facing a challenge where I need to selectively change the ...

Unable to add content to jQuery wrap

Why is it that you cannot append an element to the one used for wrapping another - as shown in the example below? var $test = $('.test'), $test1 = $('.test1'), $move = $('.move'), $testWrapper = $('<div ...

Attempting to understand how to retrieve specific items from my MongoDB Database that are associated with a particular user based on their ID

I've been attempting to retrieve specific items (Portfolio pics) that have been submitted by a user from my Mongo Database. However, when I checked the extracted items using Console logs, it seems to display all portfolio pieces for every user instead ...

Framer Motion does not support animations for exiting elements

Why is it that when I specify the exit property of framer motion to my HTML elements, they fail to animate upon being removed from the DOM? Here's an example of what my code looks like: <motion.div initial={{opacity: 0, y: -500}} animate={ ...

Change an array into a Mailchimp file with tab-delimited formatting

Looking to convert a JSON array into tab-delimited format for easy uploading to Mailchimp as a .txt file. Here's the desired result: "Date","Pupil","Grade" "25 May","Bloggs, Fred","C" "25 May","Doe, Jane","B" "15 July","Bloggs, Fred","A" ...

What is the method for customizing the color of a placeholder text in a specific text field

Is there a way to style placeholder text in different colors for each text field? According to the Mozilla documentation, the code snippet provided will change the color of the entire input tag. If you'd like to learn more, follow this link: https:/ ...

The most effective method for incorporating a header and footer into an HTML page utilizing a variety of client-side frameworks

Looking for a solution for my HTML project where I want to incorporate a header and footer to minimize rework. Any suggestions on a good approach? I have experimented with AngularJS using ng-include, and here is the code snippet: var app = angular.module ...

Safari is capable of rendering Jquery, whereas Chrome seems to have trouble

The code I am using renders perfectly in Safari but not in Chrome. Despite checking the console in Chrome, no errors are showing up. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script src="ht ...

Deleting all PHP array keys

Although it may sound simple, I'm struggling to figure out a solution to this problem. Let's say we have an array containing some of my favorite fruits: $array = array("Banana", "Rasberry", "Blackberry"); I want to completely clear this array ...

ReactJS: A single digit input may result in the display of numerous '0's

My goal is to have a small box that only allows one digit, but it seems to work fine until I try to input multiple '0's. Then the box displays multiple 0000 persistently. https://i.sstatic.net/Ouot4.png https://i.sstatic.net/MMKjm.png H ...

Transmitting data to a PHP script via AJAX and receiving a delayed response is not ideal for my needs

I am currently working on a contact page and have set it up to send a response if an invalid email is entered. However, the current code sends back an error message if a field is missing or left blank before clicking send. You can view the page at I still ...

I'm encountering difficulties retrieving the accurate information for my post submission form

Currently, I am in the process of implementing a comment function to enable product reviews. The backend functionality is working correctly as I have tested it using Postman. However, when attempting to post comments through the form on EJS, it fails due t ...

Filtering server-side components in Next.js to create a customized list

Having been accustomed to the previous architecture of Next.js, I embarked on a new project where I am exploring the use of server and client components in the latest architecture. Specifically, I have a page dedicated to displaying race results in a tabl ...

The 'load()' event method in jQuery does not function properly within the 'ready()' event method on mobile browsers

After testing on Firefox mobile and Chrome mobile browsers, I found that my code works perfectly on computer browsers. Below is the code I have inside the ready() and load() event methods: $(document).ready(function(){ $(window).on('load hashchan ...

Combining AngularJS objects from dual HTTP requests

My goal is to combine two HTTP.get requests into one $scope in order to display the data in the same ng-repeat table. I am utilizing chained promises in my AngularJS application as shown below: AngularJS: function getContainer() { $http.get(" ...

Locate items within a nested array of objects

I need to extract a specific object from a JSON array with nested objects by using the key name. I've attempted various methods but haven't found a generic solution yet. let data = {"role":"http://www.icai.org/xbrl/taxonomy/role/in ...

Steps to append a property to an already existing object within an array

Consider the following example of an original array [ {name:xyz,id:123 }, {name:abc,id:232}, ] Now, we have another array as shown below [ {value:'anything'}, {value:'anything12312'} ] The desired output, combining elements from b ...

After checking the checkbox to add a class, I then need to remove that class without having to interact with the entire document

When I click on a checkbox, an animation is added to a div. However, I am struggling to remove this animation unless I click elsewhere on the document. The goal is for the checkbox to both add and remove the class. JS $('#inOrder').click(functi ...

Tips for preventing a promise from being executed more than once within an observable while being subscribed to a BehaviorSubject

I've defined a class called Store with the following structure: import { BehaviorSubject, Observable } from 'rxjs' export abstract class Store<T> { private state: BehaviorSubject<T> = new BehaviorSubject((undefined as unknown ...