Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
0
rated 0 times [  5] [ 5]  / answers: 1 / hits: 32924  / 11 Years ago, mon, october 14, 2013, 12:00:00

I've setup the basic wordpress ajax example in my wp theme. The trigger is made by modernizr.js checking the media queries on the page.



jQuery(document).ready(function($) {
if(Modernizr.mq('only all and (max-width:6300px)')) {
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(data) {
$(#trending-Container).html(data).fadeIn(1000);
});
}

});//end function


I have localized and enqueue'd my scripts.



wp_enqueue_script('mainJS', get_template_directory_uri() . '/js/mainJS.js', array(jquery) );
wp_localize_script( 'mainJS', 'ajax_object',
array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'we_value' => 1234 ) );


and finally the function that handles the request is:



add_action('wp_ajax_my_action', 'my_action_callback');
add_action('wp_ajax_nopriv_my_action', 'my_action_callback');
function my_action_callback() {
global $wpdb;
$whatever = intval( $_POST['whatever'] );
$whatever += 10;
echo $whatever;
die();

}


This constantly gives me a response of 0 (no properties) and I do not know why.
P.S This is all local.



Status code 200
Host:lart.co.uk
Origin:http://lart.co.uk
Referer:http://lart.co.uk/
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/28.0.1500.71 Chrome/28.0.1500.71 Safari/537.36
X-Requested-With:XMLHttpRequest
Form Dataview sourceview URL encoded
action:my_action
whatever:1234

More From » php

 Answers
4

Everything has to match here:



PHP




add_action('wp_ajax_my_action', 'my_action');
add_action('wp_ajax_nopriv_my_action', 'my_action');

function my_action() {}


JS




var data = {
action: 'my_action',
whatever: ajax_object.we_value
};


Also, you're missing security checks and a better handling of the response.

Check this examples: [ 1 ] and [ 2 ].


[#74993] Sunday, October 13, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kalynnkathrynd

Total Points: 273
Total Questions: 101
Total Answers: 93

Location: Nauru
Member since Thu, Feb 2, 2023
1 Year ago
;