my ajax not giving result in codeigniter - codeigniter

i am registering users via ajax, user is inserted into the database but my loader continue to show loading and is no hiding furthermore i put an alert to view the result but it is also not shown
so where i am doing wrong please help me.
here is my view
<tr>
<td style="width: 25%;"><p>Name</p>
<input type="text" name="name" id="name_r"
placeholder="Enter name" required=""/>
</td>
<td style="width: 25%;"><p>username</p>
<input type="text" name="username" id="uname"
placeholder="Enter username" required=""/>
</td>
</tr>
my script is
$(document).ready(function(){
$("#register_staff").click(function(){
var name = $("#name_r").val();
var username = $("#uname").val();
if (name && username) {
$('#loader_register').show();
$.ajax(
{
type: "POST",
url:"<?php echo
base_url('register_management_staff')?
>",
data:{name:name,username:username},
success: function(result){
alert(result);
$('#loader_register').hide();
$('#name_r').val("");
$('#result_register').html(result);
}
}
);
}
else{
document.getElementById
('result_register').innerHTML='<font color=red>
Please fill all fields.</font>';
}
});
});
my controller is
public function register_management_staff()
{
$post['name']= $_REQUEST['name'];
$post['username']= $_REQUEST['username'];
$result = $this->managementmodel
->register_management_staff($post);
if($result == 1){
echo '<font color=green>Congrats! Successfully
Register.</font>';
}
else{
echo '<font color=red>Please enter correct data
and check availability.</font>';
}
}
my model is
public function register_management_staff($post)
{
$this->db->insert('management_login',$post);
return 1;
}

If you have a button by the id of register_staff then >
Edit Your Script and Use This
$(document).ready(function(){
$("#register_staff").on('click',function(){
var name = $("#name_r").val();
var username = $("#uname").val();
if (name && username) {
$('#loader_register').show();
$.ajax({
type: "POST",
url:"<?php echo base_url('register_management_staff'); ?>",
data:{name:name,username:username},
success: function(result){
alert(result);
$('#loader_register').hide();
$('#name_r').val("");
$('#result_register').html(result);
}
});
}
else{
$('#result_register').html("<font color='red'>Please fill all fields.</font>");
}
});
});

In your ajax code provide correct path in url
$.ajax(
{
type: "POST",
url:"<?php echo
site_url('register_management_staff')?
>",
data:{name:name,username:username},
success: function(result){
alert(result);
$('#loader_register').hide();
$('#name_r').val("");
$('#result_register').html(result);
}
}
);
Here in ajax url must be like
url:"<?php echo site_url('controller_name/method');?>"
Make changes are try

Related

controller not sending data back to ajax request codeigniter

