update status from active to inactive using codeigniter - ajax

Hi when i want to update my status using a button from inactive to active through ajax method so i have written some code i dont know wether it is right or wrong but status is not updating

This is sample code, This should work
Controller:
public function update_status(){
$status = $this->input->post('status');
$course_id = $this->input->post('id');
$this->CoursesModel->update_course_status($course_id,$status);
}
Model:
public function update_course_status($course_id,$status){
$data['status'] = $status;
$this->db->where('course_id', $course_id);
$this->db->update('courses',$data);
}
Script:
$(document).on('click','.status_checks',function()
{
var status = ($(this).hasClass("btn-success")) ? '1' : '0';
var msg = (status=='0')? 'Deactivate' : 'Activate';
if(confirm("Are you sure to "+ msg))
{
var current_element = $(this);
var id = $(current_element).attr('data');
url = "<?php echo base_url().'index.php/Dashboard/update_status'?>";
$.ajax({
type:"POST",
url: url,
data: {"id":id,"status":status},
success: function(data) {
// if you want reload the page
location.reload();
//if you want without reload
if(status == '1'){
current_element.removeClass('btn-success');
current_element.addClass('btn-danger');
current_element.html('Deactivate');
}else{
current_element.removeClass('btn-danger');
current_element.addClass('btn-success');
current_element.html('Activate');
}
} });
}
});
HTML:
<button type="button" class="status_checks btn <?php echo ($element->status == 1) ? "btn-danger" : "btn-success"; ?> "><?php echo ($element->status == 1) ? "Deactivate" : "Activate"; ?></button>

I guess you should put some info in $data like so
$data['status'] = $status;
$this->db->where('course_id', $course_id);
$this->db->update('courses', $data);
Hope it solves the problem !

Related

Cakephp 4 giving 403 error while using ajax

I am trying to implement cascading drop down box in cakephp 4 using ajax.
I'm getting an 403 error has tried many solutions from google and stack overflow from htaccess till syntax error and logical error can anyone please help trying since long.
Here is my code:
Add.php
<?php echo $this->Form->control('groups',['options' => $groups],array('id'=>'GroupId'));
echo $this->Form->input('user_id',array('id'=>'UsersId'));
?>
<?= $this->Form->button(__('Submit'),array('id'=>'post')) ?>
<?= $this->Form->end() ?>
<?php echo $this->Html->script('//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js');?>
<script type="text/javascript" >
$(document).ready(function(){
$("#groups").change(function(){
var deptid = $(this).val();
//var path="<?php echo $this->Url->webroot ?>/Users/getbygroup";
$.ajax({
url: '../Users/getbygroup',
type: 'POST',
data: deptid,
dataType: 'json',
cache: false,
contentType: false,
success:function(response){
var len = response.length;
$("#UserId").empty();
for( var i = 0; i<len; i++){
var id = response[i]['id'];
var name = response[i]['name'];
$("#UserId").append("<option value='"+id+"'>"+name+"</option>");
}
}
});
});
});
</script>
Add action in files controller:
public function add()
{
$this->loadModel('Users');
$this->loadModel('Groups');
$this->set('groups', $this->Groups->find('list'));
$result = $this->Users->find('all'); // returns query object
$data = $result->toArray(); // converts query object to key value array
$file = $this->Files->newEmptyEntity();
if ($this->request->is('post')) {
$file = $this->Files->patchEntity($file, $this->request->getData());
if ($this->Files->save($file)) {
$this->Flash->success(__('The file has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The file could not be saved. Please, try again.'));
}
$this->set(compact('file'));
}
getbygroup function in users controller:
public function getbygroup() {
$fname= $this->request->getData('deptid');
$this->viewbuilder()->layout = 'ajax';
$users = $this->Users->find('list', array(
'conditions' => array('Users.group_id' => $fname),
'recursive' => -1));
$this->set('users', $users);
}

Getting data by ajax in Codeigniter

I am adding record to database by ajax in CI , so i was trying to return the id of the new record but it's not working , the record has been added but no id is returned .(in ajax code am trying to alert the new record id but it's alerting undefined)
Below is the ajax code:
$.ajax({
type:'post',
url: baseURL+"admin/Products/add_product",
data:postData,
success:function(data){
alert(data[0].id);
$('#register_form')[0].reset();
} });
This is the controller,
notice that am returning id from create_product method and put it in get_by_id method, and then return result
if($id=$this->Products_model->create_product($data)){
$result = $this->Products_model->get_product_by_id($id);
return $result;
}
This is my model methods
public function create_product($data){
$query = $this->db->insert('products',$data);
if($query){
$id = $this->db->insert_id();
return $id;
}else{
return false;
}
}
//////////get_by_id_method
public function get_product_by_id($id){
$this->db->where($id,'id');
$query = $this->db->get('products');
if($query){
return $query->result();
}
}
Hope this will help You :
Your ajax should be like this :
$.ajax({
type:'post',
url: baseURL + "admin/Products/add_product",
data:postData,
success:function(data)
{
var response = JSON.parse(data);
alert(response.id);
$('#register_form')[0].reset();
}
});
Your controller should be like this :
$id = $this->Products_model->create_product($data);
if($id)
{
$result = $this->Products_model->get_product_by_id($id);
echo json_encode($result);
exit;
}
Your model method get_product_by_id should be like this :
public function get_product_by_id($id)
{
$this->db->where($id,'id');
$query = $this->db->get('products');
if($query->num_rows() > 0)
{
return $query->row();
}
}
You may need to echo a JSON with a proper Content-type in your Controller:
$result = [];
$id = $this->Products_model->create_product($data);
if ($id) {
$result = $this->Products_model->get_product_by_id($id);
}
header("Content-type: application/json");
echo json_encode($result);
So that the response can be an empty object or the query result.

