Steps to dynamically retrieve and incorporate external JavaScript using an Ajax request

Just getting started with Ajax and running into an issue. We have a cart page on our site where users can dynamically add, remove, and update item quantities using Ajax without refreshing the entire page. My problem is that I need to trigger some third-party external calls whenever a user updates their cart.

Below is the code snippet that makes the Ajax call to a JSP file containing parameters for the script evaluation. The JSP file also includes a third-party external script that needs to be triggered separately. Any help would be greatly appreciated:


var callExternalUpdate = function(secure) {
    var ajaxParams = "secure=" + secure;
    ajax('POST',
        '/abc/my-ajax.jsp',
        ajaxParams, 
        function(r) {
            eval(r.responseText);
        },
        function(r) {
            //alert(r.responseText);
        }
    );
}

Here's the content of my-ajax.jsp:

<script type="text/javascript" src="http://www.mywebsite.com/js/criteo_ld_0.5.4.js" async="true"></script>
<script type="text/javascript">var CRITEO_CONF = [[{ 
    pageType: 'basket', 
    'Product IDs': [123], 
    'Prices': [10], 
    'Quantities': [1] 
    }], [6507,'ppr','us.','110',[[7721658, 7721659]],{'Product IDs':['i',1], 'Prices':['p',1], 'Quantities':['q',1]}]]; 
    if (typeof (CRITEO) != "undefined") { CRITEO.Load(false); }
</script>

I know I'll need to exclude the script tag since I'm using eval in my JavaScript, but how do I trigger the external JavaScript?

Please assist. Thanks in advance!

Answer №1

Make sure to load the criteo_ld_0.5.4.js file on your page and ensure that the JSP page only returns the values of Java script expressions without any script tags.

var CRITEO_CONF = [[{ 
pageType: 'basket', 
'Product IDs': [123], 
'Prices': [10], 
'Quantities': [1] 
}], [6507,'ppr','us.','110',[[7721658, 7721659]],{'Product IDs':['i',1], 'Prices':['p',1], 'Quantities':['q',1]}]]; 
if (typeof (CRITEO) != "undefined") { CRITEO.Load(false); }

