Cannot Get AJAX To Load - php

Here is HTML Nav:
<ul class="sub-menu side-nav page-sidebar child-pages">
<li class="menu-item menu-item-type-post_type menu-item-object-post menu-item-9045" data-id="105"><span class="menu-image-title">History</span></li>
<li class="menu-item menu-item-type-post_type menu-item-object-post menu-item-9046" data-id="185"><span class="menu-image-title">Strategic Plan</span></li>
<li class="menu-item menu-item-type-post_type menu-item-object-post menu-item-9047" data-id="183"><span class="menu-image-title">Financial Statements</span></li>
</ul>
Here is my PHP function:
add_action ( 'wp_ajax_nopriv_load-content', 'my_load_ajax_content' );
add_action ( 'wp_ajax_load-content', 'my_load_ajax_content' );
function my_load_ajax_content(){
$post_id = $_POST[ 'post_id' ];
$post = get_post( $post_id, OBJECT);
$response = array( apply_filters( 'the_content', $post->post_title ), apply_filters( 'the_content', $post->post_content ) );
echo '<div class="entry-header"><h1 class="entry-title">'.$response[0].'</h1></div><div class="entry-content">'.$response[1].'</div>';
die(1);
}
wp_enqueue_script( 'my-ajax-request', get_template_directory_uri() . '/js/ajax.js', array( 'jquery' ) );
wp_localize_script( 'my-ajax-request', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
Here's what's in ajax.js:
jQuery(document).ready(function($) {
$(window).on('load',Foundation.utils.throttle(function(e){
if($('.current-menu-item > .sub-menu')){
$('#sidebar-b').append($('.current-menu-item > .sub-menu').addClass('side-nav page-sidebar child-pages'));
$("#sidebar-b .menu-item a:not(.pdf)").each(function(){
var link_text = $(this).children('.menu-image-title').html();
$(this).attr('href','#'+link_text);
});
}
},300));
$("#sidebar-b .menu-item .menu-image-title-after").click(function(e) {
$("#loading-animation").show();
var post_id = $(this).parent("li").attr("data-id");
var ajaxURL = MyAjax.ajaxurl;
$.ajax({
type: 'POST',
url: ajaxURL,
data: {"action":"load-content",post_id:post_id},
success: function(response){
$("#content > article").html(response);
$("#loading-animation").hide();
return false;
}
});
});
});
Additionally, when checking the <head> I noticed that my ajax.js script is not even loading even though it's being enqueued in my PHP function. Any ideas on what I'm doing wrong? I've scoured Google for the last 3 hours and haven't found an exact answer.

1, you have to make sure that your script is triggered at the right element
2, you should change : "action":"load-content" to action: 'load-content' ( remove the double quote at action )

You need to enqueue the scripts by using below mentioned way, then it will be hooked with wp_enqueue_scripts hook and load properly :
function load_scripts() {
wp_enqueue_script( 'my-ajax-request', get_template_directory_uri() . '/js/ajax.js', array( 'jquery' ) );
wp_localize_script( 'my-ajax-request', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'load_scripts' );
Hope it helps you.

Ultimately, after days and days of trial and error, I FINALLY got AJAX working! The secret was making my ajax.js an anonymous function.
(function($){
$(document).on('click','.ajax-click',function(e){
e.preventDefault();
var post_id = $(this).parent().attr('data-id');
var ajaxURL = MyAjax.ajaxurl;
$.ajax({
cache: false,
type: "POST",
url: ajaxURL,
data:{ action: "load_content", post_id: post_id },
beforeSend: function(){
$("#loading-animation").show();
$("#content > article").fadeOut();
},
success: function(response){
$("#content > article").html(response).fadeIn();
$("#loading-animation").hide();
return false;
}
});
});
})(jQuery);
I kept everything in my ajaxify.php file as follows:
add_action ( 'wp_ajax_nopriv_load_content', 'my_ajax_load_content', 99 );
add_action ( 'wp_ajax_load_content', 'my_ajax_load_content', 99 );
function my_ajax_load_content(){
$post_id = $_POST[ 'post_id' ];
$post = get_post( $post_id );
$response = array( apply_filters( 'the_content', $post->post_title ), apply_filters( 'the_content', $post->post_content ) );
echo '<div class="entry-header"><h1 class="entry-title">'.$response[0].'</h1></div><div class="entry-content">'.$response[1].'</div>';
die(0);
}
wp_enqueue_script( 'my-ajax-request', get_template_directory_uri() . '/js/ajax.js', array( 'jquery' ) );
wp_localize_script( 'my-ajax-request', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
Quick reminder: Your action in PHP MUST match your action inside you jQuery. In my case it was load_content (e.g. wp_ajax_nopriv_load_content, wp_ajax_load_content, data:{ action: "load_content" }).
Hopefully this helps someone going through a similar issue with WordPress AJAX.

Related

Execute a shortcode when button is clicked

I am using a metabox in the Post creator to store extra content as described in this post
Now, I would like to execute the shortcode [extra] on the click of a button similar to this post, but I can't get it to work.
Here's my code so far:
jQuery
jQuery(document).ready(function($) {
$('#extra').on('click',function() {
$.ajax({
type: "POST",
url: my_ajaxurl,
data: {
action : 'process_shortcode_on_click_action'
},
success:function(data) {
console.log("Success");
},
error: function(errorThrown){
console.log("Error");
}
});
})
})
functions.php
add_action( 'wp_enqueue_scripts', 'add_my_script' );
function add_my_script() {
wp_enqueue_script(
'extra-script', // name your script so that you can attach other scripts and de-register, etc.
get_template_directory_uri() . '/js/script.js', // this is the location of your script file
array('jquery') // this array lists the scripts upon which your script depends
);
wp_localize_script( 'extra-script', 'my_ajaxurl', admin_url( 'admin-ajax.php' ) );
}
add_shortcode( 'extra', 't5_extra_content' );
add_action( 'add_meta_boxes_post', 't5_register_extra_metabox' );
add_action( 'save_post', 't5_save_shortcode_box', 10, 2);
add_action( 'wp_ajax_process_shortcode_on_click_action', 'process_shortcode_on_click_ajax');
add_action( 'wp_ajax_nopriv_process_shortcode_on_click_action', 'process_shortcode_on_click_ajax');
function process_shortcode_on_click_ajax() {
echo do_shortcode('[extra]');
die;
}
function t5_extra_content( $attributes, $content = '' )
{
$args = shortcode_atts( array ( 'cap' => 'edit_posts' ), $attributes );
if ( current_user_can( $args['cap'] ) )
return wpautop(
get_post_meta( get_the_ID(), '_t5_extra_box', TRUE )
. $content
);
}
function t5_register_extra_metabox()
{
add_meta_box(
't5_extra',
'My Point of View',
't5_extra_metabox_callback',
NULL, // screen
'normal',
'default'
);
}
function t5_extra_metabox_callback( $post )
{
$nonce = wp_create_nonce( __FILE__ );
echo "<input type='hidden' name='t5_extra_box_nonce' value='$nonce' />";
$content = get_post_meta($post->ID, '_t5_extra_box', TRUE );
wp_editor(
$content,
'_t5_extra_box',
array (
'textarea_rows' => 10,
'media_buttons' => FALSE,
'teeny' => TRUE,
'tinymce' => TRUE
)
);
}
function t5_save_shortcode_box( $post_id )
{
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE
or ! isset ( $_POST['post_type'] )
or 'post' !== $_POST['post_type']
or ! current_user_can( 'edit_post', $post_id )
or ! wp_verify_nonce( $_POST[ 't5_extra_box_nonce' ], __FILE__ )
)
{
return;
}
if ( isset ( $_POST['_t5_extra_box'] ) )
update_post_meta( $post_id, '_t5_extra_box', $_POST['_t5_extra_box'] );
else
delete_post_meta( $post_id, '_t5_extra_box' );
}
I am seeing "Success" in the console, so I know that the jQuery is getting called correctly. I can't figure out how to get the do_shortcode('[extra]') to fire however. Any help is greatly appreciated.
Your ajax call does not have coxtent of the global $post from the page the ajax request is coming from and thus get_the_ID() should be false and get_post_meta( get_the_ID(), '_t5_extra_box', TRUE ) will also be false. Furthermore, you're calling do_shortcode('[extra]') (no content) so $content inside your callback will be an empty string. So return wpautop(get_post_meta( get_the_ID(), '_t5_extra_box', TRUE).$content); becomes return wpautop(''); which is just an empty string. Based on your code I would expect your data response to always be an empty string.
To fix this I would add an extra ajax post data item along with the action that tells the callback what $post_id should be. That's the most primitive way. You may want to add a nonce or some other measure for security (but that may not be relevant for your original question).
UPDATE
I haven't tested this, and you may want to do it differently, but here is one option. Ultimately you just need a way to get the $post_id from the original request and pass it along to the ajax call. Since you're already passing the ajax url via wp_localize_script, I would just add another JavaScript variable there.
jQuery
jQuery(document).ready(function ($) {
$('#extra').on('click', function () {
$.ajax({
type: "POST",
url: my_ajaxurl,
data: {
action: 'process_shortcode_on_click_action',
post_id: my_postid,
},
success: function (data) {
console.log("Success");
},
error: function (errorThrown) {
console.log("Error");
}
});
})
})
functions.php
add_action('wp_enqueue_scripts', 'add_my_script');
function add_my_script () {
wp_enqueue_script(
'extra-script', // name your script so that you can attach other scripts and de-register, etc.
get_template_directory_uri() . '/js/script.js', // this is the location of your script file
array('jquery') // this array lists the scripts upon which your script depends
);
wp_localize_script('extra-script', 'my_ajaxurl', admin_url('admin-ajax.php'));
wp_localize_script('extra-script', 'my_postid', get_the_ID());
}
add_action('wp_ajax_process_shortcode_on_click_action', 'process_shortcode_on_click_ajax');
add_action('wp_ajax_nopriv_process_shortcode_on_click_action', 'process_shortcode_on_click_ajax');
function process_shortcode_on_click_ajax ()
{
$_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
if (empty($post_id = $_POST['post_id']) || !is_numeric($post_id)) {
wp_die('Post ID is Invalid', 400);
}
echo do_shortcode("[extra post_id='{$post_id}']");
wp_die();
}
add_shortcode('extra', 't5_extra_content');
function t5_extra_content ($attributes, $content = '')
{
$defaults = [
'post_id' => get_the_ID(),
'cap' => 'edit_posts'
];
$args = shortcode_atts($defaults, $attributes);
if (!current_user_can($args['cap']) || empty($args['post_id'])) {
return ''; // or some message on fail
}
return wpautop(get_post_meta($args['post_id'], '_t5_extra_box', TRUE) . $content);
}

400 Bad Request with Wordpress AJAX call [duplicate]

This question already has answers here:
Wordpress admin-ajax.php 400 bad request
(8 answers)
Closed 4 years ago.
I'm working on a search plugin for the front-end of a Wordpress site. At the moment I keep getting a 400 Bad Request Error and I can't understand why. I've reviewed many questions on SO and the WordpressStackExchange but cannot see where I'm going wrong, nothing appears to be out of place. Please give me guidance:
plugin.php:
function my_admin_scripts() {
$localize = array(
'ajaxurl' => admin_url( 'admin-ajax.php' )
);
wp_register_script('veh-app-search', plugin_dir_url( __FILE__ ) . '/ajax.js', '', '', true);
wp_localize_script( 'veh-app-search', 'veh_app_script', $localize);
wp_enqueue_script( 'veh-app-search', plugin_dir_url( __FILE__ ) . '/ajax.js', array( 'jquery' ) );
}
add_action( 'wp_enqueue_scripts', 'my_admin_scripts' );
add_action( 'wp_ajax_the_ajax_hook', 'handle_request' );
add_action( 'wp_ajax_nopriv_the_ajax_hook', 'handle_request' );
//takes care of the $_POST data
function handle_request(){
echo "hello";
}
ajax.js
var data = {
action: 'handle_request',
RequestType: 'category',
Category: jQuery('#Category option:selected').val()
};
jQuery.post(
veh_app_script.ajaxurl,
data,
function(categories){
console.log(categories);
}
);
One would expect to see "Hello" in the console but I only see the error in the console:
jquery.js?ver=1.12.4:4 POST http://localhost/wp-admin/admin-ajax.php 400 (Bad Request)
Please replace code and check
plugin.php
function my_admin_scripts() {
$localize = array(
'ajaxurl' => admin_url( 'admin-ajax.php' )
);
wp_enqueue_script( 'veh-app-search', plugin_dir_url( __FILE__ ) . '/ajax.js', array( 'jquery' ) );
wp_localize_script( 'veh-app-search', 'veh_app_script', $localize);
}
add_action( 'wp_enqueue_scripts', 'my_admin_scripts' );
add_action( 'wp_ajax_handle_request', 'handle_request' );
add_action( 'wp_ajax_nopriv_handle_request', 'handle_request' );
//takes care of the $_POST data
function handle_request(){
echo "hello";
}
ajax.js
var data = {
action: 'handle_request',
RequestType: 'category',
Category: jQuery('#Category option:selected').val()
};
jQuery.post(
veh_app_script.ajaxurl,
data,
function(categories){
console.log(categories);
}
);
Use JSON instead:
function handle_request(){
echo json_encode( array( "message" => "hello" ) );
exit;
}
Parse the JSON in your ajax.js response handler:
function( response ) {
var returndata = JSON.parse( response );
console.log( returndata.message );
}
Don't forget to add json2 as a dependency to your script.
wp_enqueue_script( 'veh-app-search', plugin_dir_url( __FILE__ ) . '/ajax.js', array( 'jquery', 'json2' ) );

woocommerce ajax in the front-end not working

I try to use woocommerce Ajax, I find a lot example online, none of them works.
could someone take a look on my code, where's the problem.
add_action( 'wp_ajax_my_action', 'mmy_real' );
add_action( 'wp_ajax_nopriv_my_action', 'mmy_real' );
function mmy_real(){
check_ajax_referer( 'my-special-string', 'security' );
$make = $_SESSION['vpf']['search']['make'];
$model = $_SESSION['vpf']['search']['model'];
$year = $_SESSION['vpf']['search']['year_id'];
die();
}
function mmy_script(){
wp_register_script( "hover_script", get_template_directory_uri() . '/js/mmy.js', array('jquery'), '1.0.0', true );
wp_localize_script( 'hover_script', 'mmy', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ),'security' => wp_create_nonce( 'my-special-string' )));
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'hover_script' );
}
add_action('init', 'mmy_script');
jQuery(document).ready(function() {
jQuery.ajax({
type: "post",
url : mmy.ajaxurl,
data:{
action:"mmy_real",
make: "make",
model: "model",
year: "year"
},
success: function( response ) {
alert("success");
}
});
});
I test in localhost. It won't alert success messagebox, if I change url to localhost/fhgroupauto/test.php . it will alert success .
I don't know what do i miss for this .
Thanks
The value of "action" is wrong.
You add the hook "wp_ajax_my_action" and "wp_ajax_nopriv_my_action", so the string after "wp_ajax_" and "wp_ajax_nopriv_" is the parameter for the "action" key.
Which means your data array for the ajax call should look like this:
data:{
action: "my_action",
make: "make",
model: "model",
year: "year"
},
For more information see the Wordpress documentation - AJAX in Plugins