Wordpress AJAX Login Not Redirecting After Successful Login

I have implemented the AJAX based log in functionality in my WP site as follows:
functions.php
function ajax_login_init(){
wp_register_script('ajax-login-script', get_template_directory_uri() . '/ajax-login-script.js', array('jquery') );
wp_enqueue_script('ajax-login-script');
wp_localize_script( 'ajax-login-script', 'ajax_login_object', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'redirecturl' => home_url(),
'loadingmessage' => __('Sending user info, please wait...')
));
// Enable the user with no privileges to run ajax_login() in AJAX
add_action( 'wp_ajax_nopriv_ajaxlogin', 'ajax_login' );
}
// Execute the action only if the user isn't logged in
if (!is_user_logged_in()) {
add_action('init', 'ajax_login_init');
}
function ajax_login(){
// First check the nonce, if it fails the function will break
check_ajax_referer( 'ajax-login-nonce', 'security' );
// Nonce is checked, get the POST data and sign user on
$info = array();
$info['user_login'] = $_POST['username'];
$info['user_password'] = $_POST['password'];
$info['remember'] = true;
$user_signon = wp_signon( $info, false );
if ( is_wp_error($user_signon) ){
echo json_encode(array('loggedin'=>false, 'message'=>__('Wrong username or password.')));
} else {
echo json_encode(array('loggedin'=>true, 'message'=>__('Login successful, redirecting...')));
}
die();
}
ajax-login-script.js
jQuery(document).ready(function() {
// Perform AJAX login on form submit
jQuery('form#login_form').on('submit', function(e){
jQuery('form#login_form p.login-status').show().text(ajax_login_object.loadingmessage);
jQuery.ajax({
type: 'POST',
dataType: 'json',
url: ajax_login_object.ajaxurl,
data: {
'action': 'ajaxlogin', //calls wp_ajax_nopriv_ajaxlogin
'username': jQuery('form#login_form #txtEmail').val(),
'password': jQuery('form#login_form #txtPassword').val(),
'security': jQuery('form#login_form #security').val() },
success: function(data){
jQuery('form#login_form p.login-status').text(data.message);
if (data.loggedin == true){
document.location.href = ajax_login_object.redirecturl;
}
}
});
e.preventDefault();
});
});
Now when I enter wrong credentials in my login popup, it successfully shows me the waiting message, and then error Wrong username or password.. But when I use correct credentials and press sign in, then it silently logs me in but never refreshes the page (actually it does try to refresh the page in the background, but since it is an ajax request, i can only see the refresh in console tab).
I want the ajax to refresh my current page from which the request has been sent.
I assume that the culprit could be this snippet:
$user_signon = wp_signon( $info, false );
if ( is_wp_error($user_signon) ){
echo json_encode(array('loggedin'=>false, 'message'=>__('Wrong username or password.')));
} else {
echo json_encode(array('loggedin'=>true, 'message'=>__('Login successful, redirecting...')));
}
When $user_signon = wp_signon( $info, false ); is called, it actually logs the user in and redirects the page (within AJAX), and never executes code further. Hence, I don't get the JSON encoded data in my AJAX success function (which is where I am actually trying to redirect the page using JavaScript).
Any help would be highly appreciated. Thanks
Did it another way. Used wp_check_password, wp_set_current_user and wp_set_auth_cookie functions to achieve the same goal.
function ajax_login(){
// First check the nonce, if it fails the function will break
check_ajax_referer( 'ajax-login-nonce', 'security' );
// Nonce is checked, get the POST data and sign user on
$info = array();
$info['user_login'] = $_POST['email'];
$info['user_password'] = $_POST['password'];
$info['remember'] = true;
$userdata = get_user_by('login', $info['user_login']);
$result = wp_check_password($info['user_password'], $userdata->data->user_pass, $userdata->data->ID);
if ( $result ) {
auto_login( $userdata );
echo json_encode(array('loggedin'=>true, 'message'=>__('Login successful, redirecting...')));
} else {
echo json_encode(array('loggedin'=>false, 'message'=>__('Wrong username or password.')));
}
die();
}
function auto_login( $user ) {
if ( !is_user_logged_in() ) {
$user_id = $user->data->ID;
$user_login = $user->data->user_login;
wp_set_current_user( $user_id, $user_login );
wp_set_auth_cookie( $user_id );
}
}
<form class="well form-inline" id="login">
<div id="message"></div>
<div id="loading" style="display:none;"></div>
<div class="rowmargin">
<h4>Login</h4>
</div>
<div class="rowmargin">
<input type="text" name="username" id="loginUsername" class="input-medium" placeholder="Username">
<input type="password" name="password" id="loginPassword" class="input-medium" placeholder="Password">
</div>
<a class="btn btn-primary" id="loginButton"><i class="icon-check icon-white"></i> Login</a>
</form>
jQuery(document).ready(function(){
jQuery('#loading').hide();
jQuery("#loginButton").click(function() {
jQuery('#message').hide().html('');
jQuery('#loading').hide();
var input_data = jQuery('#login').serialize();
var logUser = jQuery('#loginUsername').val();
var logPass = jQuery('#loginPassword').val();
if(logUser == '' && logPass != ''){ jQuery('#message').show().html('Your Username is empty!'); return false; }
if(logPass == '' && logUser != ''){ jQuery('#message').show().html('Your Password is empty!'); return false; }
if(logUser == '' && logPass == ''){ jQuery('#message').show().html('Your Username and Password is empty!'); return false; }
jQuery('#loading').show();
jQuery.ajax({
type: "POST",
url: "<?php echo site_url('wp-login.php','login_post'); ?>",
data: input_data,
success: function(msg) {
// login success. redirect users to some page.
jQuery(location).attr('href', '<?php echo home_url( '/thank-you/' ); ?>');
},
error: function(msg) {
// login error.
jQuery('#message').show();
jQuery('#message').html("<?php _e('Your login is not correct. Please try again.'); ?>");
jQuery('#loading').hide();
}
});
return false;
});
});

