Welcome Guest, Not a member yet? Register   Sign In
How do I call MVC Controller from with Javascript function
#1

[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">
#2

[eluser]NeoArc[/eluser]
I did not understood your problem correctly, but, you can try using an AJAX enabled Framework, as jQuery:

Code:
jQuery("#form_id").submit(function(e){
  //We detect the submit event, and instead, we request the update using an xmlhttprequest object
  jQuery.post('/base/process/',jQuery("#form_id").serialize(), function(response){
    if(response=='ok'){ alert('ok');}
    else { alert('Not ok'); }
  });
  
  e.preventDefault(); //Do not submit the form.
});
#3

[eluser]CodeIgniteMe[/eluser]
To call on CI Controller from JS without reloading the page would somewhat require an AJAX request or so.
You can use what NeoArc suggest, use jQuery because it has a cool syntax and has AJAX bundled with it.
This is a sample code for your issue.
Code:
<$cript src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></$cript>
<$script>
//save the URL path to your MVC controller
var request_url = '&lt;?php echo site_url('request'); /*requires URL Helper*/ ?&gt;';
//execute codes when HTML document is ready
$(document).ready(function(){
// holds the click event of the button with id=btn_Add
$('input#btn_Add').click(function(e){
  //save the button object for future purpose
  btnAdd = $(this);
  //prevent normal postback
  e.preventDefault();
  //create an AJAX request
  $.ajax(
   'url':request_url, //URL of the request
   'type':'post', //POST method
   'success':function(){ //execute when successful
    btnAdd.attr('disabled','true'); //disable the button
    btnAdd.val('sending ...'); //change the button text value
   }
  });
});
</$script>




Theme © iAndrew 2016 - Forum software by © MyBB