I have developed a login system using ajax the problem is when i send the ajax request everything is working and validating fine i just need to pass data back to my ajax request I am using echo json_encode("true"); but somehow it is just echoing the value true in the controller and not going back in the view!
HTML
<form onsubmit="return validate()" method="post" action="<?php echo base_url(); ?>admin/admin_login">
<input class="md-input" placeholder="username" type="text" name = 'login_username' id = 'login_username' />
<input class="md-input" placeholder="password" type="password" name= 'login_password' id= 'login_password' />
<button type='submit' class="btn btn-primary btn-block btn-large">Login</button>
</form>
AJAX
<script>
function validate(){
if(!$("#login_username").val()){
alert("username is required");
return false;
}
if(!$("#login_password").val()){
alert("Password is required");
return false;
}
return true;
var data={
"login_username" : $("#login_username").val(),
"login_password" : $("#login_password").val()
};
$.ajax({
type: 'post',
url: '<?=base_url()?>Admin/admin_login',
dataType: 'json',
data:data,
success: function (data) {
if(data=="true"){
alert("ok");
}
else
{
alert("not ok");
}
}
});
}
</script>
admin_login controller
public function admin_login(){
$data = $this->input->post();
$status=$this->admin_validate->validate($data);
if($status){
$session=array(
"admin"=>$this->input->post("login_username"),
);
$this->session->set_userdata($session);
//redirect("Admin/contact");
header('Content-Type: application/json');
echo json_encode("true");
}
else
{
header('Content-Type: application/json');
echo json_encode("false");
//redirect("Admin");
}
}
Now iam going to change the code little
change the HTML form to
<form>
<input class="md-input" placeholder="username" type="text" name = 'login_username' id = 'login_username' />
<input class="md-input" placeholder="password" type="password" name= 'login_password' id= 'login_password' />
<button type='button' onclick="validate()" class="btn btn-primary btn-block btn-large">Login</button>
</form>
and Now change your ajax to
<script>
function validate(){
if(!$("#login_username").val()){
alert("username is required");
return false;
}
if(!$("#login_password").val()){
alert("Password is required");
return false;
}
$.ajax({
type: 'post',
url: '<?php echo base_url()."Admin/admin_login"; ?>',
data:{ "login_username" : $("#login_username").val(), "login_password" : $("#login_password").val() },
success: function (data) {
if(data=="true"){
alert("ok");
}
else
{
alert("not ok");
}
}
});
}
</script>
and your controller to
public function admin_login(){
$data = $this->input->post();
$status=$this->admin_validate->validate($data);
if($status){
$session=array(
"admin"=>$this->input->post("login_username"),
);
$this->session->set_userdata($session);
echo "true";
}
else
{
echo "false";
}
}
Hope this helps you. :)
Have you tried sending true or false without the quotation marks?, if not try creating an array and then passing it to the echo json_encode(); something like:
$result = array();
array_push($result, true);
echo json_encode($result);
on your ajax you will have to read it as follow
if(data[0] == true){
alert("Ok");
}else{
alert("Not OK");
}
Hope it helps
you are returning true in the script so the form is get submitted. no ajax call occurs.
<script>
function validate(){
if(!$("#login_username").val()){
alert("username is required");
return false;
}
if(!$("#login_password").val()){
alert("Password is required");
return false;
}
return true; // HERE THE ISSUE //
var data={
"login_username" : $("#login_username").val(),
"login_password" : $("#login_password").val()
};
$.ajax({
type: 'post',
url: '<?=base_url()?>Admin/admin_login',
dataType: 'json',
data:data,
success: function (data) {
if(data=="true"){
alert("ok");
}
else
{
alert("not ok");
}
}
});
}

ajax alert is not working using codeigniter

I am newer to ajax. I want to add two fields using ajax and codeigniter.. When i click the submit button the two fields are added but the alert message is not showing also the page is not refreshing. Can any one solve my issue.. Thanks in advance..
This is my Form
<form action="" id="suggestionsform" method="post">
<div class="form-group">
<label for="suggname">Name</label>
<input type="text" class="form-control" name="suggname" id="suggname" placeholder="Enter Your Name" required="required">
</div>
<div class="form-group">
<label for="suggmessage">Suggestion</label>
<textarea class="form-control" rows="4" name="suggmessage" id="suggmessage"
placeholder="Enter Your Suggestions"></textarea>
</div>
<button type="submit" class="btn btn-default" id="suggestions">Submit</button>
</form>
This is my ajax codeing
<script>
// Ajax post
$(document).ready(function() {
$("#suggestions").click(function(event) {
event.preventDefault();
var name = $("#suggname").val();
var suggestion = $("#suggmessage").val();
$.ajax({
type: "POST",
url: "<?php echo site_url('Helen/addSuggestion')?>",
dataType: 'json',
data: {name: name, suggestion: suggestion},
success: function(data) {
if (data=='true')
{
alert("Thank you for your Suggestion");
}
}
});
});
});
</script>
Controller Coding
public function addSuggestion()
{
$data=array(
'name' => $this->input->post('name'),
'messages' => $this->input->post('suggestion'),
'date' => now()
);
$data=$this->Helen_model->setSuggestion($data);
echo json_encode($data);
}
Model Coding
public function setSuggestion($data){
$this->db->insert('messages', $data);
return $this->db->insert_id();
}
You can achieve like this..
Model
Return true status if insert successful.
public function setSuggestion($data){
$res = $this->db->insert('messages', $data);
if($res){
$result = array('status'=>true,'message'=>'successful');
}
else
{
$result = array('status'=>false,'message'=>'failed');
}
return $result;
}
JS
Check status in success function
<script>
// Ajax post
$(document).ready(function() {
$("#suggestions").click(function(event) {
event.preventDefault();
var name = $("#suggname").val();
var suggestion = $("#suggmessage").val();
$.ajax({
type: "POST",
url: "<?php echo site_url('Helen/addSuggestion')?>",
dataType: 'json',
data: {name: name, suggestion: suggestion},
success: function(response) {
data = eval(response);//or data = JSON.parse(response)
if (data.status ===true)
{
alert("Thank you for your Suggestion");
}
}
});
});
});
</script>
Try to use echo '{"status": "success"}; on your controller response.
That i see on your script you are shown database response.

