controller not sending data back to ajax request codeigniter - ajax

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");
}
}
});
}

Related

Delete record with out page refresh in codeigniter is not working

Hi all i am trying to delete my record from datatable with out page refresh in codeigniter i have used ajax i don't know where i have done mistake its not deleting the record
Below is the my view:
<tbody>
<?php
if (!empty($employees)) {
foreach ($employees as $emp) {
?>
<tr>
<td><?php echo $emp->emp_name; ?></td>
<td><?php echo $emp->salary; ?></td>
<td class='text-center'>
<button type="submit" class="btn btn-info btn-xs confirmation" name="login"><i class='fas fa-edit'></i></button>
</td>
<td class='text-center'>
<button type="submit" onClick="return ConfirmDelete()" class="btn btn-danger btn-xs confirmation empdelete" id="<?php echo $emp->id;?>"><i class='fas fa-times'></i></button>
</td>
</tr>
<?php
}
}
?>
</tbody>
<script>
$(document).ready(function(){
$(".empdelete").click(function(e){
alert();
e.preventDefault();
$.ajax({
alert();
type: "POST",
url: "<?=site_url('Employee/delete');?>",
cache: false,
data: {id:$(this).attr("id")}, // since, you need to delete post of particular id
success: function(data) {
if (data){
alert("Success");
} else {
alert("ERROR");
}
return false;
}
});
});
});
</script>
Here is the my controller:
function delete()
{
$id = $this->input->post('id'); // get the post data
$empdelete=$this->Emp_model->delete($id);
if($empdelete){
echo true;
} else {
echo false;
}
}
Here is my model's method delete:
function delete($id)
{
$sql = "DELETE FROM employees WHERE id=?";
return $this->db->query($sql,array($id));
}
Can any one help me how can i do that with out page refresh i want to delete my record.
Thanks in advance.
Try this:
$(document).ready(function () {
function ConfirmDelete() {
var x = confirm("Are you sure you want to delete?");
if (x)
return true;
else
return false;
}
$(".empdelete").click(function (e) {
var obj = $(this);
e.preventDefault();
//alert(); what's this do?
if (ConfirmDelete() == false) {
return false;
}
$.ajax({
//alert(); this can't go here
type: "POST",
url: "<?php echo site_url('Employee/delete'); ?>",
cache: false,
data: {id: $(this).attr("id")},
success: function (data) {
console.log('ajax returned: ');
console.log(data);
if (data) {
obj.closest('tr').remove();
alert("Success");
} else {
alert("ERROR");
}
return false;
}
});
});
});
and remove HTML onClick:
<button type="submit" class="btn btn-danger btn-xs confirmation empdelete" id="<?php echo $emp->id;?>"><i class='fas fa-times'></i></button>
Hope this will help you :
Your button should be like this :
<button type="button" onClick="return ConfirmDelete(this)" class="btn btn-danger btn-xs confirmation empdelete" data-id="<?=$emp->id;?>"><i class='fas fa-times'></i></button>
Your ajax code should be like this :
function ConfirmDelete(obj)
{
var x = confirm("Are you sure you want to delete?");
if (x == true)
{
var id = $(obj).data('id');
alert(id);
if (id != '')
{
//do you ajax here
$.ajax({
type: "POST",
url: "<php echo site_url('Employee/delete'); ?>",
cache: false,
data: {'id': id},
success: function (data) {
console.log('ajax returned: ');
console.log(data);
if (data) {
alert("Success");
} else {
alert("ERROR");
}
return false;
}
});
}
}
else
{
return false;
}
}
Your controller should be like this :
function delete()
{
$id = $this->input->post('id'); // get the post data
$empdelete = $this->Emp_model->delete($id);
if($empdelete)
{
echo true;
} else
{
echo false;
}
exit;
}
Your delete method should be like this :
function delete($id)
{
$this->db->where('id',$id);
$this->db->delete('employees');
return $this->db->affected_rows();
}

my ajax not giving result in 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