Wordpress ajax request returns 0 in my infinite scroll script

I'd like to implement a very customized infinite scroll. But that comes later, cause i'm already stuck at the ajax request. What's wrong with my code (i get alwas a '0' response even though i have die() in the php function and added nopriv ...)??
my header.php:
<script type="text/javascript">
var count = 2;
var total = <?php echo $wp_query->max_num_pages; ?>;
jQuery(window).scroll(function(){
if (jQuery(window).scrollTop() == jQuery(document).height() - jQuery(window).height()){
if (count > total){
return false;
}else{
loadArticle(count);
//viewsite();
}
count++;
}
});
function loadArticle(pageNumber) {
jQuery.ajax({
url: ajaxurl,
type:'POST',
data: {
action: 'ozinfinite_scroll',
page_no: pageNumber
},
success: function(html){
jQuery("#inf-cont-1").append(html);
}
});
return false;
}
</script>
functions.php:
function ozinfinite_scroll(){
// $loopFile = $_POST['loop_file'];
$paged = $_POST['page_no'];
$posts_per_page = get_option('posts_per_page');
# Load the posts
query_posts(array('paged' => $paged ));
get_template_part( 'contentoz', 'blog' );
die();
}
add_action('wp_ajax_ozinfinite_scroll', 'ozinfinite_scroll'); // for logged in user
add_action('wp_ajax_nopriv_ozinfinite_scroll', 'ozinfinite_scroll'); // if user not logged in
function add_ajaxurl_cdata_to_front(){ ?>
<script type="text/javascript"> //<![CDATA[
ajaxurl = '<?php echo admin_url( 'admin-ajax.php'); ?>';
//]]> </script>
<?php }
add_action( 'wp_head', 'add_ajaxurl_cdata_to_front', 1);
thanks for your help!!
According to the docs http://codex.wordpress.org/AJAX_in_Plugins
you should have something like
echo $someValue
before wp_die() or die()