I can't update status by use the checked box

Please help i can't update the status by use the checked box.
When i selected the check box and select delete button, status will change to 'deleted' but now i can't update the data.
This is my view
<a href="javascript:;" id="delete" class="myButton" >Delete</a>
<div>
<input type="checkbox" class="cb_invoice" id="<?php echo $r->INVOICENUMBER;?>" value="<?php echo $r->INVOICENUMBER;?>">
</div>
This my script
<script>
$('#delete').click(function() {
var _url = "<?php echo site_url('commission/delete_invoices');?>";
var d_obj = $(".cb_invoice");
var d_val = [];
for (var i = 0; i < d_obj.length; i++){
if(d_obj[i].checked){
d_val.push(d_obj[i].value);
}
}
$.ajax({
url: _url,
data: {data: d_val},
type: 'post',
success: function(data) {
//console.log(data);
location.reload();
}
});
});
</script>
This my controller
function delete_invoices(){
$invoice = $this->input->post('data');
foreach ($invoice as $invoice) {
$this->m_commission->delete_invoice($invoice);
}
}
This is my model
function delete_invoice($invoice){
$this->db->update('salesinvoiceheader');
$this->db->set('STATUS','deleted');
$this->db->where('INVOICENUMBER', $invoice);
}
Change the order of update as follows in your modal:-
function delete_invoice($invoice){
$this->db->set('STATUS','deleted');
$this->db->where('INVOICENUMBER', $invoice);
$this->db->update('salesinvoiceheader');
}

how to get the dropdown selected value and send it to controller in codeigniter

