Wordpress AJAX Form - ajax

I have the oddest issue and I have a feeling I am missing something easy. I am trying to process a form through Wordpress and AJAX. But when pointed to the right url it gives me a 400 error. I have a feeling I have my action setup wrong or something. The processing function is a method in the same class called process_registration_form.
//JS
$('#user-registration').submit(function(e){
e.preventDefault();
var registrationForm = jQuery(this).serialize();
jQuery.ajax({
action: 'tribe_process_registration_form',
type: "POST",
url: tribe_process_user_registration.ajaxurl,
data: registrationForm,
success: function(data) {
console.log(data);
//jQuery("#feedback").html(data);
}
});
});
//PHP
wp_enqueue_script( 'tribe_process_user_registration', plugin_dir_url( __FILE__ ) . 'js/tribe-product-gifting-public.js', array( 'jquery' ) );
wp_localize_script( 'tribe_process_user_registration', 'tribe_process_user_registration', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
add_action('wp_ajax_tribe_process_user_registration', array($this,'process_registration_form'));
add_action('wp_ajax_nopriv_tribe_process_user_registration', array($this,'process_registration_form'));

I don't thing there is any issue in the above code but might be i have missing something. so here is the way i can do my ajax call.
The enqueue the script file with wp function.
wp_enqueue_script( 'pc-frontend-js', plugins_url( 'Scripts/front-end.js', __FILE__ ), false );
wp_localize_script( 'pc-frontend-js', 'pc_var_arguments', array(
'woopb_nonce' => wp_create_nonce('woopb_nonce'),
'ajax_url' => admin_url('admin-ajax.php')
)
);
Ajax call
function callback_function(quantity) {
var condition = 'ajax_callback_condition';
jQuery.ajax({
url: pc_var_arguments.ajax_url,
type : 'post',
dataType: 'json',
data : {
action : 'ajax_callback_action',
condition :condition,
data : data,
},
success : function(response) {
console.log(response);
}
});
};
Hooks for ajax
add_action( 'wp_ajax_ajax_callback_action', array($this,'callback_function' ));
add_action( 'wp_ajax_nopriv_ajax_callback_action', array($this,'callback_function' ));

Related

Wordpress Ajax returning full html of same page

Am trying to run Ajax call in my Woocommerce checkout page, but am always getting the full html of same page return.
add_action( 'wp_enqueue_scripts', 'theme_scripts' );
function theme_scripts() {
wp_enqueue_script( 'theme_scripts', get_stylesheet_directory_uri() . '/assets/js/theme.js', array(), '1.0.0', true );
wp_localize_script( 'theme_scripts', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
Am calling the ajax when address is changed
add_action('wp_footer','my_custom_ajax');
function my_custom_ajax(){
?>
<script>
(function($){
$( document.body ).on( 'updated_checkout', function(){
$.ajax({
url: my_ajax_object.ajaxurl,
data: {
'action':'example_ajax_request',
},
success:function(data) {
console.log(data);
},
error: function(errorThrown){
console.log(errorThrown);
}
});
});
})(jQuery);
</script>
<?php
}
The example Function
function example_ajax_request() {
echo 'ok';
wp_send_json_success( 'It works' );
die();
}
add_action( 'wp_ajax_example_ajax_request', 'example_ajax_request' );
add_action( 'wp_ajax_nopriv_example_ajax_request', 'example_ajax_request' );
Fixed by using 'nonce'
refer to this sample project

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

Making an ajax call in wordpress, undefined variable

Im trying to open Wordpress posts in a modal popup by following this guide : https://premium.wpmudev.org/blog/load-posts-ajax/
However when I try I get an error saying : Uncaught ReferenceError: modalpost is not defined
I have this code in my functions file so far :
wp_localize_script( 'modal-post', 'modalpost', array(
'ajaxurl' => admin_url( 'modal-post.php' )
));
And this code in my js file :
(function($) {
$(document).on( 'click', '.itemtoshow', function( event ) {
event.preventDefault();
$.ajax({
url: modalpost.ajaxurl,
type: 'post',
data: {
action: 'modal-post'
},
success: function( result ) {
alert( result );
}
})
});
})(jQuery);
Any ideas what Im doing wrong ?
Many thanks in advance,
Scott
You have make some changes in your code like
wp_localize_script( 'modal_post', 'modalpost', array(
'ajaxurl' => admin_url( 'modal-post.php' )
));
to
wp_localize_script( 'modal-post', 'modalpost', array(
'ajaxurl' => admin_url( 'admin-ajax.php' )
));
Then in your jQuery
(function($) {
$(document).on( 'click', '.itemtoshow', function( event ) {
event.preventDefault();
$.ajax({
url: modalpost.ajaxurl,
type: 'post',
data: {
//action: 'modal-post' change function name here
action: 'modal_post'
},
success: function( result ) {
alert( result );
}
})
});
})(jQuery);
Now code response function in your plugin or functions.php file like
// Add hooks for handle ajax request
add_action( 'wp_ajax_nopriv_modal_post', 'model_post' );
add_action( 'wp_ajax_ajax_modal_post', 'model_post' );
function model_post(){
// Your modal code goes here
// echo your modal code and then exit / die
die();
}

wordpress adding plugin for ajax

i am new to wordress. trying to test creating a plugin to combine my js and ajax for a module. I did the following:
[Not sure if i need to add anything in admin-ajax.php.]
created my new plugin under wp-content/pluging/test-plugin
created 2 files: test.php and test.js
test.php content as the following:
/**
* Plugin Name: Test
*/
add_action("wp_ajax_my_test", "my_test");
add_action("wp_ajax_nopriv_my_test", "my_test");
function my_test()
{
echo "in ajax";
}
add_action( 'init', 'test_script_enqueuer' );
function test_script_enqueuer() {
wp_register_script( "test", WP_PLUGIN_URL.'/my_plugin/test.js', array('jquery') );
wp_localize_script( 'test', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'test');
}
test.js code as the following:
$(document).ready(function()
{
console.log('in js!');
$('#testDiv').on('click', '#test', function()
{
console.log('clicked!');
jQuery.ajax(
{
type: 'POST',
url: myAjax.ajaxurl,
data:
{
action: 'my_test'
},
dataType: 'json',
cache: false,
success: function(response)
{
alert(response);
},
error: function(xhr, textStatus, errorThrown)
{
alert('error');
}
});
})
});
Note that I can't even see the "in js!" message in my console.
Change
add_action( 'init', 'test_script_enqueuer' );
to
add_action("wp_enqueue_scripts", "test_script_enqueuer");
But first, try to echoes something from your php file. If nothing happened your file isn't call.
Try then tell me.

get_posts query returning empty array over Ajax when not logged in

I am having trouble in getting WordPress ajax working when not logged in. My get_posts query returns the correct posts when logged in. The Ajax is called from the front end when the user clicks onto an author. The author ID is passed in as a parameter through the Ajax function.
I have set up the admin_url and localized the script that the js is called from
function ajax_scripts()
{
wp_localize_script( 'meet_the_team_js', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ), 'imgurl' => plugins_url( 'img' , __FILE__ )) );
}
add_action( 'wp_enqueue_scripts', 'ajax_scripts' );
I have then added the wp_ajax (logged in users) and wp_ajax_nopriv (anon users) actions within the if is_admin() statement which I found on the wordpress documentation.
if ( is_admin() ) {
add_action( 'wp_ajax_nopriv_employee_recent_posts_ajax', 'employee_recent_posts_ajax' );
add_action( 'wp_ajax_employee_recent_posts_ajax', 'employee_recent_posts_ajax' );
}
This is the employee recent posts ajax function
function employee_recent_posts_ajax($atts)
{
$html = get_employee_recent_posts();
die($html);
}
The full get_employee_recent_posts function is too long to post. However here is the get_posts query that is causing the problem. Note that the $userid and $catid variables contain the correct data when the user is not logged in.
$authorposts = get_posts(array('author'=>$userid, 'posts_per_page' => 2, 'order' => 'DESC', 'category' =>$catid));
If any one has any insight or ideas on how this could be fixed it would be greatly appreciated!
Thanks!
EDIT: Including part of the ajax request code.
jQuery.ajax({
crossDomain: true,
type: 'GET',
url: MyAjax.ajaxurl,
data: {
'action': 'employee_recent_posts_ajax',
'userid': userid
},

Resources