Am using WordPress ajax to load the sub-categories dynamically.
Here's my code
Php code
function techento_getsubcat() {
$category_name = $_POST['catname'];
$cat_id = $_POST['catid'];
return wp_dropdown_categories( 'show_option_none=Choose a Sub Category&tab_index=10&taxonomy=category&hide_empty=0&child_of=' . $cat_id . '' );
}
add_action('wp_ajax_techento_getsubcat', 'techento_getsubcat');
add_action('wp_ajax_nopriv_techento_getsubcat', 'techento_getsubcat');
Jquery
jQuery(document).ready(function(){
$('#cat').change(function(e){
alert("changed");
$.ajax({
type: 'POST',
dataType: 'json',
url: pcAjax.ajaxurl ,
data: {
'action': 'techento_getsubcat', //calls wp_ajax_nopriv_ajaxlogin
'catname': $('#cat option:selected').text(),
'catid': $('#cat option:selected').val() },
success : function(response){
alert(response);
console.log(response);
$("#subcats").html(response);
}
});
e.preventDefault();
});
});
The problem with the above code is that php returns the raw html irrespective of the thing asked to return
even if set it to
return true;
it then returns the raw html of subcategories generated plus '0'
You're missing the $ shortcode in
jQuery(document).ready(function($){
The Ajax callback is better handled by wp_send_json_success(), so we don't have to worry with return or echo, exit or die. For that, set echo to false in the dropdown arguments:
function techento_getsubcat() {
$cat_id = intval( $_POST['catid'] );
$args = array(
'hide_empty' => 0,
'echo' => 0,
'child_of' => $cat_id,
'taxonomy' => 'category'
);
$data = wp_dropdown_categories( $args );
wp_send_json_success( $data );
}
On Ajax success, use response.data:
success : function(response){
console.log(response.data);
}
Related
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
My ajax function goes in error after I set the dataType to Json.
That's the code:
Ajax script:
$('#da').on("change",function() {
$.ajax({
url: "callAjaxIndex.php",
type: "POST",
dataType: "json",
data: {
method: 1,
id: $('#da').val(),
},
success: function() {
alert('test');
},
error: function() {
alert('error');
}
});
});
callAjaxIndex.php
<?PHP
require('includes/core.php');
if ( isset($_POST['method']) ) {
$sql = "SELECT tratte.nome as 'nome_arrivo', tratte.id as 'id_arrivo' FROM tariffe, tratte WHERE id_arrivo = tratte.id AND id_partenza = '".$_POST['id']."'";
$query = $conn->query($sql);
while ( $tariffe = $query->fetch_array() ) {
$result[] = array(
'id' => $tariffe['id_arrivo'],
'nome' => $tariffe['nome_arrivo']
);
}
echo json_encode($result);
}
?>
What's wrong?
Thank you
You can try this
$(document).on('change', '#da', function(){
$.post("callAjaxIndex.php", {'method': 1, 'id': $(this).val()}, function(data){
var d = $.parseJSON(data); //here is the data parsed as JSON
//data is that returned from callAjaxIndex.php file
});
});
<?php
require('includes/core.php');
if ( isset($_POST['method']) ) {
$sql = "SELECT tratte.nome as nome_arrivo, tratte.id as id_arrivo FROM tariffe INNER JOIN tratte ON id_arrivo = tratte.id WHERE id_partenza = '".$_POST['id']."'";
$query = $conn->query($sql);
while ( $tariffe = $query->fetch_array() ) {
$result[] = array(
'id' => $tariffe['id_arrivo'],
'nome' => $tariffe['nome_arrivo']
);
}
echo json_encode($result);
}
You can find out the error by changing your function to this:
//other code
error: function(data)
{
console.log(data.responseText)
}
//other code
This will tell you why it fails, might be something generic but better than 'error'
Also note:
this was done from a phone so excuse any mistakes
I'd rather this be treated as a comment until I can get to a machine to help more :)
I am displaying events with a date filter in wordpress. Current date is preselected and so events on the current day display by default. If someone clicks on another date, I call function newDate.
Problem: I pass the new variable with post method successfully, but can't pass it to php. Variable is in the unix timestamp format.
//calendar.js
function newDate(selectedDate){
var sendDate = selectedDate;
$.ajax({
type : 'POST',
url: ajax_date.ajaxurl,
data: {
action: 'submit_date',
sendDate : sendDate
}
});
}
In my functions php I enqueue, localize the scrip and call the functions
//functions.php
wp_enqueue_script( 'calendar', get_template_directory_uri() .
'/resources/js/calendar.js', array( 'jquery' ), '1.0', true);
wp_localize_script('calendar', 'ajax_date', array(
'ajaxurl' => admin_url('admin-ajax.php'));
add_action( 'wp_ajax_nopriv_submit_date', 'submit_date' );
add_action( 'wp_ajax_submit_date', 'submit_date' );
function submit_date(){
$newdate = $_POST['sendDate'];
wp_die();
};
And finally my php file for displaying events. var_dump prints out null and echo also displays no content.
<div id ="events-container">
<?php
echo $newdate;
var_dump($newDate);
?>
EDIT - FIXED
Thank you, it worked, my code as follows:
//events-page.php
<div id ="events-container">
<?php
echo get_events($args);
?>
</div>
//calendar.js
$.ajax({
type : 'POST',
url: ajax_date.ajaxurl,
data: {
action: 'submit_date',
sendDate1 : date1,
sendDate2 : date2
}
}).done(function(data) {
console.log( data ); // will log the data you get back from your PHP function.
// Now you can display it on the view
$('#events-container').html(data);
})
//functions.php
wp_enqueue_script( 'calendar', get_template_directory_uri() . '/resources/js/calendar.js', array( 'jquery' ), '1.0', true);
wp_localize_script('calendar', 'ajax_date', array(
'ajaxurl' => admin_url('admin-ajax.php')));
//ajax actions
add_action( 'wp_ajax_nopriv_submit_date', 'submit_date' );
add_action( 'wp_ajax_submit_date', 'submit_date' );
function submit_date(){
$newdate1 = $_POST['sendDate1'];
$newdate2 = $_POST['sendDate2'];
$args = array(
'post_type' => 'epsa_events',
'posts_per_page' => 5,
'order' => 'ASC',
'meta_query' => array (
array(
'key' => 'start_time',
'value' => array($newdate1, $newdate2),
'compare' => 'BETWEEN'
)
));
get_events($args);
wp_die();
};
function get_events($args){
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
echo '<div class="entry-content">';
the_title();
the_content();
$startTime = DateTime::createFromFormat('Y-m-d H:i', get_field('start_time'));
echo date_format($startTime, 'H:i a d.m.');
echo '</div>';
endwhile;
}
You need a callback on your $.ajax() method. Right now, you just send the data to your PHP function, but you don't get it back on front.
//calendar.js
function newDate(selectedDate){
var sendDate = selectedDate;
$.ajax({
type : 'POST',
url: ajax_date.ajaxurl,
data: {
action: 'submit_date',
sendDate : sendDate
}
}).done(function(data) {
console.log( data ); // will log the data you get back from your PHP function.
// Now you can display it on the view
$('#events-container').html(data);
});
}
More information : http://api.jquery.com/jquery.ajax/
You need to process ajax date after getting date in $_POST['sendDate'] in submit_date function either by applying WP_Query or any your custom written function of your plugin and you need to echo processed results before wp_die() then you can get the data in ajax success function and with jquery can insert your results.
A thorough guide you can check here:
https://www.creare.co.uk/blog/simple-wp_query-ajax
I'm trying to send a message from php to ajax. I'm using echo json_encode to do it. When I do that, the website displays the arrays message. ({"foo":"content of foo"}). How can I get it to not display the message?
Also, the alerts from ajax don't get called.
Here's the code:
<?php
$myString = $_POST['data'];
if ($myString == "") {
echo json_encode(
array()
);
} else if ($myString == "foo" {
echo json_encode(
array(
'foo2' => 'this is the contents of foo'
)
);
} else if ($myString == "foo2") {
echo json_encode(
array(
'foo2' => 'this is the contents of foo2'
)
);
}
?>
<script>
var formData = new FormData($(this)[0]);
$.ajax({
url: $(this).attr("action"),
context: document.body,
data: formData,
type: "POST",
contentType: false,
processData: false,
success: function(response) {
if (response.length == 0) {
alert("empty");
} else if (response.foo) {
alert("foo");
} else if (respons.foo2) {
alert("foo2");
}
}
});
</script>
How can I get the array to not display on the website? And why are the ajax if statements not getting called?
You need to set the HTTP header at the top of the script so you can return son:
header('Content-type: application/json');
Your script is a little confusing. You can't return json AND html/javascript.
It's one or the other.
drupal 6: here is the code:
http://pastebin.com/GGVFfAGS
//getcity.js:
$(document).ready(function() {
$("#edit-field-house-geo-area-value").bind('change', function(){
selected_loc=$("#edit-field-house-geo-area-value option:selected").val();
var myURL="http://whatever.com/getajax/citys/"+selected_loc+"/";
$.ajax({
type: "GET",
url: myURL,
dataType: "json",
success: function(data){
console.log(data);
}
});
});
});
drupal module:
function sf_menu()
{
cache_clear_all();
$items = array ();
$items ['getajax/citys/%'] = array ('title' => 'This is my custom page', 'page callback' => 'sf_get_cities_ajax', 'access arguments' => array ('access content' ), 'access callback' => 'user_access', // TRUE will give access to everyone
'page arguments' => array (2 ), 'type' => MENU_CALLBACK );
return $items;
}
function sf_get_cities_ajax($cityid)
{
$termsarray = array ();
$terms = array ();
$cityid_safe = (int)$cityid;
$cityid_safe = check_plain($cityid_safe);
if (is_number($cityid_safe)) {
$terms = taxonomy_get_children($cityid_safe, 143, 'tid');
if (count($terms)) {
foreach ($termsarray as $k => $v) {
$termsarray [check_plain($k)] = t($v [tid]);
}
$f= array('status' => 1, 'data' => $termsarray,'moo'=>'sadasdsd');
print drupal_json($f);
exit();
}
}
}
its not return me somthing even i print the 'moo' data
its my function its working fine i get array at the final but its dont pass it
That looks like it should work except one thing... PHP doesn't have a function 'is_number()' so unless you wrote your own you need to change your IF statement to use PHP built in 'is_numeric':
if (is_numeric($cityid_safe)) {
Its not a JS issue at all.