CakePHP-2.4 : subcategories according to categories by ajax

I am trying to get subcategories according to categories by ajax.So I have sent data in controller by ajax get method like bellow code in add.ctp
$('document').ready(function(){
$( "#division" ).change(function() {
var value=$('#division').val();
$.get("<?php echo Router::url(array('controller'=>'userStoreSelections','action'=>'add'));?>",{list:value},function(data){
$('.districts').html(data);
alert(data);
});
});
});
In controller in find methods when I am writing bellow code It's working fine.
$madDistricts = $this->UserStoreSelection->MadDistricts->find('list',array(
'conditions'=>array('mad_divisions_id'=>3)
));
But when I give the value that I have sent by ajax it's not working.I have written like this
$madDistricts = $this->UserStoreSelection->MadDistricts->find('list',array(
'conditions'=>array('mad_divisions_id'=>"$list")
));
It showing the query like this
SELECT `MadDistricts`.`id`, `MadDistricts`.`name` FROM `store`.`mad_districts` AS `MadDistricts` WHERE `mad_divisions_id` IS NULL
After select categories nothing change in query.I have tested ajax code there is no problem to send value.
For more specific this is the add action code
public function add() {
if(isset($this->request->query['list'])){
$search = $this->request->query['list'];
echo $search;
}
else{
$search = '';
}
if ($this->request->is('post')) {
$this->UserStoreSelection->create();
if ($this->UserStoreSelection->save($this->request->data)) {
$this->Session->setFlash(__('The user store selection has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user store selection could not be saved. Please, try again.'));
}
}
$madDivisions = $this->UserStoreSelection->MadDivisions->find('list');
$madDistricts = $this->UserStoreSelection->MadDistricts->find('list',array(
'conditions'=>array('mad_divisions_id'=>"$list")
));
$madAreas = $this->UserStoreSelection->MadAreas->find('list');
$users = $this->UserStoreSelection->Users->find('list',array('fields' => array('id','username')));
$madStores = $this->UserStoreSelection->MadStores->find('list',array('fields' => array('id','store_name')));
$this->set(compact('madDivisions', 'madDistricts', 'madAreas', 'users','madStores'));
}
You need to change your add.ctp file code like as :
$('document').ready(function () {
$("#division").change(function () {
var value = $(this).val();
$.ajax({
url: '<?php echo Router::url(' / ',true);?>userStoreSelections/subcategories',
type: "POST",
dataType: 'json',
data: 'category=' + id,
success: function (res) {
var html = '<option>Sub Category</option>';
if (res.flage == true) {
html = res.data;
}
$('.districts').html(html);
}
});
});
});
Than create a function in your userStoreSelections for get sub categories as
public function subcategories() {
$response = array('flage' => false);
$madDistricts = $this->UserStoreSelection->MadDistricts->find('list', array(
'conditions' => array('mad_divisions_id' => $this->request->data['category'])
));
$options = "<option>Subcategories</option>";
if ($states) {
$response['flage'] = true;
foreach ($madDistricts as $id => $name) {
$options .= "<option value='" . $id . "'>" . $name . "</option>";
}
$response['data'] = $options;
}
echo json_encode($response);
exit;
}

Resources