CodeIgniter Forums
Call MVC Controller from with Javascript function - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived General Discussion (https://forum.codeigniter.com/forumdisplay.php?fid=21)
+--- Thread: Call MVC Controller from with Javascript function (/showthread.php?tid=50500)



Call MVC Controller from with Javascript function - El Forum - 03-28-2012

[eluser]justmelat[/eluser]
I have a onclick event on a submit button in my CI app. So when user clicks submit, it goes to my js function that disables the button, but it does not continue processing. I used this "document.forms["mainFrm"].submit();", but because of the way the code is written I need it to go directly to a controller and finish processing.

So how do I call a CI controller from my js function?

Here is the function that is being called onClick:

Code:
function disableWhenSubmit()
{
alert ("You did get here");
var holdBtnElement = document.getElementById('btn_Add');
holdBtnElement.disabled = true;
holdBtnElement.value = "sending ...";
//document.forms["createRequestForm"].submit();
<?= base_url();?>index.php/request"; //this is what I am working on
}

and here is the button:
Code:
<input type="submit" id="btn_Add" name="btn_Add" value="Submit">



Call MVC Controller from with Javascript function - El Forum - 03-28-2012

[eluser]Kamarg[/eluser]
Most likely you want to look into doing an ajax request. Or if you don't care if the page refreshes, you just ignore all the javascript and let the html form submit normally.


Call MVC Controller from with Javascript function - El Forum - 03-28-2012

[eluser]Matalina[/eluser]
You can't use php in an external javascript file unless your php parser parses .js files, or if you extranal script is a .php with a javascript header at the start, but you can't call ci code inside of the external javascript file unless it's processed through ci with a controller.

I tend to do this for my straight js files: Note: remove the index.php part if you are using .httaccess to remove it.
Code:
$url = [removed].href.toString();
re = /^(http:\/\/\w*\.*(\w+\.\w+)\/.*)\/*index\.php*/;
matches = re.exec($url)

var $base_url = matches[0];
var $img_url = matches[1];

You'll have to use XMLHttpRequest as well to process said script.

If your javascript is in the view then you can use php like you have it.