am having the following code
view
<script>
$(document).ready(function()
{
$("#Login").click(function()
{
$("#message").html("");
var action = $("#loginform").attr('action');
var login_data = {
username: $("#txt_email").val(),
password: $("#txt_password").val(),
language: $("#language").val(),
is_ajax: 1
};
$.ajax(
{
type: "POST",
url: '<?php echo base_url();?>survey/login',
data: login_data,
success: function(response)
{
if(response == 'success')
{
$("#message").html("<span class='success'>You have logged in successfully!</span><p>Redirecting...</p>");
setTimeout(function() {
window.location.href = '<?php echo base_url();?>survey/communication_letter';
}, 2000);
}
else
{
$("#message").html("<span class='error'>OOPS! Authentication failed</span>");
}
}
});
return false;
});
});
</script>
</head>
<body>
<div id= "header">
<br/>
<p style="text-align:center; color:#8D0F1D;font-size:28px" >Work Environment Survey</p>
</div>
<div id= "bar" style="z-index:1">
<div id="logo" style="z-index:2">
</div>
</div>
<br/>
<br/>
<div id="homemain">
<!--div id="content-login"-->
<br/><br/><br/>
<form action="#" id="loginform" method="post">
<table border="0" align="center" cellpadding="5" cellspacing="10" >
<tr>
<td>Email Id </td>
<td><input type="text" id="txt_email" name="username" /></td>
</tr>
<tr>
<td>Password </td>
<td><input type="password" id="txt_password" name="password" /></td>
</tr>
<tr>
<td>Select Language</td>
<td><select style="width:215px" name="language" id = "language" ><option value="simplified">English with Simplified Chinese</option>
<option value="traditional">English with Traditional Chinese</option>
</select></td>
</tr>
</table>
<input type="image" id="Login" style="position:relative;left:120px" src="<?php echo base_url();?>images/login.png"/>
</form>
and the controller is as follows
public function login()
{
if(isset($_REQUEST['is_ajax']) && $_REQUEST['is_ajax']) {
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
echo $verify = $this->user_model->user_login($username, $password);
exit;
}
$this->load->view('login');
}
here how can i get the dropdown selected value depending on the language selected i need to open the next page. please someone help me please, thanks.
you can get that by using $_POST or $_REQUEST like you did for username
if(isset($_REQUEST['is_ajax']) && $_REQUEST['is_ajax']) {
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
$language= $_REQUEST['language'];
echo $verify = $this->user_model->user_login($username, $password);
exit;
}
I think this what you want, when user enter correct credential, user will be redirected to the page depending on the language selected by the user. You do not need to access language in your controller because you are redirecting from you login page,
you controller has to be
public function login()
{
if(isset($_REQUEST['is_ajax']) && $_REQUEST['is_ajax']) {
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
$verify = $this->user_model->user_login($username, $password);
if($verify){
echo 1;
}else{
echo 0;
}
}
}
you don't need to load view, as it is an ajax response.
$.ajax(
{
type: "POST",
url: '<?php echo base_url();?>survey/login',
data: login_data,
success: function(response)
{
if(response == 1)
{
$("#message").html("<span class='success'>You have logged in successfully!</span><p>Redirecting...</p>");
setTimeout(function() {
if($("#language").val() == "simplified"){
window.location.href = '<?php echo base_url();?>survey/communication_letter';
}else{
window.location.href = '<?php echo base_url();?>survey/trad_communication_letter'; }
}
}, 2000);
}
else
{
$("#message").html("<span class='error'>OOPS! Authentication failed</span>");
}
}
});
I hope this will help you. please check you development tool (chrome) or firebug (firefox) that your request is going and what is coming in response.
The correct way to grab the selected index value from drop down is
$('#language option:selected').val();
also in your controller you can verify the ajax request using
$this->input->is_ajax_request()

How do i fire validation message on Button click instead of Submit button