Submit form within bootstrap modal using ajax and codeigniter without page change

I am trying to submit a form within a bootstrap modal using ajax. And my form is successfully submitted, but the success statements within ajax are not executed. The page is redirected to a blank page saying {"msg":"ok"}.
I am pasting the code from controller and view. Please help.
Controller
$update_profile_details = $this->userp_m->edit_profile_m($uname,$uemail,$data1,$new_email);
if($update_profile_details == true)
{
$status['msg'] = 'ok';
}
else
{
$status['msg'] = 'err';
}
echo json_encode ($status);
View
$(document).ready(function()
{
$("#myForm").submit(function(e)
{
e.preventDefault();
var reg = /^[A-Z0-9._%+-]+#([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
var name = $('#inputName').val();
var email = $('#inputEmail').val();
if (name.trim() == '') {
alert('Please enter your name.');
$('#inputName').focus();
return false;
} else if (email.trim() == '') {
alert('Please enter your email.');
$('#inputEmail').focus();
return false;
} else if (email.trim() != '' && !reg.test(email)) {
alert('Please enter valid email.');
$('#inputEmail').focus();
return false;
} else {
var fd = new FormData(this);
$.ajax({
type: 'POST',
url: $('#myForm').attr('action'),
dataType: "json",
data: $('#myform').serialize(), fd,
contentType: false,
cache: false,
processData:false,
beforeSend: function()
{
$('.submitBtn').attr("disabled", "disabled");
$('.modal-body').css('opacity', '.5');
},
success: function(status)
{
alert(status);
if (status.msg == 'ok') {
$('#inputName').val('');
$('#inputEmail').val('');
$('.statusMsg').html('<span style="color:green;">Changes have been saved successfully.</p>');
} else
{
$('.statusMsg').html('<span style="color:red;">Some problem occurred, please try again.</span>');
}
$('.submitBtn').removeAttr("disabled");
$('.modal-body').css('opacity', '');
},
error: function(status)
{
alert("Some error, please try again");
}
});
}
});
HTML
<form id="myform" method="post" enctype="multipart/form-data" action="<?php echo site_url('User/user_index_c/edit_profile_c'); ?>">
<label>Full Name : </label>
<input class="name_styling" type="text" placeholder="Enter name" id="inputName" name="uname">
<label>Email Id : </label>
<input class="email_styling" type="email" placeholder="Enter email" id="inputEmail" name="new_email">
<div class="controls">
<label>Profile Photo : </label>
<input name="file1" type="file" id="image_file" />
<img id="blah" class="logoupload" src="#" alt="your image" />
<span class="filename"></span>
</div>
<center><input class="submitBtn" id="submit" type="submit" value="Save Changes" name="submit" ></center>
</form>
Instead of function you have to write jquery code like below.
Remove function submitContactForm(e){}
Add $(document).on('submit', '#myform', function(e) { })
$(document).on('submit', '#myform', function(e) {
e.preventDefault();
var reg = /^[A-Z0-9._%+-]+#([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
var name = $('#inputName').val();
var email = $('#inputEmail').val();
if (name.trim() == '') {
alert('Please enter your name.');
$('#inputName').focus();
return false;
} else if (email.trim() == '') {
alert('Please enter your email.');
$('#inputEmail').focus();
return false;
} else if (email.trim() != '' && !reg.test(email)) {
alert('Please enter valid email.');
$('#inputEmail').focus();
return false;
} else {
$('.submitBtn').prop("disabled", true);
$('.modal-body').css('opacity', '.5');
var myFormData = new FormData();
e.preventDefault();
var inputs = $('#myForm input[type="file"]');
$.each(inputs, function(obj, v) {
var file = v.files[0];
var filename = $(v).attr("data-filename");
var name = $(v).attr("name");
myFormData.append(name, file, filename);
});
var inputs = $('#myForm input[type="text"],input[type="email"]');
$.each(inputs, function(obj, v) {
var name = $(v).attr("name");
var value = $(v).val();
myFormData.append(name, value);
});
var xhr = new XMLHttpRequest;
xhr.open('POST', '<?php echo base_url(); ?>index.php/User/user_index_c/edit_profile_c/', true);
xhr.send(myFormData);
xhr.onload = function() {
if (xhr.readyState === xhr.DONE) {
if (xhr.status === 200) {
$('#inputName').val('');
$('#inputEmail').val('');
$('.statusMsg').html('<span style="color:green;">Changes have been saved successfully.</p>');
$('.submitBtn').removeAttr("disabled");
$('.modal-body').css('opacity', '');
}
}
};
}
});
Let me know if it not works.
try this: in your file.js:
$(document).ready(function () {
$('#submit').click(function () {
var name= $("#inputName").val();
var mail = $("#inputEmail").val();
var img = $("#image_file").val();
$.post("User/user_index_c/edit_profile_c", {send_name:name,send_mail:mail, send_igm:img},
function (data) {
if (data.trim() != "ok") {
alert('error');
}
else{
//action for "success" exemple: alert("send with success!"); and insert a code for clean fields
}
});
});
});
in your controller's method:
$uname = $this->input->post("send_name");
$uemail = $this->input->post("send_mail");
$new_email = $this->input->post("send_igm");
$update_profile_details = $this->userp_m->edit_profile_m($uname,$uemail,$data1,$new_email);
if($update_profile_details == true){
echo 'ok';
}
else
{
echo 'err';
}
I hope I have helped

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.

Form submission using AJAX and handling response in Wordpress Website

I have a wordpress website. I have made a contact form and it is POSTed by AJAX.
Here's the code:
<script type="text/javascript">
jQuery(document).ready(function(){
$("#error_box").hide();
$('#contact_form').submit(function(e){
// prevent the form from submitting normally
e.preventDefault();
var na=$("#1").val();
var email2=$("#2").val();
var subject2 = $("#3").val();
var message2 = $("#4").val();
var mydata = "pn2="+na+"&email="+email2+"&subject="+subject2+"&msg="+message2;
alert(mydata);
$("#contact_form").css({"opacity":"0.1"});
$.ajax ({
type: 'POST',
url: $(this).attr.action, // Relative paths work fine
data: mydata,
success: function(){
$("#contact_form").css({"opacity":"1"});
$('#error_box').fadeIn('fast').css({"height": "auto"});
}
});
});
});
</script>
When the form is submitted, I want the error box (#error_box) to display a message according to the data submitted, for example if one of the fields is empty it should display an error, or display a success message if the processing is successful and the form has been mailed. Is there any way I can do this?
[UPDATE]
Here's my contact-form.php file(the action)
<?php if(isset($_POST['pn2']) && isset($_POST['email']) && isset($_POST['subject']) && isset($_POST['msg']))
{
if(empty($_POST['pn2']) || empty($_POST['email']) || empty($_POST['subject']) || empty($_POST['msg'])){
echo 'EMPTY ERROR';
}
else
{
$name = $_POST['pn2'];
$email = $_POST['email'];
$subj = $_POST['subject'];
$msg = $_POST['msg'];
$to = "ankushverma61#gmail.com";
$mail_cont = "FROM: $person_name. \n Email: $email. \n Msg: $msg";
echo "success";
mail($recipient, $subj, $mail_cont) or die("UNABLE TO SEND!!!");
}
}
?>
Form submission using Ajax call
Contact Form
<form action="#" id="contactForm" method="post">
<input class="require" type="text" placeholder="First Name" name="firstName">
<span class="fieldError"></span>
<input class="require" type="text" placeholder="Last Name" name="lastName">
<span class="fieldError"></span>
.
.
.
<input type="submit" value="Submit">
</form>
client side validation with ajax call
jQuery('#contactForm').submit(ajaxSubmit);
function ajaxSubmit(){
var newContactForm = jQuery(this).serialize();
var flag = 0;
jQuery('.require', '#contactForm').each(function(){
var inputVal = jQuery(this).val();
if(jQuery.trim(inputVal) === ""){
flag = 1;
jQuery(this).next().html("Can't be blank");
jQuery(this).next().show();
}
else{
jQuery(this).next().hide();
}
});
if(flag){
return false;
}
jQuery.ajax({
type:"POST",
url: "/wp-admin/admin-ajax.php?action=contactForm",
data: newContactForm,
success:function(data){
jQuery(':input','#contactForm')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
jQuery("#feedback").html(data);
jQuery("#feedback").fadeOut(10000);
},
error: function(errorThrown){
alert(errorThrown);
}
});
return false;
}
store form data in db and send mail
add the following code in functions.php
wp_enqueue_script('jquery');
add_action('wp_ajax_addContactForm', 'addContactForm');
add_action('wp_ajax_nopriv_addContactForm', 'addContactForm');
function addContactForm(){
global $wpdb;
$first_name = $_POST['firstName']; $last_name = $_POST['lastName'];
$email = $_POST['email'];
.
.
.
if($wpdb->insert('table_name',array(
'first_name' => $first_name,
'last_name' => $last_name,
'email' => $email,
.
.
.
))===FALSE){
echo "Error";
}
else {
$headers = 'From: xyz <xyz#xyz.com>';
$subject = "Thank you";
$body = "<p>Thank you</p><p>.........</p>";
wp_mail( $email, $subject, $body, $headers);
echo "<div class='success'>Thank you for filling out your information, we will be in contact shortly.</div>";
}
exit;
}
You should use:
$.ajax ({
type: 'POST',
url: $(this).attr.action,
data: mydata,
success: function(response) { // here you receive response from you serverside
$("#contact_form").css({"opacity":"1"});
$('#error_box').html(response).fadeIn('fast').css({"height": "auto"});
}
});
Your server action url: $(this).attr.action, should return message which be inserted in #error_box
First create form like this
<p class="register-message"></p>
<form action="#" method="POST" name="testregister" class="register-form">
<fieldset>
<label><i class="fa fa-file-text-o"></i> Register Form</label>
<input type="text" name="firstname" placeholder="Username" id="firstname">
<p id="firstname-error" style="display:none">Firstname Must be Enter</p>
<input type="email" name="email" placeholder="Email address" id="email">
<p id="email-error" style="display:none">Email Must Be Enter</p>
<input type="submit" class="button" id="test" value="Register">
</fieldset>
</form>
then bind the click and send ajax call
<script type="text/javascript">
jQuery('#test').on('click', function(e) {
e.preventDefault();
var firstname = jQuery('#firstname').val();
var email = jQuery('#email').val();
if (firstname == "") {
jQuery('#firstname-error').show();
return false;
} else {
jQuery('#firstname-error').hide();
}
if (email == "") {
jQuery('#email-error').show();
return false;
} else {
jQuery('#email-error').hide();
}
jQuery.ajax({
type: "POST",
dataType: 'json',
url: "<?php echo admin_url('admin-ajax.php'); ?>",
data: {
action: "test", // redirect function in function.php
firstname: firstname,
email: email
},
success: function(results) {
//console.log(results);
if (results == "1") {
jQuery('.register-message').text("Email already exist");
} else {
jQuery('.register-message').text("Register successfu");
}
},
error: function(results) {}
});
});
</script>
In function.php add the below code to insert data in table
<?php
//
add_action('wp_ajax_test', 'test', 0);
add_action('wp_ajax_nopriv_test', 'test');
function test()
{
$firstname = stripcslashes($_POST['firstname']);
$email = stripcslashes($_POST['email']);
global $wpdb;
$q = $wpdb->prepare("SELECT * FROM wp_test WHERE email='" . $email . "' ");
$res = $wpdb->get_results($q);
if (count($res) > 0) {
echo "1";
} else {
$user_data = array(
'firstname' => $firstname,
'email' => $email
);
$tablename = $wpdb->prefix . 'test';
$user_id = $wpdb->insert($tablename, $user_data);
echo "0";
}
die;
}

Resources