TraxxTrack
TraxxTrack

Reputation: 1

How to send an ajax post request to a front controller (AdressController.php)

I have a select dropdown, and when I select a value from that dropdown, I am trying to send from address.tpl an ajax post request to AddressController.php.

I cant seem to find how to send the form to the correct URL (the url of the controller, its path is: /public_html/override/controllers/front/AddressController.php)

My ajax request that is in the address.tpl

<script>
    {literal}

        var uriAddress = 'index.php?controller=AddressController&action=example&token=922fb5c427f8abfa1eaf7aa175c9529b';



        $('#id_state').change( function() {
           $(this).find(":selected").each(function () {                              
                city = $(this).text();                   
            });

            $.ajax({
                url : uriAddress,
                type : 'POST',
                async: true,
                cache: false,
                dataType : "json",
                data: {
                    city: city
                },
                success : function (result) {
                    console.log(result);
                }
            });
        });

    {/literal}
</script>

And this is my AddressController.php

    public function displayAjax()
    {
        if (count($this->errors))
        {
            $return = array(
                'hasError' => !empty($this->errors),
                'errors' => $this->errors
            );
            die(Tools::jsonEncode($return));
        }

        if(Tools::getValue('MyControllerAction')=='myMyControllerAction')
        {
            $cities = array();
            $sql = 'SELECT judet, localitate FROM sdn_fancourier_cities WHERE judet = "alba"';
            if ($results = Db::getInstance()->ExecuteS($sql))
            foreach ($results as $resultCity) {
                array_push($cities, $resultCity);
            }

            $this->context->smarty->assign(array(
                'city_list' => $cities,     
            ));

           return json_encode($this->context->smarty->assign(array(
                'city_list' => $cities,     
            )));

        }

    }

Upvotes: 0

Views: 1827

Answers (1)

WebXY
WebXY

Reputation: 139

The displayAjax() function is called only if you send an ajax parameter in your $.ajax call.

Also, when you send an action parameter (in your case it's "example"), the function called will be displayAjaxExample().

Your AddressController.php should be something like this :

class AddressController extends AddressControllerCore
{
    public function displayAjaxExample()
    {
        [YOUR CODE HERE]
    }
}

and your ajax call should be :

$.ajax({
    url : uriAddress,
    type : 'POST',
    async: true,
    cache: false,
    dataType : "json",
    data: {
        city: city,
        ajax: 1
    },
    success : function (result) {
        console.log(result);
    }
});

Upvotes: 0

Related Questions