Natasha Natasha - 3 months ago 11
Javascript Question

Calling controller method from javascript

I need to call a method of controller named

test()
from a Javascript. Script code is given below:

function changeColor(id, color)
{
element = document.getElementById(id);
qnid = document.form1.pickupFrom.qnid;

//window.location = "<?= site_url('controller/test') ?>"
}


Is it possible? And how to pass the parameters?

Answer

It depends on what parameters youn need to pass. Are they PHP parameters? The you're doing just fine, or better see @Sudhir answer.

If your params come from javascript you shoulnd't use the site_url() function (since when it elaborates and spit out the url, javascript is yet to be executed). It would be much easier to build a URL this way:

function changeColor(id, color) {
            element = document.getElementById(id);
            qnid = document.form1.pickupFrom.qnid;

            window.location =  "<?php echo base_url();?>index.php/controller/test/"+element+"/"+qnid;
}

I'm assuming those two are the parameters you want to pass.

Comments