1

I want to create a City dropdown, I have one issue with Ajax and 404

I want to show 3 dropdowns (country , state , city ) I choose country and all fine, the state field have the states in the dropdown. Then I choose state and nothing happens in the city field... It still with blank input text

I saw in firebug a 404 error for this url: http://mydomain.com/index.php/citydropdown/index/getCities/?state_id=149&default_city=

My code:

app/etc/modules/Zeo_Citydropdown.xml

<?xml version="1.0"?>
<config>
  <modules>
    <Zeo_Citydropdown>
      <active>true</active>
      <codePool>local</codePool>
      <version>0.1.0</version>
    </Zeo_Citydropdown>
  </modules>
</config>

app/code/local/Zeo/Citydropdown/etc/config.xml

<?xml version="1.0"?>
<config>
  <modules>
    <Zeo_Citydropdown>
      <version>0.1.0</version>
    </Zeo_Citydropdown>
  </modules>
  <global>
    <helpers>
      <citydropdown>
        <class>Zeo_Citydropdown_Helper</class>
      </citydropdown>
    </helpers>
  </global>
</config>

app/code/local/Zeo/Citydropdown/Helper/Data.php

<?php
class Zeo_Citydropdown_Helper_Data extends Mage_Core_Helper_Abstract
{
    public function getCities($stateId)
    {
        $resource = Mage::getSingleton('core/resource');
        $readConnection = $resource->getConnection('core_read');
        $tableName = $resource->getTableName('ciudades');
        $query = "SELECT * FROM '".$tableName."' WHERE state_id = ".$stateId;
        $results = $readConnection->fetchAll($query);
        $cities = array();

        if(count($results) > 0)
        {
            foreach($results as $city)
            {
                $cityId = $city['id'];
                $cityName = $city['city_name'];
                $cities[$cityId] = $cityName;
            }
        }
        return $cities;
    }

    public function getCitiesAsDropdown($selectedCity = '',$stateId)
    {
        $cities = $this->getCities($stateId);
        $options = '';
        if(count($cities) > 0)
        {
            foreach($cities as $city)
            {
                $isSelected = $selectedCity == $city ? ' selected="selected"' : null;
                $options .= '<option value="' . $city . '"' . $isSelected . '>' . $city . '</option>';
            }
        }
        return $options;
    }
}

I add this script at the end of my billing.phtml in app/design/frontend/rwd/default/template/persistent/checkout/onepage/billing.phtml

<script type="text/javascript">
    <?php
    $address         = Mage::getSingleton('checkout/session')->getQuote()->getBillingAddress();
    $defaultCity     = $address->getCity();
    ?>
    Event.observe($('billing:region_id'), 'change', function(event) {
        var action = "<?php echo $this->getUrl('citydropdown/index/getCities'); ?>";
        var defaultCity = '<?php echo  $defaultCity ?>';
        var selectCountry = $('billing:country_id').value;
        if(selectCountry == "ES") {
            var action = "<?php echo $this->getUrl('citydropdown/index/getCities'); ?>";
            var stateId = $('billing:region_id').value;
            var request = new Ajax.Request(action,
                {
                    method: 'GET',
                    onSuccess: function (data) {
                        $('billing:city').replace('<select id="billing:city" name="billing[city]" class="required-entry">' + '<option value=""></option>' + data.responseText + '</select>');
                    },
                    onFailure: '',
                    parameters: {state_id: stateId, default_city: defaultCity}
                }
            );
        }

    });
    Event.observe($('billing:country_id'), 'change', function(event) {
        var selectCountry = $('billing:country_id').value;
        var defaultCity = '<?php echo  $defaultCity ?>';
        if(selectCountry != "ES"){
            $('billing:city').replace('<input type="text" class=" input-text required-entry absolute-advice " title="City" value="' + defaultCity + '" id="billing:city" name="billing[city]" autocomplete="off">');
        }
    });
</script>

I created one table in my database to save my cities:

CREATE TABLE `ciudades` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`state_id` int(11) NOT NULL,
`city_name` varchar(100) NOT NULL,
PRIMARY KEY (`id`)

I added some rows.

I didn't create more files or directories. All the code is here.I need to create some more files ?

I followed this guide. http://hemantwebsolution.blogspot.com.es/2014/03/magento-configuring-city-as-drop-down.html?view=classic

0

1 Answer 1

4

Hi you have not created controller from where you will get data using below your script code script

  if(selectCountry == "ES") {
            var action = "<?php echo $this->getUrl('citydropdown/index/getCities'); ?>";
            var stateId = $('billing:region_id').value;
            var request = new Ajax.Request(action,
                {
                    method: 'GET',
                    onSuccess: function (data) {
                        $('billing:city').replace('<select id="billing:city" name="billing[city]" class="required-entry">' + '<option value=""></option>' + data.responseText + '</select>');
                    },
                    onFailure: '',
                    parameters: {state_id: stateId, default_city: defaultCity}
                }
            );
        }

As You url citydropdown/index/getCities is that means

citydropdown -> citydropdown is frontName of router.

index -> controller name file name is IndexController.php.

getCities -> action name at controller file and that means function name : getCitiesAction

Step1: add below at config.xml

<!-- start of routers
    -->
    <frontend>
        <routers>
            <citydropdown>
                <use>standard</use>
                <args>
                    <module>Zeo_Citydropdown</module>
                    <frontName>citydropdown</frontName>
                </args>
            </citydropdown>
        </routers>
    </frontend>

Step2: create IndexController.php at app/code/local/Zeo/Citydropdown/controllers/ and code is

<?php
class Zeo_Citydropdown_IndexController extends Mage_Core_Controller_Front_Action{

    public function getCitiesAction($selectedCity = '',$stateId){
        $result=array();
        $result['mycities']=Mage::helper('citydropdown')->getCitiesAsDropdown($selectedCity,$stateId);
        $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($result));
    }
}

and return json data

Step3:'modify script code to get json data

Change code

 onSuccess: function (data) {
                        $('billing:city').replace('<select id="billing:city" name="billing[city]" class="required-entry">' + '<option value=""></option>' + data.responseText + '</select>');
                    }

to

 onSuccess: function (data) {
                        /* add this code */
                        var myjson=data.responseText.evalJSON(true);

                        $('billing:city').replace('<select id="billing:city" name="billing[city]" class="required-entry">' + '<option value=""></option>' + myjson.mycities + '</select>');
                    }
5
  • Awesome! It works perfect! thank you so much
    – Xus
    Commented Nov 6, 2014 at 10:31
  • Hi, I've tested it again and I have one problem, in IndexController.php stateId and selectedCity never have value. With firebug I can see the parameters are sending via get but the controller can't read those variables
    – Xus
    Commented Mar 26, 2015 at 11:47
  • 1
    I do not know if is the best way but for now I've fixed using this....... $this->getRequest()->getParams()
    – Xus
    Commented Mar 26, 2015 at 13:54
  • 1
    Don't worry man, I appreciate a lot the help you gave me, when I have more reputation (15 points) I will vote you positively.
    – Xus
    Commented Mar 26, 2015 at 14:15
  • how can i add this code in customer registration form in magento 2 Commented Mar 6, 2017 at 11:14

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