Answer №2

        Implementing Criteo retargeting with Magento CE or EE using New OneTag

        **Home Page - integration :**

        <script type="text/javascript" src="//static.criteo.net/js/ld/ld.js" async="true"></script> 

        <script type="text/javascript"> 
            window.criteo_q = window.criteo_q || []; 
            window.criteo_q.push( { event: "setAccount", account: **Your Account Number**}, 
                { event: "setCustomerId", id: "<?php if(Mage::getSingleton('customer/session')->isLoggedIn()) {$customerData = Mage::getSingleton('customer/session')->getCustomer();echo $customerData->getId();
             }?>"}, { event: "setSiteType", type: "d"}, { event: "viewHome"} ); 
        </script>


        **Listing Page Setup :**

        <script type="text/javascript" src="//static.criteo.net/js/ld/ld.js" async="true"></script> 

        <script type="text/javascript"> 
            window.criteo_q = window.criteo_q || [];
            window.criteo_q.push( 
            { event: "setAccount", account: **Your Account Number**}, 
            { event: "setCustomerId", id: "<?php if(Mage::getSingleton('customer/session')->isLoggedIn()) {$customerData = Mage::getSingleton('customer/session')->getCustomer();echo $customerData->getId();
             }?>"}, 
            { event: "setSiteType", type: "d"}, 
            { event: "viewList", item: [<?php 
            $cat_id = Mage::getModel('catalog/layer')->getCurrentCategory()->getId(); 
            $category = Mage::getModel('catalog/category')->load($cat_id); 
            $products = $category->getProductCollection()
            ->addCategoryFilter($category)
            ->addAttributeToSort('entity_id','desc')
            ->addAttributeToFilter('type_id','configurable')
            ->addAttributeToSelect('sku');
            $products->setPage(1, 3);
            $skus = '';
            foreach ( $products as $_product ): 
            $skus .= '"'.$_product->getSku().'",';
            endforeach;
            $skus = substr($skus,0,-1);
            print($skus);
            ?>], keywords: "<?php echo $this->htmlEscape($this->getCurrentCategory()->getName()) ?>" } ); </script>


        Product Page Embedding :

        <script type="text/javascript" src="//static.criteo.net/js/ld/ld.js" async="true"></script> 

        <script type="text/javascript"> 
            window.criteo_q = window.criteo_q || []; 
            window.criteo_q.push( 
                { event: "setAccount", account: **Your Account Number**}, 
                { event: "setCustomerId", id: "<?php if(Mage::getSingleton('customer/session')->isLoggedIn()) {$customerData = Mage::getSingleton('customer/session')->getCustomer();echo $customerData->getId();
                 }?>"}, 
                { event: "setSiteType", type: "d"}, 
                { event: "viewItem", item: "<?php echo $_product->getSKU() ?>" }
             ); 
        </script>


       **Order Basket Implementation Code :**

        <script type="text/javascript" src="//static.criteo.net/js/ld/ld.js" async="true"></script> 
        <script type="text/javascript"> 
            window.criteo_q = window.criteo_q || []; 
            window.criteo_q.push( 
                {event: "setAccount", account: **Your Account Number**}, 
                {event: "setCustomerId", id: "<?php if(Mage::getSingleton('customer/session')->isLoggedIn()) {$customerData = Mage::getSingleton('customer/session')->getCustomer();echo $customerData->getId();
         }?>"}, 
                {event: "setSiteType", type: "d"}, 
                {event: "viewBasket", item: [ 
                <?php   
                    $count = 0;
                    $cartLines = Mage::helper('checkout/cart')->getCart()->getItems();
                    foreach ($cartLines as $cartLine):
                    $count++;
                    $product = Mage::getModel('catalog/product')->load($cartLine->getProductId());
                    if ($product->getSpecialPrice()) {
                        $price = $product->getSpecialPrice();
                    } else {
                        $price = $product->getPrice();
                    }

                    /* Get Configurable Sku from Simple product SKU/ID.
                     * If there is no configurable/simple product set up, then just use the standard Sku display
                     * */
                    $parentId = Mage::getResourceSingleton('catalog/product_type_configurable')->getParentIdsByChild($cartLine->getProductId());
                    $configurableProductSku = Mage::getModel('catalog/product')->load($parentId)->getSku();
                    if ($configurableProductSku)  {
                        $IdString .= $configurableProductSku;
                    }
                    else  {
                        $idString .= $cartLine->getSku();
                    }
            //      $IdString .= $cartLine->getSku();
                    $PriceString .= $price;
                    $quantityString .= (int) $cartLine->getQty();   
                ?>  
                <?php if( $count == count($cartLines)): ?>

                    { id: "<?php echo $IdString; ?>", price: <?php echo number_format($PriceString,2,'.',' ')?>, quantity: <?php echo $quantityString ?> } 
                    <?php else: ?>
                    { id: "<?php echo $IdString; ?>", price: <?php echo number_format($PriceString,2,'.',' ')?>, quantity: <?php echo $quantityString ?> }, 
                    <?php endif; ?>

                <?php 
                    $IdString = '';
                    $PriceString = '';
                    $quantityString ='';
                    endforeach;
                ?>
                ]}); </script>


**Order Success Tracking Code:**

    <script type="text/javascript" src="//static.criteo.net/js/ld/ld.js" async="true"></script> 
    <script type="text/javascript"> 
        window.criteo_q = window.criteo_q || []; 
         window.criteo_q.push( {event: "setAccount", account: **Your Account Number**}, 
            {event: "setCustomerId", id: "<?php if(Mage::getSingleton('customer/session')->isLoggedIn()) {$customerData = Mage::getSingleton('customer/session')->getCustomer();echo $customerData->getId();
     }?>"}, 
            {event: "setSiteType", type: "d"}, 
            {event: "trackTransaction" , id: "<?php echo $this->getOrderId(); ?>", item: [
            <?php   
                $count = 0;
                foreach ($items as $item):
                $count++;
                /* Get Configurable Sku from Simple product SKU/ID.
                 * If there is no configurable/simple product set up, then just use the standard Sku display
                 * */
                $parentId = Mage::getResourceSingleton('catalog/product_type_configurable')->getParentIdsByChild($item->getProductId());
                $configurableProductSku = Mage::getModel('catalog/product')->load($parentId)->getSku();
                if ($configurableProductSku)  {
                    $IdString .= $configurableProductSku;
                }
                else  {
                    $idString .= $item->getSku();
                }
                $PriceString .= $item->getPrice();
                $quantityString .= (int)$item->getQtyOrdered();
            ?>  
                <?php if( $count == count($items)): ?>
                { id: "<?php echo $IdString; ?>", price: <?php echo number_format($PriceString,2,'.',' ')?>, quantity: <?php echo $quantityString ?> } 
                <?php else: ?>
                { id: "<?php echo $IdString; ?>", price: <?php echo number_format($PriceString,2,'.',' ')?>, quantity: <?php echo $quantityString ?> }, 
                <?php endif; ?>

            <?php 
                $IdString = '';
                $PriceString = '';
                $quantityString ='';
                endforeach;
            ?>
            ]}); </script>



----------------------------------
And that's everything you need to know! 

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

Generate a novel item by organizing the key of an array of objects

I have an array of objects containing various items: [ { CATEGORY:"Fruits" ITEM_AVAIL:true ITEM_NAME:"Apple" ITEM_PRICE:100 ITEM_UNIT:"per_kg" ITEM_UPDATED:Object ORDER_COUNT:0 }, { CATEG ...

What is the best way to retrieve the maximum value from a JSON array?

I need help calculating the highest probability value and finding the corresponding label using JavaScript or jQuery. For example, I want to determine the highest probability for "tulips." Any assistance is greatly appreciated. result_predictions=[ { ...

Internet Explorer does not support the split function in JavaScript

I've been utilizing the split function to separate dates, but I encountered an issue where the code doesn't function properly in Internet Explorer, although it works fine in other browsers. The ul and li elements are dynamically generated. <! ...

Tips for placing a component at the top of QML views

Seeking advice on how to add a QML Menu component to the top of all views in order to achieve a cohesive look and feel similar to that of a typical webpage menu. Any suggestions on how I can accomplish this? import QtQuick 1.0 Row { width: 500 ...

Vuejs application is not producing the anticipated outcome when an ordered list contains an unordered list

Is there a way to nest an unordered list within an ordered list in vue 2? I've attempted <template> <div class="p-14"> <ol class="numberlist"> <li>An numbered list</li> <li>Cont ...

Utilizing Jquery to automatically scroll to a specific div on page load by setting an

I am attempting to automatically scroll to the div specified in the URL. The URL may include one of 21 different IDs such as: url.com/test#lite1 url.com/test#lite2 url.com/test#lite3 This scrolling action should happen when the page loads (so that user ...

I have been working on incorporating a menu item in React, but I keep encountering an error

I am using the MenuItem component to create a dropdown menu in my React project. Despite importing the necessary package, I am encountering an error when running the server. I have searched for solutions but haven't found a definitive me ...

Activate a Tab using JavaScript in Vue.js

Hello there, currently working with Vue and Bootstrap-Vue. The scenario is as follows: I have designed a registration page with 2 tabs. The user needs to complete the first tab before moving on to the second one by clicking a button. The second tab initia ...

Having difficulty uploading files using FormData in JavaScript, as $_FILES is returning empty

I have implemented a file upload feature to my server using JavaScript, but I am facing an issue with certain jpeg/png files where the $_FILES and $_POST variables are empty. Despite trying various solutions, I haven't been able to resolve this issue. ...

Using Node.js: Mimicking Keystrokes on the Server Side (Similar to a Macro)

I am currently working on a node.js script that is designed to replicate the functionality of sending keypresses, such as the up arrow or the "a" button. My ultimate goal is to create a clone of the popular game Twitch Plays Pokemon. Essentially, whenever ...

How can one get rid of a sudden strong beginning?

Recently, I delved into the world of CSS animation and encountered a frustrating issue. I've tried numerous methods and workarounds to achieve a smoothly looping animation without interruptions. Despite my efforts, I have not been able to replicate th ...

Organize table cells based on decimal places

Organize the table cells based on their decimal points. Plunker Sample JSON: [ { "data1": [ { "name": "Download", "id": "1.1.1" }, { "name": "Download", ...

Transferring PHP array data to JavaScript using JSON

Hello there! I'm currently working with a PHP file that uses json_encode to encode an array. This file is then accessed by the jQuery ajax function to fetch the array. However, I'm having trouble understanding how to properly utilize the array. W ...

I'm seeking assistance in identifying the issue with my form validation code. Could anyone lend a hand?

<!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="./css/createanaccount.css"> <script src="https://kit.fontawesome.com/c90e5c3147.js" crossorigin=&quo ...

Issue with redirecting to another link in Angular routing

After numerous attempts, I finally managed to configure the adviceRouterModule correctly. Despite extensive research and Google searches, I couldn't quite crack it. Here is the configuration for my AdviceRoutingModule: const adviceRouters: Routes = ...

Activating/Deactivating a button with just a press

In my SQL data display, each row has an "Add To Zip" button that is initially enabled. I want to disable the button in the current row when it's clicked and later re-enable them using a different PHP file. What's the best way to achieve this with ...

Issue with displaying the Bootstrap Autocomplete Input Dropdown

I've been struggling with this issue for hours now. Using Bootstrap 3, I am attempting to implement the bootstrap autocomplete input with ajax. The data is being retrieved successfully through Ajax, and I can confirm that. However, the dropdown menu i ...

Stopping the execution of a request handling function in Express/Node: tips and tricks

I am currently running an Express server that offers some computations as web services. The computation time can vary from less than 1 second to 10 seconds. I am curious if there is a method to halt the execution of a request-handling function (which is ...

What could be causing the JSON content to not display in an AJAX request?

I am facing an issue while trying to retrieve JSON data from one page to another. js_page.php <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> ...

Safari having trouble with cross-domain cookie functionality

I currently manage 2 different websites: 3rdpartycookiemanager.com website.com When I access website: I initiate an Ajax call to: using the following jQuery call: $.ajax({ ... type: 'POST', url: 'https://www.3rdpartycookiemanag ...