2

I am trying to call $states = craft()->commerce_states->getAllStates(); from within my own plugin, via an ajax request.

MyPlugin.php

if (craft()->request->isAjaxRequest()) {
    return $this->returnJson(['states' => craft()->commerce_states->getAllStates()]);
}

The above will return this:

Object {states: Array[72]}

However, as I'm walking myself through it, I can see that the original call:

var states = {{ craft.commerce.statesArray|json_encode|raw }};

Gives me these objects:

Object {13: Object, 38: Object, 233: Object}
Object {13: Object, 38: Object, 233: Object}

So it's pretty obvious i'm not calling the correct method. I am using requirejs within my project and having the javascript right in the template is returning errors - it can't access jquery.

Thank you for any suggestions!

2

Instead of calling getAllStates() to get the same data back as the twig call:

var states = {{ craft.commerce.statesArray|json_encode|raw }};

Within your plugin you need to call getStatesGroupedByCountries()

MyPlugin.php

if (craft()->request->isAjaxRequest()) {
    return $this->returnJson(['states' => craft()->commerce_states->getStatesGroupedByCountries()]);
}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.