Getting data from database and use it to complete a form - Wordpress

I have the following files:
Main plugin file:
<?php
/*
Plugin Name: FixFormData
Description: If you want to autocomplete a form with existing data, this plugin is for you.
Version: 1.1
Author: Stijn Aerts
Author URI: http://stijnaerts.be
License: GPL2
*/
require( plugin_dir_path( __FILE__ ) . 'menu.php');
require_once( plugin_dir_path( __FILE__ ) . 'getuser.php');
add_action( 'wp_enqueue_scripts', 'ffd_load_scripts' );
function ffd_load_scripts()
{
wp_register_script('ffd_js_script', WP_PLUGIN_URL.'/FixFormData/js/ffd_js_script.js', array('jquery'));
wp_localize_script('ffd_js_script', 'myAjax', array(
'ajaxurl' => admin_url('admin-ajax.php')
)
);
wp_enqueue_script('jquery');
wp_enqueue_script('ffd_js_script', plugin_dir_url(__FILE__) . 'js/ffd_js_script.js');
}
getuser.php:
<?php
function getuser($str)
{
global $wpdb;
$myoption = get_option( 'fixformdata_options' );
$myoptionValue = maybe_unserialize( $myoption );
$result2 = $wpdb->get_row
(
$wpdb->prepare
(
"SELECT * FROM {$myoptionValue[tablename]} WHERE personeelsNummer = %d", $str
)
);
if($result2)
{
echo json_encode( $result2 );
}
}
?>
ffd_js_script.js:
jQuery(document).ready(function($){
jQuery('#input_1_2').change(function()
{
jQuery.ajax({
type : 'post',
dataType : 'json',
url : myAjax.ajaxurl,
data : {action: 'getuser', this.value},
succes: function(response){
var parsed = JSON.parse(response);
var arr = [];
for(var x in parsed){ arr.push(parsed[x]);}
jQuery('#input_1_3').val(arr[1]);
jQuery('#input_1_4').val(arr[2]);
}
})
});
});
How do I properly implement this? First time I'm making a plugin and I have read much about it and saw alot of examples, but I'm failing to implement this correctly.
EDIT:
IF I replace the sql statement with the following:
"SELECT * FROM {$myoptionValue[tablename]} WHERE personeelsNummer = %s", 1
I get my results in the console due to following code:
echo json_encode( $result2 );
So following code is not executing properly:
succes: function(response){
var parsed = JSON.parse(response);
var arr = [];
for(var x in parsed){ arr.push(parsed[x]);}
jQuery('#input_1_3').val(arr[1]);
jQuery('#input_1_4').val(arr[2]);
}
ok, you're getting there.
1st When you localize the script add a nonce for better security:
wp_register_script('ffd_js_script', WP_PLUGIN_URL.'/FixFormData/js/ffd_js_script.js', array('jquery'));
wp_localize_script('ffd_js_script', 'myAjax', array(
'ajaxurl' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce( 'ajax-nonce' )
)
);
Then, you need to place getuser.php somewhere where the plugin can see it, so be sure to include it or place it in the main file of the plugin
function getuser($str)
{
global $wpdb;
//verify the nonce
if ( ! wp_verify_nonce( $_REQUEST['_nonce'], 'ajax-nonce' ) )
die ( 'Non autorizzato!');
$myoption = get_option( 'fixformdata_options' );
$myoptionValue = maybe_unserialize( $myoption );
$result2 = $wpdb->get_row
(
$wpdb->prepare
(
"SELECT * FROM {$myoptionValue[tablename]} WHERE personeelsNummer = %d", $str
)
);
if($result2)
{
echo json_encode( $result2 );
}
die();
}
Than, to make the funciont getuser callable from ajax you need to do the proper hooking:
//ajax hooks
add_action( 'wp_ajax_nopriv_getuser', 'getuser' );
add_action( 'wp_ajax_getuser', 'getuser' );
In the js, you need to pass the nonce as well:
$.post(myAjax.ajaxurl,
{
action : 'getuser',
_nonce : myAjax.nonce,
value : $(this).value
},
function( response ) { ... });
the rest of the js seems good, forgive me for some typos, I wrote it right here so it's not tested.

Wordpress plugin development ajax url not working

jQuery(document).ready(function(e) {
jQuery('#m').click(function()
{
//jQuery(this).fadeOut();
var d='<?php echo $plugins;?>';
jQuery.ajax({url:d,data:{q:10},type:GET,success: function(msg)
{
alert(msg);
}
}
)
});
I have to develop my own plugin, basically Wordpress has an admin-ajax file which handles this type of request, so how can I make it request using its own file to handle an Ajax request?
for that you need to do it like this:
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 in your handler file :
add_action('wp_ajax_my_action', 'my_action_callback');
function my_action_callback() {
global $wpdb; // this is how you get access to the database
$whatever = intval( $_POST['whatever'] );
$whatever += 10;
echo $whatever;
die(); // this is required to return a proper result
}
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' => $email_nonce ) );
}
And Do not forget to enqueue your script :
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' => $email_nonce ) );
}

Categories