Magento Ajax add to cart not working for subsites - ajax

I've written a small script that is called via ajax for adding products to the cart.
$request = Mage::app()->getRequest();
$session = Mage::getSingleton('core/session', array('name'=>'frontend'));
$cart = Mage::helper('checkout/cart')->getCart();
foreach($pids as $pid){
if(!pid || $pid == ''){continue;}
$product = Mage::getModel('catalog/product')->load($pid);
$cart->addProduct($product, $qty);
}
$session->setCartWasUpdated(true);
$cart->save();
I have a multi site setup and this script works fine when it is run under the main site but when I run it under one of the subsites it doesn't add it to the cart.
I've tried having the addtocart.php in the root of the subsite (and including the main sites mage.php) and have also tried adding it to the root of the main site, But nothing works.
Do I need to specify the website id somewhere?
Thanks

First take the easy step of setting a cookie domain prefixed with a single period. This acts like a wildcard.
The default behaviour is to not share carts between stores. In your 'small script' make sure the correct store is chosen the first time you initialise the app.
Mage::app($storeId);
Sometimes when crossing domains you need to include the SID as an URL parameter. I'm not sure how you would find that value, perhaps from the referrer page..?

Related

I duplicated products magento and my urls are product-1.html product-2.html

I have made my magento store (community)
I have used duplicate product on a lot of products and I didn't get that the URL key field had to be changed for every product i thought i would solve it self.
Now i have about 100 products and unfortunately they are now named example:
/HaircolorBlack.html , /haircolorblack-1.html, /haircolorblack-2.html and so on.
I wonder if there are any way to easy make magento re create the url after what the products meta title is?
This would be so helpful.
I saw this two year old post about approx the same thing but I didn't wanted to use that script since I don't know if it might break anything in my magento since its been so much updates. Here is link: Clearing URL keys in Magento
Also I need total moron instructions on where to put the script to. Sorry ;)
Thanks a lot.
S
You can create a one off script using magento itself.. add this script somewhere in your magento root folder (beside index.php):
<?php
require_once "app/Mage.php";
Mage::app('admin'); // must be admin to do changes
function convertToUrlKey($string) {
return $string; // I WILL LEAVE YOU TO SOLVE THIS PART
}
foreach(Mage::getModel('catalog/product')->getCollection() as $product):
$metaTitle = $product->getMetaTitle();
$urlKey = convertToUrlKey($metaTitle);
try {
$product->setUrlKey($urlKey);
$product->save();
echo "Assigned url key {$urlKey} to {$product->getName()}.\n";
} catch(Exception $ex) {
echo "ERROR: {$ex->getMessage()}";
}
endforeach;
Obviously this is not a complete solution as you will have to re-create the convertToUrlKey function for the correct behavior of converting 'Black Hair Color' to 'black-hair-color' and also ensure that there will be no duplicate url keys generated..
You can run the script by browsing to it or running through SSH:
$ cd magentoProject
$ php -f changeUrlkeys.php
Good luck!

Magento cart / session data outside magento