I have to execute a authentication process using JQuery. I have two textbox UserName and Password and two button are Login and Submit.
If i am clicking on Submit button then it will automatically fire validation that good and this functionality i have to implement on Login button click.
So how could i achieve automatic validation on button click?
Why i would like this:
Usin JQuery it is sending a request to the server with UserName and
Password during that time i will display Processing....
Then it will verify supplied value with database and return response
with Success or Failed then i will display either Success or Failed.
Here is the code snippet:
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#Html.ValidationSummary(true, "Login was unsuccessful. Please correct the errors and try again.")
#using (Html.BeginForm(null, null, FormMethod.Get, new { id = "Form1", name = "Form1" }))
{
<table>
<tr>
<td>
User Name
</td>
<td>#Html.TextBoxFor(u => u.UserName, new { id = "txtUser" }) #Html.ValidationMessageFor(u => u.UserName)
</td>
</tr>
<tr>
<td>
Password
</td>
<td>#Html.TextBoxFor(u => u.Password, new { id = "txtPassword" }) #Html.ValidationMessageFor(u => u.Password)
</td>
</tr>
<tr>
<td>
</td>
<td>
<input type="button" value="Login" onclick="checkAuthentication();" />
<input type="submit" value="Submit" />
</td>
</tr>
<tr>
<td colspan="2">
<div id="dvStatus" class="loginMessageStatus">
</div>
</td>
</tr>
</table>
}
<script language="javascript" type="text/javascript">
function getUserCredentials() {
var user = jQuery('#txtUserName').val();
var pass = jQuery('#txtPassword').val();
return { UserName: user, Password: pass };
}
function clearUserCredentials() {
jQuery('#txtUserName').val("");
jQuery('#txtPassword').val("");
jQuery('#txtUserName').focus();
}
function checkAuthentication() {
jQuery('#dvStatus').html("<div class='requestProcess'></div><div class='requestMessage'>Please wait...</div>")
var postData = getUserCredentials();
var ajaxResponse = $.ajax({
type: "post",
url: '#Url.Action("Index", "Login")',
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(postData),
success: function (result) {
var res = jQuery.parseJSON(result);
if (res.Success == true) {
jQuery('#dvStatus').html("<div class='requestSuccess'></div><div class='requestMessage'>Your are successfully logged in. Redirecting...</div>")
jQuery.doTimeout(100, redirectToPage);
}
else {
jQuery('#dvStatus').html("<div class='requestFailed'></div><div class='requestMessage'>Error: " + res.Message + ". <a href='javascript:void(0)' onclick='clearUserCredentials()'>Try Again</a></div>")
}
}
});
}
function redirectToPage() {
href = '#Url.Action("Index", "TabMaster")';
window.location.href = href;
}
Note:-
Validation completely work with Submit button
Verifying process completely work with Login button ( just i have to integrate validation with Login button)
you can do the validation using the onclick of the submit button with the following event handler:
Add an identifier to the button:
<input id="SubmitButton" type="submit" value="Submit" />
JavaScript:
$(document).ready(function(){
$("#SubmitButton").click(function(){
return checkAuthentication();
});
});
Change the Validation method to return whether it failed or not:
function checkAuthentication() {
var _user = jQuery.trim(jQuery('#txtUserName').val());
var _pass = jQuery.trim(jQuery('#txtPassword').val());
if (_user.length == 0 || _pass.length == 0) {
jQuery('#dvStatus').html("<div class='requestFailed'></div><div class='requestMessage'>User Name and Password are required!</div>")
return false;
}
else {
jQuery('#dvStatus').html("<div class='requestProcess'></div><div class='requestMessage'>Please wait...</div>")
var postData = getUserCredentials();
var ajaxResponse = $.ajax({
type: "post",
url: '#Url.Action("Index", "Login")',
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(postData),
success: function (result) {
var res = jQuery.parseJSON(result);
if (res.Success == true) {
jQuery('#dvStatus').html("<div class='requestSuccess'></div><div class='requestMessage'>Your are successfully logged in. Redirecting...</div>")
jQuery.doTimeout(100, redirectToPage);
}
else {
jQuery('#dvStatus').html("<div class='requestFailed'></div><div class='requestMessage'>Error: " + res.Message + ". <a href='javascript:void(0)' onclick='clearUserCredentials()'>Try Again</a></div>")
}
}
});
return true;
}
}
This should then stop the submit if the validation fails.
I have solved this one:
I have used only submit button
<input id="btnLogin" type="submit" value="Login" />
Following are the updated code
<script language="javascript" type="text/javascript">
$(document).ready(function () {
//$.preloadCssImages();
$("#btnLogin").click(function () {
if ($("#Form1").valid() == true) {
checkAuthentication();
return false;
}
});
});
function getUserCredentials() {
var user = jQuery('#txtUserName').val();
var pass = jQuery('#txtPassword').val();
return { UserName: user, Password: pass };
}
function clearUserCredentials() {
jQuery('#txtUserName').val("");
jQuery('#txtPassword').val("");
jQuery('#txtUserName').focus();
}
function checkAuthentication() {
jQuery('#dvStatus').html("<div class='requestProcess'></div><div class='requestMessage'>Please wait...</div>")
var postData = getUserCredentials();
var ajaxResponse = $.ajax({
type: "post",
url: '#Url.Action("Index", "Login")',
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(postData),
success: function (result) {
var res = jQuery.parseJSON(result);
if (res.Success == true) {
jQuery('#dvStatus').html("<div class='requestSuccess'></div><div class='requestMessage'>Your are successfully logged in. Redirecting...</div>")
jQuery.doTimeout(100, redirectToPage);
}
else {
jQuery('#dvStatus').html("<div class='requestFailed'></div><div class='requestMessage'>Error: " + res.Message + ". <a href='javascript:void(0)' onclick='clearUserCredentials()'>Try Again</a></div>")
}
}
});
}
function redirectToPage() {
href = '#Url.Action("Index", "TabMaster")';
window.location.href = href;
}
</script>

Resources