Using infinite scroll AJAX load more with URL search parameter - ajax

I have an infinite scroll working on my site. It works perfectly well on category pages, e.g.
example.com/example
However, it doesn't work when I try to use it on a search page, e.g.
example.com/example//?search=true&gender=female
I know I need to pass more parameters to the AJAX call, I'm just not sure how. The shortcode is like so...
do_shortcode('[talent taxonomy="'.$_GET['params']['taxonomy'].'" term="'.$_GET['params']['term'].'" page="'.$_GET['params']['page'].'" per_page="'.$_GET['params']['per_page'].'"]');
And the AJAX data:
var ajax_data = {
page:1,
taxonomy:"'.$a['taxonomy'].'",
term:"'.$a['term'].'",
per_page:"'.$a['per_page'].'",
max_pages: '.$my_query->max_num_pages.'
};
UPDATE: Here's the talent function called in functions.php:
function talent_func( $atts ) {
$a = shortcode_atts( array(
'term' => false,
'taxonomy' => false,
'per_page' => 4,
'page' => 1,
'gender' => 1,
'orderby' => 1,
), $atts );
Here is the AJAX:
jQuery.ajax({
url: "/wp-admin/admin-ajax.php",
dataType: 'html',
data: {
'action':'talent_ajax',
'params': ajax_data,
'option':orderby
},

Related

select2 js empty value on load in select option

I have implemented select2js in my project, In few cases when i load my page, an empty value is appending to my select input box. Can anyone help me out, what is the issue,
I have added a image of it and My code is
{!! Form::select('searchSkillTools[]',[],(isset($skillToolXref) && $skillToolXref!='')?$skillToolXref:'', array('autocomplete' => 'off', 'class' => 'chosen-select','multiple'=>'multiple', 'id' => 'searchSkillTools-'.$randomId, 'placeholder' => '' ,'style' => 'height: auto !important')) !!}
$('#searchSkillTools-{{$randomId}}').select2({
ajax: {
url: skillToolUrl,
dataType: 'json',
method:'get',
delay: 250,//delay in response
data: function (data) {
return {
search: data.term //search term
};
},
/*option to transform the data returned by response into the format expected by Select2*/
processResults: function (response) {
return {
results:response
};
},
cache: true
}
});
This way will fix the bug:
(isset($skillToolXref) && $skillToolXref!='')?$skillToolXref:null

Yii1: CGridView link ajax request shows 400 Bad Request

I am working on Yii 1 application. In my application, there is a CGridView where there is a link, which also fires an ajax request on onclick event. I am sending id as parameter. But the ajax return 400 Bad Request error. Please help me in this matter.
Here is the Gridview:
<h3>Civil Cases</h3>
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'notifications-grid',
'dataProvider'=>$dataProvider_civil,
'summaryText' => false,
'columns'=>array(
array(
'name' => 'case_id',
'type' => 'raw',
'value' => 'CHtml::link(CHtml::encode($data->case_id),array("civilcases/view","id"=>$data->case_id), array("onclick"=>"js:readNotification($data->id)"))'
),
array(
'name' => 'caseno',
'type' => 'raw',
'value' => 'CHtml::link(CHtml::encode($data->caseno),array("civilcases/view","id"=>$data->case_id), array("onclick"=>"js:readNotification($data->id)"))'
),
'date_filing',
'next_date',
'panel_lawyer_id',
),
));
?>
here is the script:
<script>
var readNotification = function(id) {
console.log("button clicked with ID: "+id); //getting id here
$.ajax({
type:'POST',
url:'<?php echo Yii::app()->createUrl("notifications/readNotification");?>',
data: {id: id}
});
};
</script>
here is the controller:
public function actionReadNotification(){
echo $_POST['id'];
}
added readNotification function to the accessRules. When clicking on the link new page is loading but ajax request shows error.
Try adding the csrf token inside your data with your ajax request.
<script>
var readNotification = function(id) {
console.log("button clicked with ID: "+id); //getting id here
$.ajax({
type:'POST',
url:'<?php echo Yii::app()->createUrl("notifications/readNotification");?>',
data: {id: id,<?=
Yii::app()->request->csrfTokenName?>:<?=Yii::app()->request->csrfToken?>,}
});
};
</script>
You can also disable the csrftoken by adding the below in the beforeAction()
public function beforeAction($action) {
if($action->id=='readnotification'){
$this->enableCsrfValidation = false;
}
return parent::beforeAction($action);
}
but this is not recommended way of doing the work.
EDIT
i mistakenly added Yii::$app->request instead of Yii::app()->request as the first one is for Yii2 and not for Yii1 please change it to
<?=Yii::app()->request->csrfTokenName?>:<?=Yii::app()->request->csrfToken?>
and make sure you have the request component with the following configurations
'components'=>array(
.
.
.
'request'=>array(
'enableCookieValidation'=>true,
'enableCsrfValidation'=>true,
'csrfTokenName'=>'_my-token',
),
Note : you can change the _my-token to any other name you like

CanĀ“t add products to CodeIgniter Cart from another view

I am using codeigniter 2.2.2 with HMVC and a custom session library
I have two views I'll call them V1.php and V2.php for simplicity
and in each view I have a product that can be added to the cart via ajax when you click on the button:
<button class="add-to-cart" id="123" type="button" class="btn btn-fefault cart">
both V1.php and V2.php are sending product details to a controller cart.php to the method add() via ajax
and here is the ajax call in both V1.php and V2.php
$(".add-to-cart").click(function()
{
var target_url = '<?php echo(base_url()."cart/add") ; ?>';
var prod_id = $(this).attr("id");
var qty = 1;
// prepare the data to be sent
var ProductData = {product_id:prod_id,quantity:qty};
$.ajax(
{
url : target_url,
type: "POST",
data : ProductData,
success: function(data)
{
cart = JSON && JSON.parse(data) || $.parseJSON(data);
$("#cart_num").html("( " + cart.num_of_items + " )");
},
error: function(jqXHR, textStatus, errorThrown)
{
$("#cart_notice").show();
$("#cart_notice").html('<pre><code class="prettyprint">AJAX Request Failed<br/> textStatus='+textStatus+', errorThrown='+errorThrown+'</code></pre>');
}
});
// prevent default
return false;
});
and here is the controller cart.php
public function add()
{
$product_id = $this->input->post('product_id');
$quantity = $this->input->post('quantity');
// prepare the array for the cart
$data = array(
'id' => $product_id,
'qty' => $quantity,
'price' => 39.95,
'name' => 'T-Shirt',
'options' => array('Size' => 'L', 'Color' => 'Red')
);
// insert the array in the cart
$cart_flag = $this->cart->insert($data);
//$cart_flag returns false if something went wrong
//$cart_flag returns an id if everything is ok
// prepare the array for the ajax callback function
$cart = array(
'num_of_items' => $this->cart->total_items(),
'total_price' => $this->cart->total()
);
echo json_encode($cart);
}
thanks to debugging tools I could see that :
1.when I add the product from V1.php everything is fine ($cart_flag returns an id)
but
2.when I add the product from V2.php it doesn't add anything ($cart_flag returns FALSE ) although $data is the same in both cases
what I'm I doing wrong ?
the answer was casting, it really gave me a hard time but at last I found it,
the $data looked the same but the type was not
this fixes the problem
$data = array(
'id' => (int)$product_id,
'qty' => (int)$quantity,
'price' => 39.95,
'name' => 'T-Shirt',
'options' => array('Size' => 'L', 'Color' => 'Red')
);
hope this helps someone else with the same issue

Need JSON to pass values to AJAX from specific content type fields

Im new to PHP.
I'd like to build a module and i need json to pass specific content type fields.
Im trying with this but i dont know how to deal with callback function.
here is my ajax in .js
$.ajax({
type: 'GET',
url: '/mappy/ajax/poi',
data: {
nid: nid
},
dataType: 'json',
success: function(data){
alert(data)
}
});
})
here is my php in .module
function mappy_menu() {
$items = array();
$items['/mappy/ajax/poi'] = array(
'title' => 'Mappy Pois',
'page callback' => 'mappy_get',
'access arguments' => array('access content'),
'type' => MENU_CALLBACK,
);
return $items;
}
function mpapy_get() {
$nid = $_GET('nid');
$title = field_get_items('node', $node, 'field_title');
$result = json_encode(
db_query("SELECT nid,title FROM {node}", $nid)
);
drupal_json_output($result);
print $result;
}
Many thanks for advice.
Once you get the JSON response you need to convert it to a javascript array. For that, you can do:
var javaArray = $.parseJSON(data);
Now you can retrieve the data, using code like javaArray['key1']['key2'], etc.
.js
$.ajax({
type: 'GET',
// Do not use slash at the beginning, use Drupal.settings.basePath instead
url: Drupal.settings.basePath + 'mappy/ajax/poi',
data: {
nid: nid
},
dataType: 'json',
success: function(data) {
alert(data)
}
});
.module
function mappy_menu() {
$items = array();
// Never use slash at the beginning in hook_menu
$items['mappy/ajax/poi'] = array(
'title' => 'Mappy Pois',
'page callback' => 'mappy_get',
'access arguments' => array('access content'),
'type' => MENU_CALLBACK,
);
return $items;
}
function mappy_get() {
$node = node_load($_GET('nid'));
// Or equivalent
/* $node = db_select('node', 'n')
->fields('n', array('nid', 'title'))
->condition('n.nid', $_GET('nid')))
->execute()
->fetchAll(); */
$values = array(
'nid' => $node->nid,
'title' => $node->title
);
#$result = json_encode(
# db_query("SELECT nid,title FROM {node}", $nid)
#);
// drupal_json_output already print the value
// print $result;
drupal_json_output($values);
drupal_exit();
}

