Join us for an upcoming Shopify Partner webinar on February 27, 2024. Discover the latest Checkout Extensibility features, and deep dive on improvements to Shopify Functions and Web Pixels. Register now for either the 10am EST or 2pm EST sessions.

Attempting to return a selected list of Products using PHP/Javascript API.

ScinteraShopy
Shopify Partner
37 2 2

Obviously I am new and attempting my first Shopify App. I choose to use PHP / Javascript. 

 

In the below code example on my test store I can successfully Select Products through the Button. Checked the console and the correct selected array exists. Yay! However, I am trying to use Cookies to save the Selected list. And there is no output from: print_r(selected); 

Can some kind soul please tell me what I am doing incorrectly or if there is a better way to return the selected array?

Thank you.

 

 

 

 

 

<?php include_once("header.php"); ?>
<script>
  
// Creating a cookie after the document is ready
$(document).ready(function () {
    createCookie("efc", "EdwardC", "10");
});
   
// Function to create the cookie
function createCookie(name, value, days) {
    var expires;
      
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    }
    else {
        expires = "";
    }
      
    document.cookie = escape(name) + "=" + 
        escape(value) + expires + "; path=/";
}
  
</script>


<button id="open-picker">Select Products</button>

<script>
document
.getElementById('open-picker')
.addEventListener('click', async () => {
const selected = await shopify.resourcePicker({type: 'product', multiple: true});
console.log(selected);
});
</script>

<?php

$selected = $_COOKIE['selected'];
echo print_r($selected);

echo $_COOKIE["efc"];
?>

<?php include_once("footer.php"); ?>

 

Reply 1 (1)

Liam
Shopify Staff
2677 288 736

HI ScinteraShopy,

 

It looks like you're not setting the cookie for the selected products in your JavaScript code. The selected products are being logged to the console, but they're not being saved to a cookie.

 

You can set the cookie in your JavaScript code right after logging the selected products to the console. You may need to stringify the selected products array because cookies can only store strings. Then, in your PHP code, you can retrieve and decode the cookie.

 

Hope this helps!

Liam | Developer Advocate @ Shopify 
 - Was my reply helpful? Click Like to let me know! 
 - Was your question answered? Mark it as an Accepted Solution
 - To learn more visit Shopify.dev or the Shopify Web Design and Development Blog