I have a questio related with ajax. Sometimes it gets the right response but sometimes just returns 0. What could be the problem? Host or code?
Code is below:
jquery:
$(document).ready(function(){
//var cat = $(".bear_image").children("img").attr("alt");
var top = $("li");
var icons = $(top).children(".icons").children("div");
$(icons).click(function(){
//var icon = $(this).attr("class");
var item = $(this).attr("id");
var bear_id = $(this).parents("li").find("> .bear_image img");
var data = {
'action' : 'get_image_name',
'item' : item,
'bear_id' : bear_id.attr('alt')
};
$.post(ajaxurl, data, function(response) {
//alert('Got response from server: ' + response);
$(bear_id).attr("src", response);
});
});
});
functions.php
function jj_get_images()
{
global $wpdb;
$item = esc_attr($_POST['item']);
$bear_id = esc_attr($_POST['bear_id']);
$query = "SELECT * FROM wp_acc_img WHERE position = " . $item . " AND bearid = ". $bear_id;
$result = $wpdb->get_row($query);
$c = $result->num_rows;
$upload_dir = wp_upload_dir();
$var = $upload_dir['url'] . "/" .$result->img.".png";
die($var);
wp_die();
}
add_action('wp_ajax_get_image_name', 'jj_get_images');
function pluginname_ajaxurl() {
?>
<script type="text/javascript">
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>
<?php
}
add_action('wp_head','pluginname_ajaxurl');
It seems okay for me. The thing is that sometimes it return the full url that is how should it be but sometimes it just returns 0 and does not execute the code properly? Do you have any suggestions.
Thanks for the help 🙂
Change:
$(icons).click(function(){
toNote: your current setup will work only for logged-in users,
for quests use the
wp_ajax_nopriv
action