I am new to codeigniter and I am trying some ajax functionalities with it. Following ajax-codeigniter , my view is
<?php
$set_price_range_500_1500 = array(
"name"=>"price_range",
"value" => "500-1500",
"id" => "pr_500_1500"
);
?>
<?php echo form_checkbox($set_price_range_500_1500); ?>
<?php echo lang('price_range_500_1500'); ?>
And the jquery resides in ci\themes\default\assets\js\:
$(document).ready(function(){
$("#pr_500_1500").click(function(){
var range = $("pr_500_1500").val();
$.post(
'/index.php/ajax/getPricerangeProducts',
{'range' : range },
function( result )
{
if( result )
{
alert( result ) ;
}
}
);
});
});
And the controller ajax residing in ci\controllers\ :
<?php
class ajax extends CI_Controller
{
function __construct()
{
parent::__contruct();
}
function getPricerangeProducts()
{
echo 'hello';
}
}
But instead of alerting hello, it alerts the wampserver homepage !
Change this and try:
$.post(
'<?=base_url()?>/index.php/ajax/getPricerangeProducts',
{'range' : range },
function( result )
{
if( result )
{
alert( result ) ;
}
}
);
Related
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);
}
I recently added an Ajax-powered load more button that loads additional blog posts to my wordpress site. I used the tutorial listed here: https://rudrastyh.com/wordpress/load-more-posts-ajax.html, and it works, but I've ran into another problem.
I have a session variable that counts the current post number. I show 10 posts per page and the counter works for the initial 10. Then I call the next 10 with ajax and instead of counting to 11, 12, 13 etc, it goes back to 1. There's clearly a problem with passing the end value (10) from the template, to the ajax handler in functions. Anyone know what could be wrong? Everything works if I don't use ajax - it's really frustrating.
Template PHP
<?php $_SESSION['the_counter'] = 0; ?>
<?php
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$args = array(
'posts_per_page' => 10,
'paged' => $paged
);
$my_query = new WP_Query($args);
if($my_query->have_posts()): while($my_query->have_posts()) : $my_query->the_post();
get_template_part( 'template-parts/post/content', get_post_format() );
endwhile;
else:
get_template_part( 'no-results', 'home' );
endif;
if ( $my_query->max_num_pages > 1 ){
echo '</a><div class="misha_loadmore">More posts</div>';
}?>
</div>
<script>var posts_myajax = '<?php echo json_encode( $my_query->query_vars ) ?>',
current_page_myajax = 1,
max_page_myajax = <?php echo $my_query->max_num_pages ?>
</script>
<script src="/loadmore.js"></script>
<?php $my_query = null;
wp_reset_postdata();?>
Ajax Handler in functions.php
function misha_loadmore_ajax_handler(){
$args = json_decode( stripslashes( $_POST['query'] ), true );
$args['paged'] = $_POST['page'] + 1; // we need next page to be loaded
$args['post_status'] = 'publish';
query_posts( $args );
if( have_posts() ) :
// run the loop
while( have_posts() ): the_post();
// look into your theme code how the posts are inserted, but you can use your own HTML of course
// do you remember? - my example is adapted for Twenty Seventeen theme
get_template_part( 'template-parts/post/content', get_post_format() );
// for the test purposes comment the line above and uncomment the below one
// the_title();
endwhile;
endif;
die; }
add_action('wp_ajax_loadmore', 'misha_loadmore_ajax_handler');
add_action('wp_ajax_nopriv_loadmore', 'misha_loadmore_ajax_handler');
Load More JS
jQuery(function($){
$('.misha_loadmore').click(function(){
var button = $(this),
data = {
'action': 'loadmore',
'query': misha_loadmore_params.posts, // that's how we get params from wp_localize_script() function
'page' : misha_loadmore_params.current_page
};
$.ajax({
url : misha_loadmore_params.ajaxurl, // AJAX handler
data : data,
type : 'POST',
beforeSend : function ( xhr ) {
button.text('Loading...'); // change the button text, you can also add a preloader image
},
success : function( data ){
if( data ) {
button.text( 'More posts' ).prev().before(data); // insert new posts
misha_loadmore_params.current_page++;
if ( misha_loadmore_params.current_page == misha_loadmore_params.max_page )
button.remove(); // if last page, remove the button
// you can also fire the "post-load" event here if you use a plugin that requires it
// $( document.body ).trigger( 'post-load' );
} else {
button.remove(); // if no data, remove the button as well
}
}
});
});});
And this is the session code I have on the top of my blog post content template file. It increments the count by 1 for every post.
$counter = $_SESSION['the_counter'];
$counter++;
$_SESSION['the_counter'] = $counter;
At the bottom of the file, I include:
echo insert_counter($the_counter);
At a glance, I'm betting sessions aren't being set. Try adding this to your functions.php file.
add_action('init', function() {
if (!session_id()) {
session_start();
});
This will ensure that sessions are loading on every page. It's worth mentioning that sessions aren't the best way to persist data. I would recommend replacing the session with a cookie.
The new product gallery in Woocommerce is great, but unfortunately I can't get it to work outside the single product template page.
I'm using ajax to load in products in a container on my front page. The ajax call displays the product page: echo do_shortcode('[product_page id="' . $post_id . '"]');. The markup for the gallery is correct, but the .woocommerce-product-gallery container is marked with opacity: 0; and none of the scripts for the gallery is loaded.
How can I implement the gallery functionality with the ajax call and get it working?
Full ajax call:
JQuery
$('.product-modal-toggle').on('click',function(){
var theId = $(this).data('product-id');
var plagg = $(this).data('plagg');
var outfitEnkeltPlaggContainer = $('.outfit-enkelt-plagg');
var parentOutfit = $(this).closest('.outfit').attr('id');
var outfitDescendantContainer = $('#' + parentOutfit + ' .outfit-enkelt-plagg');
$.post('wp-admin/admin-ajax.php', {
action:'my_get_posts',
post_id: theId
}, function(data) {
console.log(data);
outfitDescendantContainer.html(data);
});
});
PHP
/*
** Get Woocommerce Products with Ajax.
** Display Product inside outfit container
*/
function my_get_posts_return() {
global $post;
$post_id = intval(isset($_POST['post_id']) ? $_POST['post_id'] : 0);
if ($post_id > 0) {
$the_query = new WP_query(array('p' => $post_id, 'post_type' => 'product'));
if ($the_query->have_posts()) {
while ($the_query->have_posts()) : $the_query->the_post();
$product = wc_get_product($post_id);
?>
<button class="close-plagg" type="button" name="close-plagg">
<img src="<?php echo get_template_directory_uri(); ?>/library/images/close.svg" alt="Close plagg">
</button>
<?php
echo do_shortcode('[product_page id="' . $post_id . '"]');
// wc_get_template_part( 'content', 'single-product' );
endwhile;
} else {
echo "There were no posts found";
}
}
wp_die();
}
add_action('wp_ajax_my_get_posts', 'my_get_posts_return');
add_action('wp_ajax_nopriv_my_get_posts', 'my_get_posts_return');
PHP
You have to enqueue the scripts of the gallery on your home page :
add_action( 'wp_enqueue_scripts', function(){
if( is_front_page() ){
wp_enqueue_script('zoom');
wp_enqueue_script('flexslider');
wp_enqueue_script('photoswipe-ui-default');
}
});
JS
In the success function of your $.postyou have to call the script :
$( '.woocommerce-product-gallery', data ).each( function() {
$( this ).wc_product_gallery();
} );
Hope this helps
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;
}
I would like to remove the product in the woocommerce cart using ajax without click the link.
If you have encounter this kind of functionality, please help us.
add_action( 'wp_footer', 'add_js_to_wp_wcommerce');
function add_js_to_wp_wcommerce(){ ?>
<script type="text/javascript">
jQuery('.remove-product').click(function(){
var product_id = jQuery(this).attr("data-product_id");
jQuery.ajax({
type: 'POST',
dataType: 'json',
url: "/wp-admin/admin-ajax.php",
data: { action: "product_remove",
product_id: product_id
},success: function(data){
console.log(data);
}
});
return false;
});
</script>
<?php }
add_action( 'wp_ajax_product_remove', 'product_remove' );
add_action( 'wp_ajax_nopriv_product_remove', 'product_remove' );
function product_remove() {
global $wpdb, $woocommerce;
session_start();
foreach ($woocommerce->cart->get_cart() as $cart_item_key => $cart_item){
if($cart_item['product_id'] == $_POST['product_id'] ){
// Remove product in the cart using cart_item_key.
$woocommerce->cart->get_remove_url($cart_item_key);
}
}
print_r($woocommerce->cart->get_cart());
//echo json_encode(array('status' => 0));
exit();
}
you could use the WC_Cart set_quantity method
And do as this in your php:
$cart = WC()->instance()->cart;
$id = $_POST['product_id'];
$cart_id = $cart->generate_cart_id($id);
$cart_item_id = $cart->find_product_in_cart($cart_id);
if($cart_item_id){
$cart->set_quantity($cart_item_id,0);
}
use this :
$cart = $woocommerce->cart;
foreach ($woocommerce->cart->get_cart() as $cart_item_key => $cart_item){
if($cart_item['product_id'] == $_POST['product_id'] ){
// Remove product in the cart using cart_item_key.
$cart->remove_cart_item($cart_item_key);
}
}
Try this one :
foreach ( $woocommerce->cart->cart_contents as $cart_item_key => $cart_item ) {
if($cart_item['product_id'] == $product_id){
unset($cartdetails->cart_contents[$cart_item_key]);
}
}