Concatenate multiple fields to display in autocomplete using AJAX in cakephp

currently my autocomplete works in displaying the first name of the user, but I want to concatenate the first name, last name and etc. How do I achieve this in the following code?
<script type="text/javascript">
$(function() {
$(".suggest").autocomplete({
source: function( request, response ) {
$.ajax({
url: '<?php echo $this->Html->url(array('controller' => 'searches', 'action' => 'suggestUser')); ?>',
dataType: "json",
data: {
//request.term is the value of the current textbox.
term: request.term
},
success: function( data ) {
response( $.map( data, function( item ) {
return {
label: item.User.firstName,
value: item.User.firstName
}
}));
}
});
},
minLength : 1
});
});
In my controller, the following codes below is my logic to search for that field.
function suggestUser() {
if (isset($_GET["term"])) {
$term = $_GET["term"];
$result = $this->User->find('all', array(
'conditions' => array(
'User.firstName LIKE' => $term . '%'
),
'fields' => array(
'firstName'
)
));
if ($term) {
$this->set('results', $result);
$this->view = 'Json';
$this->set('json', 'results');
}
}
}
http://book.cakephp.org/view/1588/virtualFields
It is really simple I realised. I managed to resolve it.
label: item.User.firstName + " " + item.User.lastName,
value: item.User.firstName + " " + item.User.lastName
You also need to append the lastName field in.
'fields' => array(
'firstName',
'lastName',
)

Resources