jQuery load() internal server error with wordpress - javascript

I have this simple wordpress menu that I want to load in div element.
<?php
$menuParameters = array(
'theme_location' => 'sidebar-menu',
'container' => false,
'echo' => false,
'items_wrap' => '%3$s',
'depth' => 0,
);
echo strip_tags(wp_nav_menu( $menuParameters ), '<a>' );
?>
I'm using modernizr and jQuery load() to load the php file into the div element when a certain media query is detected.
jQuery(document).ready(function($){
if(Modernizr.mq('only all and (max-width:600px)')) {
$('#content-wrapper').removeClass('col-4-5');
$("#trending-Container").load( 'wordpress/wp-content/themes/test_theme/navbar-mobile.php' );
}
});
This works if just use some html or if just echo some string but when I use a wordpress function like above or something like the_title() I get a 500 internal server error.
Any ideas?

I suppose you should no directly access any file in your theme for security reasons.
Register your function in funcitons.php in your theme and then call that function_name as refereed over here enter link description here
jQuery(document).ready(function($) {
var data = {
action: 'my_action',
whatever: ajax_object.we_value // We pass php values differently!
};
// We can also pass the url value separately from ajaxurl for front end AJAX implementations
jQuery.post(ajax_object.ajax_url, data, function(response) {
alert('Got this from the server: ' + response);
});
});
and register your action in functions.php
<?php
add_action( 'admin_enqueue_scripts', 'my_enqueue' );
function my_enqueue($hook) {
if( 'index.php' != $hook ) return; // Only applies to dashboard panel
wp_enqueue_script( 'ajax-script', plugins_url( '/js/my_query.js', __FILE__ ), array('jquery'));
// in javascript, object properties are accessed as ajax_object.ajax_url, ajax_object.we_value
wp_localize_script( 'ajax-script', 'ajax_object',
array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'we_value' => 1234 ) );
}
// Same handler function...
add_action('wp_ajax_my_action', 'my_action_callback');
function my_action_callback() {
global $wpdb;
$whatever = intval( $_POST['whatever'] );
$whatever += 10;
echo $whatever;
die();
}

Related

Accessing query of query loop block from another block, gutenberg wordpress

