Friday, September 5, 2014

Php Codeigniter :: calling controller function from view button click using Jquery AJAX

Hi in this post i will how to call a controller action method from view. In view button click event we will make a ajax call to controller method.

View :

<HTML>
<HEAD>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
function AjaxCall(){
$.ajax({
type: "post",
url: "http://localhost/phpProj/index.php/usercontroller/method1",
cache: false,
data: $('#userForm').serialize(),
success: function(json){
try{
var obj = jQuery.parseJSON(json);
alert( obj['STATUS']);


}catch(e) {
alert('Exception while request..');
}
},
error: function(){
alert('Error while request..');
}
 });
}
</script>
</HEAD>
<BODY>
<form name="userForm" id="userForm" action="">
<table border="1">
<tr>
<td valign="top" align="left">
Username:- <input type="text" name="userName" id="userName" value="">
</td>
</tr>
<tr>
<td valign="top" align="left">
Password :- <input type="password" name="userPassword" id="userPassword" value="">
</td>
</tr>
<tr>
<td>
<input type="button" onclick="javascript:AjaxCall();" value="Submit"/>
</td>
</tr>
</table>
</form>
 </BODY>
</HTML>

Controller:

class usercontroller extends CI_Controller {

  public function method1() {
$userName =  $_POST['userName'];
$userPassword =  $_POST['userPassword'];
$status = array("STATUS"=>"false");
if($userName=='admin' && $userPassword=='admin'){
$status = array("STATUS"=>"true");
}
echo json_encode ($status) ;

}


}


No comments:

Post a Comment