0

I am trying to change a drop down based on a previously selected drop down. I am able to write the function in jQuery.

Since i am not able to use the URL path across various installation based on the server as i have to hard core the URL into the script.

<script type="text/javascript">
function getCategory(){
    var industryId = $("#CompanyCompanyIndustryId").val();
    $.getJSON('http://localhost/gitgrow/users/fetch/'+industryId, function(data) {
        var options = '';
        $.each(data, function(key, value) { 
          options += '<option value="' + key + '">' + value + '</option>';
        });
        $("#CompanyCompanyCategoryId").html(options);
    })
}
</script>

How to achieve the same using CakePHP and JS component ?

Harsha M V
  • 54,075
  • 125
  • 354
  • 529

1 Answers1

1

You can write your javascript in the page, and use $this->Html->url to build your URL value. Just write it in $this->Html->scriptBlock(); and add 'inline'=>false to make it write in the head instead of at that point of the document:

$this->Html->scriptBlock("
    function getCategory(){
        var industryId = $(\"#CompanyCompanyIndustryId\").val();
        $.getJSON('" . $this->Html->url(array('controller'=>'users', 'action'=>'fetch', $industryId)) . ", function(data) {
            var options = '';
            $.each(data, function(key, value) { 
              options += '<option value=\"' + key + '\">' + value + '</option>';
            });
            $(\"#CompanyCompanyCategoryId\").html(options);
        })
    }
", array('inline'=>false));

Now you have javascript that's generated in the <head> (or anywhere else you'd like it to be), and are using CakePHP to build the URL.

Dave
  • 28,833
  • 23
  • 113
  • 183
  • I've changed my answer to fix the quote issues I could see, but - quote issues are something you can likely fix on your own when you get into an actual editor (I wrote this in StackOverflows RTE). The concept is the same, and I believe that's what you were asking. – Dave Jul 05 '12 at 14:14
  • got it.. i figured that out. Thanks a lot :) – Harsha M V Jul 05 '12 at 14:20
  • cant i just usethe html url instead of using the scriptBlock. whats the advantage of using it ? – Harsha M V Jul 06 '12 at 05:04
  • 1
    You can just use the Html helper - the benefit of the scriptBlock is that you can then tell CakePHP to put your javascript in any location on the page - in the header, or at the bottom of the page...etc. If you're already writing where you want, you can ignore the scriptBlock part – Dave Jul 06 '12 at 13:53