1

I have a view that has a form. I have a button which calls a controller via Ajax.

    echo CHtml::submitButton('Generate', array(
        'ajax'        => array(
            'type'    => 'POST',
            'url'     => CController::createUrl('Calculator/generateRetailers'),
            'update'  => '#div_retailers'
        )
    ));

The action controller what it does is to gather some data from MySQL and then renderPartial HTML tables into my form. Exactly in the div #div_retailers. This is the create option. Now I am trying to implement the update action which should render the information provided in the create action and draw the tables.

I would like to be able to call generateRetailers action controller from my view. Something like this:

<div id="div_retailers">
</div>

<script type="text/javascript">
    // I would like to call a url using jQuery?
    $.ajax({
        url: "/Calculator/generateRetailers"
    });
</script>

How can I achieve this?

Thanks

tereško
  • 58,060
  • 25
  • 98
  • 150
ivantxo
  • 719
  • 5
  • 18
  • 36
  • I don't really understand your question/problem -- you seem to be showing how to call a controller action from a view (via Ajax). Can you clarify? – ldg Sep 20 '11 at 03:23
  • @ldg Yes! exactly I want to call a controller via Ajax from within a view. But from raw JavaScript with no buttons or links or any HTML object. Is it possible? – ivantxo Sep 20 '11 at 04:57

2 Answers2

1

Do the exact same thing you already do in the widget:

<script type="text/javascript">
  // I would like to call a url using jQuery?
  $.ajax({
    url: "<?php echo CController::createUrl('Calculator/generateRetailers');?>"
  });
</script>
Jon
  • 428,835
  • 81
  • 738
  • 806
  • now before making the call I need to call another JavaScript function. If I call JavaScript before the $.ajax, then the controller is not called. How can I do this? Thanks – ivantxo Sep 23 '11 at 06:34
  • @ivan.freire: Depends on what function you are calling, how you are calling it, if it causes errors, etc. In any case, that sounds like a different question. – Jon Sep 23 '11 at 06:47
  • sorry definitely it is another question. Sorry, I had a JavaScript error, wrong index in an array. Anyway, your solution worked for me. Thanks. – ivantxo Sep 23 '11 at 07:01
0

Interesting, there is no built-in url generator for ajax. So im calling ajax with helper variable, which is generated by my yii app. I use Yii::app()->clientScript("config.url = ".Yii::app()->createUrl() . "); and then in pure javascript i can use a global variable config where i have generated urls.

$.ajax({
url: config.url
});
RusAlex
  • 8,245
  • 6
  • 36
  • 44