This might get a little confusing as I have tried everything to make this work. All I want is a link in my brand site (domain.com) which shows the qty in my magento 1.5.1 cart (domain.com/shop) I quite easily pulled in product data and navigation blocks but no matter what I do, cart qty is always 0 from outside magento.
The main way I tried was just in my brand site to go:
require_once $_SERVER['DOCUMENT_ROOT'].'/shop/app/Mage.php';
umask(0);
Mage::app();
Mage::getSingleton('core/session', array('name'=>'frontend'));
// trying everything
Mage::getSingleton('checkout/cart')->getItemsCount(); // returns 0
Mage::helper('checkout/cart')->getItemsCount(); // returns 0
Mage::getSingleton('customer/session')->isLoggedIn(); // returns blank
Mage::helper('checkout/cart')->getCart()->getItemsCount(); // returns 0
Mage::helper('checkout/cart')->getCart()->getQuote()->getItemsCount(); // returns blank
Then, when none of those worked, I created a template in Magento just to give me the cart qty as a block which returns the block fine but still zero in the cart!
$block = $this->layout->createBlock('core/template');
$block->setTemplate('page/html/cartForBrand.phtml');
return $block->renderView();
and the block in magento is simply
Mage::getSingleton('core/session', array('name'=>'frontend'));
$cart = Mage::getModel('checkout/cart')->getQuote()->getData()['items_qty'];
I've seen a lot of people having similar issues: / session_cookie_management, .domain.com cookie_domain(even though that's subdomain specific), I've read and tried everything I could find for 2 days. Constantly deleting session and cache directories and clearing cache and cookies with magento caching disabled.
This is the first question I've posted on this site after using it for years, I've been stuck on this for 3 days! Pulling my hair out!
I copied your code and tested it on Magento 1.5, 1.6 and 1.7.
I placed the code in a PHP file called test.php in the Magento root directory. This is the code I used:
umask(0);
require_once 'app/Mage.php';
Mage::app();
Mage::getSingleton('core/session', array('name'=>'frontend'));
var_dump(array(
"Mage::getSingleton('checkout/cart')->getItemsCount()" =>
Mage::getSingleton('checkout/cart')->getItemsCount()
)); // returns number of items (w/o qty)
var_dump(array(
"Mage::helper('checkout/cart')->getSummaryCount()" =>
Mage::helper('checkout/cart')->getSummaryCount()
)); // returns number according to configuration
var_dump(array(
"Mage::getSingleton('customer/session')->isLoggedIn()" =>
Mage::getSingleton('customer/session')->isLoggedIn()
)); // returns bool true|false
The Magento instances use the local test host names magento15.dev, magento16.dev and magento17.dev.
The I requested the corresponding Magento instances and placed a product in the cart (tested with a configurable and a simple product), and then updated the quantity of the product in the cart.
Between each step I reloaded the test.php file in the browser.
The result is always the same: it works as expected. Each call returns the same values as on the Magento site.
So this means your code is correct, it might be your domain and/or setup (is the browser sending the Magento frontend cookie when you request your test script)?
Your code is good, but by default Magento's "frontend" cookie isn't accessible outside of Magento (and so you can't access session data). You'll need to change the cookie's path in Admin > System > Configuration > Web > Session Cookie Management > Cookie Path. Try setting that to /
If all you want is the qty why instantiate magento at all. Just set a client side cookie (ie cart_qty) and then read this cookie on your main site header.
Think you forgot:
Mage::app()->setCurrentStore(1); // replace 1 with your store id
after
Mage::app()
In Your Code: Instead of:
Mage::app();
use
Mage::app()->loadArea('frontend');
& u will get your output...

Magento redirected to other URL after order editting

Currently I'm experiencing a problem after editing orders in the Magento admin. The page is always redirected to another URL, the base of which belongs to the store view that the order belongs to. And this page requires re-login to the admin.
For example, I have two base URLs, each belongs to one store view:
www.example.old.com //old store view (default)
www.example.new.com //new store view
The system uses www.example.old.com as the default base URL. So under www.example.old.com I create an order for the new store and invoice it. Then on submitting the invoice, the page is redirected from
http://www.example.old.com/index.php/admin/sales_order_invoice/new/order_id/1234/
to
http://www.example.new.com/admin/sales_order/view/order_id/1234/
And it requires login for another time.
I traced the redirection code to Mage_Core_Model_Url
public function getRouteUrl($routePath=null, $routeParams=null)
...
$url = $this->getBaseUrl().$this->getRoutePath($routeParams);
public function getBaseUrl($params = array())
....
if (isset($params['_store'])) {
$this->setStore($params['_store']);
}
....
return $this->getStore()->getBaseUrl($this->getType(), $this->getSecure());
Then I don't know what to do. There is no parameter _store but it seems that Magento determines which store view to run based on the order being treated, when it is supposed to stay on the same base URL throughout the admin.
Have you tried to enable customer data sharing between the stores in the backend?
Sorry for newbie answer, still learning magento
For those who may still show interests to this old entry, I share my solution. It is not a good one, indeed it is a hard-coded redirection to avoid going back to an uncertain URL, but it fixed the problem for me.
In the controller action where the redirection happens, modify
$this->_redirect(..., array(... => ...));
to
$this->_redirect(..., array(... => ..., '_store' => Mage::app()->getStore($storeId)));
This ensures that the redirection always goes to the specified store.
Reason is that Magento switchs context to store of order because it requires to translate the email template correctly.
Look at class Mage_Core_Model_Template there are two method _applyDesignConfig and _cancelDesignConfig. First function switches context and remember old context, second function should return all back. But, there is a bug. See more at: http://www.magthemes.com/magento-blog/magento-142-multiwebsite-admin-redirect-problem-quick-workaround/#comment-1084

Magento - Load product by url

How would one load a product model in Magento, if the product id is not available and only the product's url is? For example, I want to retrieve the product model from it's friendly url, such as
electronics/cameras/olympus-stylus-750-7-1mp-digital-camera.html
I found the following code in another post:
$oRewrite = Mage::getModel('core/url_rewrite')->loadByRequestPath(
$path
);
but it doesn't seem to work correctly. The Magento documentation is very lacking in this area; does anyone know how to accomplish this?
Here's an alternative solution.
First use the URL rewrite model to find the route which matches your product:
$vPath = 'electronics/cameras/olympus-stylus-750-7-1mp-digital-camera.html';
$oRewrite = Mage::getModel('core/url_rewrite')
->setStoreId(Mage::app()->getStore()->getId())
->loadByRequestPath($vPath);
Then you can call getProductId() on the route to locate the produc's id:
$iProductId = $oRewrite->getProductId();
Finally if you require the product model object itself it's then a simple matter to call:
$oProduct = Mage::getModel('catalog/product')->load($iProductId);
The main difference between the above, and the code example you've posted is the call to setStoreId. The same product may have different URLs depending on which store it's in, so the routing component needs to have the appropriate store context before it can locate the product to display.
The advantages of this over Zachary Schuessler's solution is that using the URL rewriter will locate the correct product every time if the trailing portions of the url are the same for different products (e.g. folder1/my-product-name and folder2/my-product-name are different products). Using the URL rewriter also works in situations where "folder1/my-product" refers to different products on different stores. This may or may not apply to your environment.
I'm curious as to why you need to do this, since this might not be the best solution. This should be easy enough using the addAttributeToFilter() method on the collection:
$path = 'folder/folder/my-product-name';
// Get the product permalink
$productName = explode('/', $path);
$productName = end($productName);
// Filter the url_path with product permalink
$products = Mage::getModel('catalog/product')->getCollection();
$products->addAttributeToFilter('url_path', $productName)
->getFirstItem();
Zend_Debug::dump($products->getData());exit;

Auto fill information for movie products in Magento

I'm working with Magento CE 1.6 in a project where we need an easy way to fill the movie info in DVDs and Blu-Rays products for a reseller ecommerce. I'm set to use the Rotten Tomatoes API wich seems very adequate for our purposes, but here's the thing: We don't want to have to input every single detail of the movie in the New Product dialog, oppositely, we want to fetch the info automatically using the movie name as hint (the API perfectly supports this). I though that we could achieve this by two means:
Having the administrator to enter only the names of the movies and
create and run periodically a script that fetches the rest of the
info with the API and updates the data directly in the DB. I've been
watching the DB changes when a product is saved and would'nt like to
do that.
Editing the Magento code to make the new product form auto fillable,
maybe with ajax, once a movie name is entered. Zend framework isn't
my strong and seems kind of hard too.
Am I seeing this problem from the rigth angle? Is there maybe another API? Or a Magento extension? Or another ecommerce?!
I would suggest a little different approach. Enhancing the Admin interface is difficult, but possible. Here is an easier way.
Method #1 - Quick and Easy
Create yourself a script that would go through a list of products. You can select them by attribute type, category, or even just select them all! Then, loop through that collection, and for each product, grab the title, query the movie API, and set the product's attributes. Then, save the product, and move to the next one. Something like this:
Note: Be sure to create your custom attributes in the admin and assign them to the attribute set.
<?php
require_once 'app/Mage.php';
umask(0);
Mage::app('default');
function getVideoDataFromAPI($title)
{
// get your data from the API here...
return $data;
}
$collection = Mage::getResourceModel('catalog/product_collection')
->addAttributeToFilter('attribute_set_id', $yourAttributeSetId)
->addAttributeToFilter('year', ''); // <-- Set a field here that will be empty by default, and filled by the API. This is '' because it won't be null.
foreach ( $collection->getAllIds() as $id ) {
$product = Mage::getModel('catalog/product')->load($id);
$videoData = getVideoDataFromAPI($product->getName());
if ( empty($videoData) ) { continue; }
$product->setYear($videoData['year'])
->setRating($videoData['rating'])
->save();
}
?>
Method #2 - Do the above, but in a custom extension
I always like extensions over scripts. They are more secure and more powerful. With an extension you could have an admin list of the products, can filter them how ever you would like, and have a mass action to pull the video data manually. You could also set it up on a cron job to pull regularly.

Resources