I'm creating a custom block inside a plugin. It's a drop down selector of categories for posts. I'm simply trying to update the query of a query loop block on the same page. However I'm not sure how to access the query of the query loop block.
I've tried the above however getting the blockId of the block doesn't seem to be possible on the front end. Does anyone know how i can reference the query loop block from a front end js file?
plugin.php
function tapacode_selector_ajax_callback() {
$nonce = $_POST['nonce'];
if ( ! wp_verify_nonce( $nonce, 'wp-tapacode-nonce' ) ) {
die ( 'Busted!' );
}
$category = intval( $_POST['category']);
$query_args = array(
'cat' => $category
);
$query = new WP_Query( $query_args );
wp_send_json( $query->posts );
wp_die();
}
add_action( 'wp_ajax_tapacode_selector', 'tapacode_selector_ajax_callback' );
add_action( 'wp_ajax_nopriv_tapacode_selector', 'tapacode_selector_ajax_callback' );
add_action( 'wp_enqueue_scripts', 'my_enqueue' );
function my_enqueue() {
wp_register_script( 'ajax-selector-script', plugins_url( '/selector.js', __FILE__ ), array( 'wp-blocks', 'wp-editor', 'wp-element', 'jquery' ), '1.0', true );
wp_enqueue_script( 'ajax-selector-script' );
// in JavaScript, object properties are accessed as ajax_object.ajax_url, ajax_object.we_value
wp_localize_script( 'ajax-selector-script', 'ajax_object',
array(
'ajax_url' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce( 'wp-tapacode-nonce' )
) );
}
another plugin.php file
<p <?php echo get_block_wrapper_attributes(); ?>>
<?php wp_dropdown_categories(); ?>
</p>
selector.js
document.addEventListener('DOMContentLoaded', setupCategorySelector, false);
function setupCategorySelector() {
document.getElementById('cat').onchange = function () {
// if value is category id
if (this.value !== '-1') {
if (typeof wp !== 'undefined' && wp.data) {
const blockId = document.querySelector('.wp-block-tapacode-category-selector').getAttribute('data-block-id');
const queryBlock = wp.data.select('core/block-editor').getBlock(blockId);
queryBlock.setAttributes({ categories: this.value });
queryBlock.update();
}

How to pass PHP values to js script in Wordpress using AJAX

I have tried both wp_localize_script and wp_add_inline_script : it doesn't work the way I expect.
I have this in my plugin's PHP file (it is enqueued with wp_enqueue_scripts somewhere else but I don't need to write the code here right ?) :
wp_register_script(
'custom-profile-script',
"{$this->plugin_url}js/custom-profile-plugin.js",
array( 'jquery' ),
null,
false
);
wp_enqueue_script(
'custom-profile-script'
);
wp_localize_script(
'custom-profile-plugin',
'wp_ajax',
array(
'ajax_url' => admin_url( 'admin-ajax.php' ),
'ajaxnonce' => wp_create_nonce( 'ajax_post_validation' ),
'plugin_url' => "url"
)
);
wp_add_inline_script( 'custom-profile-plugin', 'const PHPVAR = ' . json_encode( array(
'plugin_url' => "url"
) ), 'before' );
And then, in my js file :
var data = {
action: 'custom_user_plugin_update_meta_rating_value',
security: wp_ajax.ajaxnonce
};
$.post(wp_ajax.ajax_url, data, function(result) {
console.log(wp_ajax);
console.log(PHPVAR.plugin_url);
});
The first console log (related to wp_localize_script) is an object that contains "ajax_url" and "ajax_nonce" with the right values, but "plugin_url" doesn't appear and is UNDEFINED when I call it using wp_ajax.plugin_url.
The second console log (related to wp_add_inline_script) tells me that PHPVAR is not defined...
What I don't understand is why the first two values are passed correctly using localize script, but not the third one and, furthermore, why wp_add_inline_script doesn't work.
The script needs to be registered in the footer for the PHP value to be passed, like this :
wp_register_script(
'custom-profile-script',
"{$this->plugin_url}js/custom-profile-plugin.js",
array( 'jquery' ),
null,
true // register script in the footer
);
Instead of :
wp_register_script(
'custom-profile-script',
"{$this->plugin_url}js/custom-profile-plugin.js",
array( 'jquery' ),
null,
false // default value of the wp_register_script function that registers script in header
);
You need to add wp_enqueue_script after wp_localize_script and also you add wrong handle to wp_localize_script check the below code.
wp_register_script(
'custom-profile-script',
"{$this->plugin_url}js/custom-profile-plugin.js",
array( 'jquery' ),
null,
true
);
wp_localize_script(
'custom-profile-script',
'wp_ajax',
array(
'ajax_url' => admin_url( 'admin-ajax.php' ),
'ajaxnonce' => wp_create_nonce( 'ajax_post_validation' ),
'plugin_url' => "url"
)
);
wp_enqueue_script(
'custom-profile-script'
);
var data = {
action: 'custom_user_plugin_update_meta_rating_value',
security: wp_ajax.ajaxnonce
};
$.post(wp_ajax.ajax_url, data, function(result) {
console.log(wp_ajax);
console.log(wp_ajax.plugin_url);
});

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

WP wp_ajax_function is not calling PHP function

I'm building a wordpress plugin for a cookie notice, i want the cookies to be created with PHP. And the button in the notice bar is supposed to run a php function, ajax is not really working with me right now.
My ajax request is being processed as far as i know, in the network tab it shows admin-ajax.php with status 200, but it just won't call the actual function.
this is my code
Main plugin file
function setAjaxCallbacks(){
add_action('wp_ajax_accepted', 'accepted');
add_action('wp_ajax_nopriv_accepted', 'accepted');
}
add_action('init', 'setAjaxCallbacks');
function accepted(){
die('test');
echo 'LOLALLES';
global $wpdb;
$whatever = intval( $_POST['whatever'] );
$whatever += 10;
echo $whatever;
wp_die('0 ', 400);
echo '<script>
alert("jhwgvbht ij")
</script>';
wp_die();
}
isset($_COOKIE['cookieBar']) or setCookieBar();
function setCookieBar()
{
if (!is_admin()){
add_action('wp_enqueue_scripts', 'enqueue_script_custom');
function enqueue_script_custom()
{
wp_enqueue_style('CookieBarStyle', plugin_dir_url(__FILE__) . 'css/styles.css');
wp_enqueue_script('ajax-script', plugins_url('/js/my_query.js', __FILE__), array('jquery'));
wp_localize_script('ajax-script', 'ajax_object',
array('ajaxurl2' => 'https://wordpressjip.jmulder.dt2/wp-admin/admin-ajax.php', 'we_value' => 1234));
wp_print_scripts('ajax-script');
}
?>
<div class="cookieBar" id="cookieBar" style="display: block">
<p align="center"></p>
<button id="submitCookies" class="submitCookies" name="accepted">Accepteer</button>
</div>
<?php
}
}
my_query.js
jQuery(document).ready(function ($) {
jQuery(".submitCookies").click(function (event) {
event.preventDefault();
jQuery.ajax({
url: ajax_object.ajaxurl2,
type: 'POST',
data: {
action: 'accepted',
whatever: 1234
},
succes: function (response) {
return response;
}
})
})
});
Function named "accepted" is inside another function, that's why it is not working. You need to learn how ajax is working in wordpress. Please go through following link. It will teach you how to use ajax in wordpress https://medium.com/techcompose/how-to-use-ajax-precisely-in-wordpress-custom-themes-dc61616720a8
Following code may help you:
<?php
function setAjaxCallbacks()
{
add_action('wp_ajax_accepted', 'accepted');
add_action('wp_ajax_nopriv_accepted', 'accepted');
}
add_action('init', 'setAjaxCallbacks');
function accepted()
{
echo 'LOLALLES';
global $wpdb;
$whatever = intval($_POST['whatever']);
$whatever += 10;
echo $whatever;
exit;
}
add_action('wp_enqueue_scripts', 'enqueue_script_custom');
function enqueue_script_custom()
{
wp_enqueue_style('CookieBarStyle', plugin_dir_url(__FILE__) . 'css/styles.css');
wp_enqueue_script('ajax-script', plugins_url('/js/my_query.js', __FILE__), array('jquery'));
wp_localize_script(
'ajax-script',
'ajax_object',
array('ajaxurl2' => 'https://wordpressjip.jmulder.dt2/wp-admin/admin-ajax.php', 'we_value' => 1234)
);
wp_print_scripts('ajax-script');
}
function setCookieBar()
{
if (!is_admin()) {
if (! isset($_COOKIE['cookieBar'])) {
?>
<div class="cookieBar" id="cookieBar" style="display: block">
<p align="center"></p>
<button id="submitCookies" class="submitCookies" name="accepted">Accepteer</button>
</div>
<?php
}
}
}
add_action( 'wp_footer', 'setCookieBar' );

wordpress passing variable to javascript

I'm trying to pass a variable to a javascript file from a plugin. Here is my plugin code:
<?php
/**
* #package JS Test
* #version 1.0
*/
/*
Plugin Name: JS Test
Description: JS Test.
*/
add_action('init', 'my_init');
add_action( 'wp', 'test_js' );
function my_init() {
wp_enqueue_script( 'jquery' );
}
function test_js() {
wp_register_script ('testjs', plugins_url('jstest.js', __FILE__));
wp_enqueue_script ('testjs');
$my_arr = array('my array',
'name' => 'Test',
);
$my_json_str = json_encode($my_arr);
$params = array(
'my_arr' => $my_json_str,
);
wp_enqueue_script('my-java-script');
wp_localize_script('my-java-script', 'php_params', $params);
}
Here is the jstest.js file:
jQuery(document).ready(function() {
alert ('test');
var my_json_str = php_params.my_arr.replace(/"/g, '"');
var my_php_arr = jQuery.parseJSON(my_json_str);
alert(php_params);
});
What I get is this error in JavaScript:
ReferenceError: php_params is not defined
Anybody see what I'm doing wrong?
You Don't need to enqueue a script just for your localized parameters you can use your testjs for that, here is a quick plugin i cooked up to test:
<?php
/*
Plugin Name: PHP to JS
Plugin URI: http://en.bainternet.info
Description: wordpress passing variable to javascript
http://stackoverflow.com/questions/12761904/wordpress-passing-variable-to-javascript
Version: 1.0
Author: Bainternet
Author URI: http://en.bainternet.info
*/
add_action('init', 'my_init');
add_action( 'wp', 'test_js' );
function my_init() {
/wp_enqueue_script( 'jquery' );
}
function test_js() {
wp_register_script ('testjs', plugins_url('jstest.js', __FILE__));
wp_enqueue_script ('testjs');
$my_arr = array('my array',
'name' => 'Test',
);
$my_json_str = json_encode($my_arr);
$params = array(
'my_arr' => $my_json_str,
);
wp_localize_script('testjs', 'php_params', $params);
}
add_action('wp_footer','footertestjs');
function footertestjs(){
?>
<script>
jQuery(document).ready(function() {
alert ('test');
var my_json_str = php_params.my_arr.replace(/"/g, '"');
var my_php_arr = jQuery.parseJSON(my_json_str);
alert(php_params);
});
</script>
<?php
}
as you can see here the wp_localized_script uses the same script as you enqueue and not a fake script.

Categories

Resources