yii ajaxLink success and replaceWith - javascript

since three hours I don't found the error in jquery.
I try to refresh a div, after I've created a file
Here is my View
<?php
echo CHtml::ajaxLink('Neuen Export erstellen',
Yii::app()->createUrl('exporter/create' ),
array(
'data' => array(),
'dataType' => 'json',
'type' => 'POST',
'complete' => "js:function(html){
$('#export-grid').fadeOut().fadeIn();
}",
'success' => "js:function(html){
$('#export-grid').replaceWith();
}"
),
array(
'class' => 'c2a_gray alignright',
'style' => 'font-size: 12px',
)
);
?>
** My Controller **
public function actionCreate()
{
// createfile();...
// do some stuff
$this->renderPartial('//users//exporter//_tmo', true, true);
}
complete Option works in ajaxLink function very well
but if I put alert(html) inside complete I got "Object object"
I don't know how to update export-grid with the new content.
please help me!
thx!

Yes if you try to alert html then it will return Object.
Please try alert(html.responseText).

Related

AJAX pagination not loading in new posts (admin-ajax not found)

I have a custom post type built in WordPress named Knowledge.
Knowledge currently only has 4 posts in total. By default, 3 posts are shown, then on load more click, I want the last, 4th blog card to show.
However, currently, my AJAX request isn't succeeding, it gives me the /wp-admin/admin-ajax.php 403 (Forbidden) error. Similar questions stated that it might be related to security plugins. However, I have disabled any security related plugins (Jetpack) and the error still exists.
Here is my approach so far:
knowledge-listing.php
<?php
global $post;
$args = array(
'post_type' => 'knowledge',
'posts_per_page' => 3,
'post_status' => 'publish',
'orderby' => 'publish_date',
'order' => 'DESC'
);
$query = new WP_Query($args);
if ($query->have_posts()):
while ($query->have_posts()):
$query->the_post();
get_part('templates/snippets/knowledge-card', array(
'heading' => get_the_title() ,
'subheading' => get_the_excerpt() ,
'background' => wp_get_attachment_url(get_post_thumbnail_id($post->ID)) ,
));
endwhile;
wp_reset_postdata(); ?>
<div class="knowledgeListing__loadmore">
<a href="#" id="loadmore" class="button--loadmore" data-type="knowledge" data-max-num-pages="<?php echo $query->max_num_pages; ?>">
<?php echo _e('Load More', 'theme'); ?>
</a>
</div>
<?php
endif; ?>
loadmore.js
jQuery(function($){
$(document).ready(function(){
$("#loadmore").on('click', function (e) {
e.preventDefault();
var btn = $(this);
showNextItems(btn);
});
function showNextItems(btn) {
var max_num_pages = btn.data('max-num-pages');
var post_type = btn.data('type');
var button = btn,
data = {
'action':'loadmore',
'query': loadmore_params.posts,
'page' : loadmore_params.current_page,
// 'security' : loadmore_params.security,
// 'max_num_pages' : max_num_pages,
// 'post_type' : post_type
};
$.ajax({
url : loadmore_params.ajaxurl,
data : data,
type : 'POST',
beforeSend : function ( xhr ) {
button.text('Loading...');
},
success : function( data ){
if( data ) {
button.text( 'Load More' ).prev().before(data);
loadmore_params.current_page++;
$('.knowledgeListing__wrapper').find('.knowledgeCard').last().after( data );
if ( loadmore_params.current_page == max_num_pages ){
button.remove();
}
console.log("success");
} else {
button.remove();
}
},
error : function(error){
button.text( 'Load More' );
console.table("Data: " + data);
console.table("loadmore_params: " + loadmore_params);
// console.log(error);
}
});
}
});
});
The following two console.log's spit out [object Object]
console.table("Data: " + data);
console.table("loadmore_params: " + loadmore_params);
Unsure where things are going wrong?
Edit:
console.log("Data:", data) and console.log("loadmore_params:", loadmore_params); results below:
On further inspection, when trying to access the /wp-admin/admin-ajax.php url, I see a 0. When searching for this online, it has been suggested to use die(). However, when I've added die() to the end of knowledge-listing.php, it still shows me a 0.
Here is my localized script for reference:
global $wp_query;
wp_localize_script( 'theme', 'loadmore_params', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'posts' => json_encode( $wp_query->query_vars ),
'current_page' => get_query_var( 'paged' ) ? get_query_var('paged') : 1,
'max_page' => $wp_query->max_num_pages,
'security' => wp_create_nonce("load_more")
) );
And actions:
add_action('wp_ajax_loadmore', 'pagination_ajax_handler'); // wp_ajax_{action}
add_action('wp_ajax_nopriv_loadmore', 'pagination_ajax_handler'); // wp_ajax_nopriv_{action}
Just my 2 cents but "loadmore" as an action name is quite common and may be used by some other plugins/theme function. You should really consider switching to something namespaced like wp_ajax_mypluginname_loadmore.
That said, another common issue is that you perform the add_actions too late or maybe they never get hit by code before wp-admin-ajax does his thing.
Please be 100% you hit the add_actions BEFORE the code enter wp-admin-ajax.
To make a quick test you could move those line (included the function) in your child-theme functions.php file

Yii ajaxSubmitButton client-side validation issue

