Making an ajax call in wordpress, undefined variable - ajax

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();
}

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

Wordpress AJAX Form

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' ));

ReferenceError: ajax_object is not defined when loading Wordpress post via Ajax

I've been trying to implement the recommendation by #SagiveSEO in this thread:
Proper way to load a single post via Ajax?
The idea: click a button and load a post via AJAX. The idea being that you'll have a tree of buttons to allow people to navigate quickly to useful content.
Unfortunately, it fails.
In the console I get the message "ReferenceError: ajax_object is not defined" which refers to the line "$.post(ajax_object.ajaxurl..."
What am I doing wrong?
Here's my HTML:
<button class="get_project" data-postid="3300">PROJECT NAME</button>
<div class="postcontainer"></div>
Here's my Javascript:
jQuery(function($){
$('.get_project').click(function() {
var postid = $(this).data('postid'); // Amended by #dingo_d
$.post(ajax_object.ajaxurl, {
action: 'my_load_ajax_content ',
postid: postid
}, function(data) {
var $response = $(data);
var postdata = $response.filter('#postdata').html();
$('.postcontainer').html(postdata);
});
})
//alert( "hello world" );
});
and here is the php from my functions.php file:
function my_load_ajax_content () {
$pid = intval($_POST['post_id']);
$the_query = new WP_Query(array('p' => $pid));
if ($the_query->have_posts()) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
$data = '
<div class="post-container">
<div id="project-content">
<h1 class="entry-title">'.get_the_title().'</h1>
<div class="entry-content">'.get_the_content().'</div>
</div>
</div>
';
}
}
else {
echo '<div id="postdata">'.__('Didnt find anything', THEME_NAME).'</div>';
}
wp_reset_postdata();
echo '<div id="postdata">'.$data.'</div>';
}
// Next two lines corrected - thanks #dingo_d
add_action ( 'wp_ajax_my_load_ajax_content', 'my_load_ajax_content' );
add_action ( 'wp_ajax_nopriv_my_load_ajax_content', 'my_load_ajax_content' );
Also required in functions.php within the script enqueuing function:
wp_enqueue_script( 'myajaxpostloader', get_template_directory_uri().'/js/ajax.js', array( 'jquery' ), '1.0', true );
wp_localize_script( 'myajaxpostloader', 'ajax_object', array(
'ajaxurl' => admin_url( 'admin-ajax.php' )
));
(note that my Javascript is saved as /js/ajax.js where /js/ is a subdirectory of the Wordpress theme).
You didn't localize your ajax object. In Twenty fifteen theme you'd do it like this - in functions.php you'd put
wp_localize_script( 'twentyfifteen-script', 'ajax_object', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
));
Where your scripts are enqueued.
In your theme be sure to use proper handle - in stead of 'twentyfifteen-script' put the one where your ajax code is in. So if your ajax JavaScript is located in a file called custom.js, and you've enqueued that script with the handle custom_js, then you'd put
wp_localize_script( 'custom_js', 'ajax_object', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
));
After you've enqueued that script. All in all in your functions.php you'd put something like this:
add_action('after_setup_theme', 'mytheme_theme_setup');
if ( ! function_exists( 'mytheme_theme_setup' ) ){
function mytheme_theme_setup(){
add_action( 'wp_enqueue_scripts', 'mytheme_scripts');
}
}
if ( ! function_exists( 'mytheme_scripts' ) ){
function mytheme_scripts() {
wp_enqueue_script( 'custom_js', get_template_directory_uri().'/js/custom.js', array( 'jquery'), '1.0.0', true );
wp_localize_script( 'custom_js', 'ajax_object', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
));
}
}
Or at the very least look for such code and just place the localization there :)

Chained selects in Wordpress via AJAX

I need to make two chained select inputs (country, city) in WP.
(all is in locations taxonomy, country is a main category and city is a subcategory)
in first select i listed all countries:
$locations = get_terms( ‘locations’, array(
‘hide_empty’ => false,
‘parent’ => 0 ) );
In second select i need only the cities depend on selected country
(without page refresh/submit, so with AJAX)
I need passing selected value from first select to php variable:
$whichCountry = AJAX RESPONSE HERE
Listing second select:
$locations = get_terms( ‘locations’, array(
‘hide_empty’ => false,
‘parent’ => $whichCounty) );
Please help me how to achieve this
i make same code but its not enough:
JS:
(function ($) {
$(document).ready(function () {
$(‘#first_select’).on(‘change’, function(){
$.post(
PT_Ajax.ajaxurl,
{
// wp ajax action
action: ‘ajax-inputtitleSubmit’,
// vars
data: $(‘#first-select’).val(),
// send the nonce along with the request
nextNonce: PT_Ajax.nextNonce
},
function (response) {
console.log(response.data);
}
);
return false;
});
});
})(jQuery);
PHP:
add_action( ‘wp_enqueue_scripts’, ‘inputtitle_submit_scripts’ );
add_action( ‘wp_ajax_ajax-inputtitleSubmit’, ‘myajax_inputtitleSubmit_func’ );
add_action( ‘wp_ajax_nopriv_ajax-inputtitleSubmit’, ‘myajax_inputtitleSubmit_func’ );
function inputtitle_submit_scripts() {
wp_enqueue_script( ‘inputtitle_submit’, get_template_directory_uri() . ‘/assets/js/inputtitle_submit.js’, array( ‘jquery’ ) );
wp_localize_script( ‘inputtitle_submit’, ‘PT_Ajax’, array(
‘ajaxurl’ => admin_url( ‘admin-ajax.php’ ),
‘nextNonce’ => wp_create_nonce( ‘myajax-next-nonce’ )
)
);
}
function myajax_inputtitleSubmit_func() {
// check nonce
$nonce = $_POST[‘nextNonce’];
if ( ! wp_verify_nonce( $nonce, ‘myajax-next-nonce’ ) ) {
die ( ‘Busted!’ );
}
// generate the response
$response = json_encode( $_POST );
// response output
header( “Content-Type: application/json” );
$whichCountry = $response;
// IMPORTANT: don’t forget to “exit”
exit;
}
Functions.php
include_once(‘inputtitle_submit_inc.php’)

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.

Resources