Wordpress + jquery (inside functions.php) not working - javascript

i was done adding this script into \mythemes\functions.php:
// FGI CODE started
function my_scripts_method() {
// register your script location, dependencies and version
wp_register_script('custom_script',
get_template_directory_uri() . '/js/javascript_.js',
array('jquery'),
'1.0' );
// enqueue the script
wp_enqueue_script('custom_script');
}
add_action('wp_enqueue_scripts', 'my_scripts_method');
wp_enqueue_script('jquery');
// FGI CODE ended
and also my jQuery script which is located under \mythemes\js\javascript_.js :
(function($) {
$(document).ready(function() {
$("#pilih_bulan").change(function() {
alert('a');
});
})
})(jQuery);
actually my purpose is making a combobox with an ID of : #pilih_bulan
always trigger some ajax function each time user change the selection (dropdown items).
And the above code (using alert code) is working fine. Unfortunately, when I changed into this below code, it doesn't work at all. Any ideas?
(function($) {
$(document).ready(function() {
$("#pilih_bulan").change(function() {
$.ajax({
method: "POST",
url: "./another_processor.php",
data: { name: "John", location: "Boston" }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
})
})(jQuery);

Use the below script and why you used wp_enqueue_script('jquery'); please check your source code jquery must be already added
<?php
function my_scripts_method() {
wp_enqueue_script(
'custom-script',
get_stylesheet_directory_uri() . '/js/custom_script.js',
array( 'jquery' )
);
}
add_action( 'wp_enqueue_scripts', 'my_scripts_method' );
?>

Related

Problem when sending an ajax post request in WordPress

I've read several articles on how to do this and all of them mention the same thing that I am using. I have two files for this:
In the receiver.php file:
<?php
add_action( 'wp_enqueue_scripts', 'my_enqueue' );
add_action( 'wp_ajax_my_action', 'theActionFunction' );
function my_enqueue() {
wp_register_script( 'ajax-script', plugins_url( '/src/WyrRoute.js' , __FILE__ ), array('jquery') );
wp_enqueue_script('ajax-script');
wp_localize_script( 'ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
function theActionFunction(){
$theQuestion = $_POST['question_id'];
echo $theQuestion; //doesn't show anything in the frontend
wp_die();
}
echo "hello" //works if outside the function
The issue is that nothing inside this theActionFunction prints in the frontend. Anything I type outside shows in the frontend, there must be something basic that I'm missing here.
WyrRoute.js
clickHandler(e) {
var ajax_url = my_ajax_object.ajax_url
var data ={
'action': 'my_action',
'question_id': '10183'
}
$.ajax({
type: 'POST',
url: ajax_url,
data: data,
dataType: 'json',
success: function (xhr, x, checkStatus) {
console.log(xhr);
console.log(checkStatus.status)
console.log("success")
},
error: function(e) {
console.log(e.statusText);
console.log("failure")
}
});
}
Ajax returns with 200 success, so no issue there, but for some reason, I can't get the $_POST['value'] to print in the frontend using php.
Welcome.
Well, from what I'm seeing in the code, it looks ok. At first glance, the thing I noticed is that you are declaring the function called "theActionFunction", but you arent calling it anywhere. Again it may just be me, but, if the method isn't printing anything, right underneath it, put this:
theActionFunction();
And you should be good to go. In total, it should look like this:
function theActionFunction(){
$theQuestion = $_POST['question_id'];
echo $theQuestion; //This should now work
wp_die();
}
theActionFunction();
Happy coding.

WP Ajax Load more button returning empty string

I'm trying to follow this tutorial to add a load more button to a site I'm working on.
tldr:
Ajax request just printing
<empty string>
on success and failing to render anything to the page
So I've added the button
<?php
// don't display the button if there are not enough posts
if ($query->max_num_pages > 1)
echo '<div class="misha_loadmore">More posts</div>';
?>
and localised the script I'm using
function misha_my_load_more_scripts() {
global $wp_query;
// In most cases it is already included on the page and this line can be removed
wp_enqueue_script('jquery');
// register our main script but do not enqueue it yet
wp_register_script( 'my_loadmore', get_stylesheet_directory_uri() . '/js/myloadmore.js', array('jquery') );
$args = [
'post_type' => 'news',
'posts_per_page' => 1,
'paged' => get_query_var('paged') ? get_query_var('paged') : 1
];
$query = new WP_Query($args);
// we have to pass parameters to myloadmore.js
wp_localize_script( 'my_loadmore', 'misha_loadmore_params', array(
'ajaxurl' => site_url() . '/wp-admin/admin-ajax.php', // WordPress AJAX
'posts' => json_encode( $query->query_vars ), // everything about your loop is here
'current_page' => get_query_var( 'paged' ) ? get_query_var('paged') : 1,
'max_page' => $query->max_num_pages
) );
wp_enqueue_script( 'my_loadmore' );
}
add_action( 'wp_enqueue_scripts', 'misha_my_load_more_scripts' );
This seems to be fine, the cpt is 'news' so i added a query to the function here to look for that.
Then I added the js
jQuery(function ($) {
// use jQuery code inside this to avoid "$ is not defined" error
$(".misha_loadmore").click(function () {
var button = $(this),
data = {
action: "loadmore",
query: misha_loadmore_params.posts, // that's how we get params from wp_localize_script() function
page: misha_loadmore_params.current_page,
};
$.ajax({
url: misha_loadmore_params.ajaxurl, // AJAX handler
data: data,
type: 'POST',
dataType: 'text',
beforeSend: function (xhr, data) {
button.text("Loading..."); // change the button text, you can also add a preloader image
console.debug(data);
},
success: function (data) {
console.debug(data);
if (data) {
button.text("More posts").prev().before(data); // insert new posts
misha_loadmore_params.current_page++;
if (
misha_loadmore_params.current_page == misha_loadmore_params.max_page
)
button.remove(); // if last page, remove the button
// you can also fire the "post-load" event here if you use a plugin that requires it
// $( document.body ).trigger( 'post-load' );
} else {
button.remove(); // if no data, remove the button as well
}
},
error: function (xhr, ajaxOptions, thrownError) {
console.debug(xhr.status);
console.debug(ajaxOptions);
console.debug(thrownError);
},
});
});
});
and this is my ajax function
function misha_loadmore_ajax_handler(){
// prepare our arguments for the query
$args = json_decode( stripslashes( $_POST['query'] ), true );
$args['paged'] = $_POST['page'] + 1; // we need next page to be loaded
$args['post_status'] = 'publish';
query_posts( $args );
if( have_posts() ) :
// run the loop
while( have_posts() ): the_post();
// look into your theme code how the posts are inserted, but you can use your own HTML of course
// do you remember? - my example is adapted for Twenty Seventeen theme
// get_template_part( '<h1>testBen</h1>' );
// for the test purposes comment the line above and uncomment the below one
get_the_title();
endwhile;
endif;
die; // here we exit the script and even no wp_reset_query() required!
}
add_action('wp_ajax_loadmore', 'misha_loadmore_ajax_handler'); // wp_ajax_{action}
add_action('wp_ajax_nopriv_loadmore', 'misha_loadmore_ajax_handler'); // wp_ajax_nopriv_{action}
So my issue I think is in the jquery file (not sure?) on the pre function I'm outputing the data and it's showing:
Object { url: "http://nichy.local/wp-admin/admin-ajax.php", type: "POST", isLocal: false, global: true, processData: true, async: true, contentType: "application/x-www-form-urlencoded; charset=UTF-8", accepts: {…}, contents: {…}, responseFields: {…}, … }
But printing it on the success just shows:
<empty string>
And the button 'loads' and goes away but nothing more is rendered to the page

Why my wordpress ajax isn't calling in frontend javascript file?

I am using ajax in js file. but now getting error in that "mydomain.com/my_ajax.ajax_url not found 404" in console logs.
here is my js file (demo.js) code. tried all methods but no solution--
jQuery.ajax({
type: "post",
url: "my_ajax.ajax_url",
data: { action: "data_fetch", keyword: input }
});
my functions.php -------
add_action( 'wp_enqueue_scripts', 'hindrise_script');
function my_enqueue() {
wp_register_script('plugin-ajaxJs', CHILD_URL . '/js/demo.js', __FILE__);
wp_enqueue_script('plugin-ajaxJs');
wp_localize_script('plugin-ajaxJs', 'my_ajax', array('ajax_url' => admin_url('admin-ajax.php')));
}
The function name is different than what you have defined in add_action. Use the same name in the add_action and the function name:
add_action( 'wp_enqueue_scripts', 'hindrise_script');
function hindrise_script() {
wp_register_script('plugin-ajaxJs', CHILD_URL . '/js/demo.js', __FILE__);
wp_enqueue_script('plugin-ajaxJs');
wp_localize_script('plugin-ajaxJs', 'my_ajax', array('ajax_url' => admin_url('admin-ajax.php')));
}
Also in the JS file remove the quotes for the passing variable:
jQuery.ajax({
type: "post",
url: my_ajax.ajax_url,
data: { action: "data_fetch", keyword: input }
});

Wordpress Plugin Class setup Ajax

Im making a plugin using Class , I need to run some Ajax on the Front end. All scripts are queue up correctly. when i trigger the call, i get 400 error.
class CCYTFeatured {
public function __construct(){
add_action( 'wp_enqueue_scripts', array($this, 'cc_yt_scripts' ));
add_action( 'wp_ajax_cc_get_featured_yt', array( $this, 'cc_get_featured_yt' ) );
add_action( 'wp_ajax_nopriv_cc_get_featured_yt', array( $this, 'cc_get_featured_yt' ) );
}
public function cc_yt_scripts() {
// JAVASCRIPT
wp_register_script( 'cc_yt_script',
plugins_url( '/js/cc_yt.js', __FILE__ ),
array('jquery'),
cc_yt_version(),
true
);
wp_localize_script(
'cc_yt_script',
'cc_yt_ajax',
array(
'ajax_url' => admin_url( 'admin-ajax.php' )
)
);
wp_enqueue_script('cc_yt_script');
}
public function cc_get_featured_yt(){
echo 'SUCCESS!';
die();
}
My ajax call is:
function start_yt(){
jQuery('#cc_yt_light_wrap').show();
// REGISTER NEW ENTRY USING AJAX
jQuery.ajax({
url: cc_yt_ajax.ajax_url,
type: 'POST',
data: {
action : 'cc_get_featured_yt',
},
async: true,
success: function(response) {
console.log(response);
}
});
}
Thanks for your help! X)
Try this:
Change the method name from cc_get_featured_yt to get_featured, and change the method name everywhere in your class.
and then in the ajaxcall you put this code:
data: {
action : 'featured_yt',
}
I think the get in the methodname is a keyword. This worked for me.
The code is ok,
The way i was calling the class was wrong.
I was calling this inside a theme. Instead, i created a new method and moved everything from __construct().
Started my class and called the method inside the plugin file. After i started the class again and only called the needed method inside my theme. Worked perfectly.

How to Check Username Availability with AJAX / jQuery Validator in Wordpress?

I've been trying to get this to work, but the code I'm using is not using the Wordpress AJAX functions correctly. The jQuery keeps trying to access the wrong url for admin ajax. I'm also not sure if my PHP code is correct or not because it seems like there's no code to deal with an empty input:
PHP:
//Ajax Password Checker
function load_user_checker() {
wp_enqueue_script( 'ajax-script', get_stylesheet_directory_uri().'/js/user-check.js', array('jquery'), 1.0 ); // jQuery will be included automatically
wp_localize_script( 'ajax-script', 'ajax_object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) ); // setting ajaxurl
}
add_action('init', 'load_user_checker');
function ajax_action_checker() {
//Validation
$username = trim($_POST['user_login']);
$username = mysqli_escape_string($username);
if ( username_exists( $username ) ){
echo 'false';
} else {
echo 'true';
}
die();
}
add_action( 'wp_ajax_nopriv_ajax_action', 'ajax_action_checker' ); // ajax for not logged in users
JS / jQuery:
jQuery(document).ready(function($) {
$('#formid').validate({
rules: {
user_login: {
required: true,
remote: {
type: 'post',
data:
{
'action': 'ajax_action',
'user_login': function()
{
return $('#formid :input[name="user_login"]').val();
}
}
}
}
},
messages:{
user_login:{
required: "Please enter a username.",
remote: jQuery.validator.format("{0} is already taken. Please choose another username")
}
}
});
});
Thanks for your help!

Categories