As you probably know, Yii does not perform client-side validation with CHtml::ajaxSubmitButton. So after a long time spending on google and stackoverflow, I found that I should use the following link
a-simple-way-to-get-yii-client-side-form-validation-run-when-submitting-by-ajax
Now, It can perform client-side validation. But, the success or complete ajax functions does not fire after validation.
Any Idea?
To be more familiar with topic, I put my codes here:
Yii::app()->clientScript->registerCoreScript('yii');
Yii::app()->clientScript->registerScript('Yii Fix',";$.yii.fix = {
ajaxSubmit : {
beforeSend : function(form) {
return function(xhr,opt) {
form = $(form);
$._data(form[0], 'events').submit[0].handler();
var he = form.data('hasError');
form.removeData('hasError');
return he===false;
}
},
afterValidate : function(form, data, hasError) {
$(form).data('hasError', hasError);
return true;
}
}
};",CclientScript::POS_HEAD);
My form:
$uniqid = uniqid();
$form = $this->beginWidget('CActiveForm', array(
'id' => 'pagescontents-add-new-contents'.$uniqid,
'htmlOptions' => array(
'class' => 'form-horizontal',
'role' => 'form'
),
'enableClientValidation' => true,
'enableAjaxValidation'=>true,
'clientOptions' => array(
'validateOnSubmit' => true,
'validateOnChange'=>false,
'afterValidate'=>'js:$.yii.fix.ajaxSubmit.afterValidate',
),
));
//The rest of code
...
//Ajax submit button
$button_uniqid = uniqid();
echo CHtml::ajaxSubmitButton(Messages::getMessage('ADD_NEW'), $this->createUrl('pagescontents/addPage/'), array(
'beforeSend' => '$.yii.fix.ajaxSubmit.beforeSend("#pagescontents-add-new-contents'.$uniqid.'")',
'type'=>'POST',
'success' => "js:function(data){
$('#page_modal').html('');
$('.modal-backdrop').remove();
$('#pageContents_list').html(data);
}",
),
array(
'class' => 'btn btn-primary',
// 'data-dismiss' => 'modal',
'id' => 'deletesubmit_' . $button_uniqid
)
);
I try your code and find that if you remove the line "'enableAjaxValidation'=>true," your code will work perfectly please check it and let me know that is work for you too or not.

how to call id of cmultifileupload in yii

in Cmultiplefileupload widget i want to call my own js function and want to track the id of the widget id
<script>
function inc_id(x)
{
alert(x);
}
</script>
$this->widget('CMultiFileUpload', array(
'name' => 'LeadRecommendations[docs_name][]',
'id'=>'LeadRecommendations_docs_name',
'model'=>$test,
'accept' => 'jpeg|jpg|gif|png|pdf|doc|docx|odt|txt|xlsx|xls|csv|zip', // useful for verifying files
//'duplicate' => 'Duplicate!', // useful, i think
'denied' => 'Invalid file type', // useful, i think
'remove'=>'[x]',
'options'=>array(
'afterFileSelect'=>'function(e, v, m){ inc_id(this.id) }',
),
but it gives the result undefined how could i get he id of this widget in my function

Cakephp Ajax, Using Js Helper to get value of a text field

guys this the code I am using to make a ajax request, its not the complete code just relevant stuff
<div class="container whiteFont">
<label>New Tag</label>
<?php echo $this->Form->input('tagValue'); ?>
<input id="tag-button" type="button" value="Add Tag"/>
<div id=tag></div>
<?php
//on button click sands request to controller and displays response data in chosen field
$this->Js->get('#tag-button')->event(
'click',
$this->Js->request(
array('controller' => 'tags', 'action' => 'add',(Here need help),$this->Form->value('Post.id')),
array(
'update' => '#tag',
'async' => true,
)
)
);
?>
Now the problem is, my actions takes in two parameters.
I can set the second one which is Post.id
but I am not able to get the value of text field which has id of 'tagValue'.
I have tried using just html input fields as well.
When I try to use Js->get here it doesnt work as well.
help me out please.
Thank you
$this->Js->get('#tag-button')->event(
'click',
$this->Js->request(
array('controller' => 'tags', 'action' => 'add',(Here need help),$this->Form->value('Post.id')),
array(
'update' => '#tag',
'async' => true,
'dataExpression'=>true,
'data'=> $this->Js->serializeForm(array(
'Post.id' => 1
))
use dataExpression and data to send parameters.
For more info: http://book.cakephp.org/2.0/en/views.html
Proper way to get all your form parameters passed:
$this->Js->get('#tag-button')->event(
'click',
$this->Js->request(
array('controller' => 'tags', 'action' => 'add',(Here need help),$this->Form->value('Post.id')),
array(
'update' => '#tag',
'async' => true,
'dataExpression'=>true,
'data'=> $this->Js->serializeForm(array(
'isForm' => true,
'inline' => true
))
))

Send data to controller with js helper

I'm trying to send some data to my controller with the Js helper like so:
view:
<?php
$this->Js->get('#FieldId')->event( //fieldId is a selectbox
'change',
$js->request(
array(
'controller'=>'users',
'action'=>'check'
),
array(
'update'=>'#result',
'data'=>'what should I put in here?'
)
)
);
?>
What should I put in data to send the value of the selected item of #fieldId and how can I us this data in my controller. The CakePHP documentation 'book' doesn't really explain much, and I'm not an expert either...
I found out that additional variables should be passed in that manner:
'data' => 'variableName=value'
So in the controller there is:
$this->params['form']['variableName']
There is also the possibility to eval some javascript values in 'data' but you have to set 'dataExpression' to true in the option array before.
I think this will help you.
<?php
$this->Js->get('#FieldId')->event('change', $this->Js->request(array(
'controller' => 'users',
'action' => 'check/DataName(view name)'
), array(
'update' => '#result',
'async' => true,
'method' => 'post',
'dataExpression' => true,
'data' => $this->Js->serializeForm(array(
'isForm' => true,
'inline' => true,
)),
)) );
?>

Categories

Resources