Viewed   157 times

My ajax call output is always showing 0 as output don't know why

In functions.php I have this code

function get_data() {
    $abc = '1';
    $result = $wpdb->get_results("SELECT * FROM ".$wpdb->options ." WHERE option_name LIKE '_transient_%'");
    echo  $result; //returning this value but still shows 0
    wp_die();
}

add_action( 'wp_ajax_nopriv_get_data', 'get_data' );
add_action( 'wp_ajax_get_data', 'get_data' );

And my ajax call is in a javascript

$('body').on("click", ".re-reset-btn", function(e){

    var panel = $('#re-compare-bar');       

    $.ajax({
             type : "GET",
             dataType : "json",
             url : "/wp-admin/admin-ajax.php",
             data : {action: "get_data"},
             success: function(response) {

                   alert("Your vote could not be added");
                   alert(response);
                }
        });   

    $("#re-compare-bar-tabs div").remove(); 
    $('.re-compare-icon-toggle .re-compare-notice').text(0); 

});

I'm making ajax call in wordpress without use of plugin but not getting what I'm passing.Even If I output $abc still it shows 0.

 Answers

4

In backend there is global ajaxurl variable defined by WordPress itself.

This variable is not created by WP in frontend. It means that if you want to use AJAX calls in frontend, then you have to define such variable by yourself.

Good way to do this is to use wp_localize_script.

Let's assume your AJAX calls are in my-ajax-script.js file, then add wp_localize_script for this JS file like so:

function my_enqueue() {
      wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '/js/my-ajax-script.js', array('jquery') );
      wp_localize_script( 'ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
 }
 add_action( 'wp_enqueue_scripts', 'my_enqueue' );

After localizing your JS file, you can use my_ajax_object object in your JS file:

jQuery.ajax({
    type: "post",
    dataType: "json",
    url: my_ajax_object.ajax_url,
    data: formData,
    success: function(msg){
        console.log(msg);
    }
});
Sunday, September 11, 2022
3

As per your request I have put this in an answer for you.

As Hieu Nguyen suggested in his answer, you can use the ajaxurl javascript variable to reference the admin-ajax.php file. However this variable is not declared on the frontend. It is simple to declare this on the front end, by putting the following in the header.php of your theme.

<script type="text/javascript">
    var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
</script>

As is described in the Wordpress AJAX documentation, you have two different hooks - wp_ajax_(action), and wp_ajax_nopriv_(action). The difference between these is:

  • wp_ajax_(action): This is fired if the ajax call is made from inside the admin panel.
  • wp_ajax_nopriv_(action): This is fired if the ajax call is made from the front end of the website.

Everything else is described in the documentation linked above. Happy coding!

P.S. Here is an example that should work. (I have not tested)

Front end:

<script type="text/javascript">
    jQuery.ajax({
        url: ajaxurl,
        data: {
            action: 'my_action_name'
        },
        type: 'GET'
    });
</script>

Back end:

<?php
    function my_ajax_callback_function() {
        // Implement ajax function here
    }
    add_action( 'wp_ajax_my_action_name', 'my_ajax_callback_function' );    // If called from admin panel
    add_action( 'wp_ajax_nopriv_my_action_name', 'my_ajax_callback_function' );    // If called from front end
?>

UPDATE Even though this is an old answer, it seems to keep getting thumbs up from people - which is great! I think this may be of use to some people.

WordPress has a function wp_localize_script. This function takes an array of data as the third parameter, intended to be translations, like the following:

var translation = {
    success: "Success!",
    failure: "Failure!",
    error: "Error!",
    ...
};

So this simply loads an object into the HTML head tag. This can be utilized in the following way:

Backend:

wp_localize_script( 'FrontEndAjax', 'ajax', array(
    'url' => admin_url( 'admin-ajax.php' )
) );

The advantage of this method is that it may be used in both themes AND plugins, as you are not hard-coding the ajax URL variable into the theme.

On the front end, the URL is now accessible via ajax.url, rather than simply ajaxurl in the previous examples.

Thursday, December 8, 2022
2

Remove JS code that automatically add the class that you wanted to be added manually,

these lines

jQuery(".grid-item").first().addClass("comercial");
jQuery(".grid-item:eq(1)").addClass("residencial");
jQuery(".grid-item:eq(2)").addClass("cultural");
jQuery(".grid-item:eq(3)").addClass("interiores");
jQuery(".grid-item:eq(4)").addClass("residencial");
jQuery(".grid-item:eq(5)").addClass("residencial");

in your wordpress loop, get the list of categories of the current item and store them in variable separated by space as this will be use as classes later, you can use get_the_category function

//get the category assign to the post
//$cat_objects = get_the_category();
$cat_objects = wp_get_post_terms( get_the_ID(), 'portfolio_category');



/**Define category variable to be use as class, leave empty if you don't want to add global classes you can add 'grid-item' in here and remove it on the LI element, **/
$categories = '';

// Loop through each category object
foreach ( $cat_objects as $cat ) {

    // extract the category slug and add them to $categories variable, 
    $categories .=  ' '. $cat->slug; /** Added Space at the beginning of each category so they will be separated during actual output**/
}

you can then add the list of categories stored in the $categories variable from the code above as additional class for grid-item li's, <li class="grid-item<?php echo $categories; ?>">

Your loop should look something like this

<div class="projecto"><div class="grid">
<?php $my_query = new WP_Query('post_type=portfolio&posts_per_page=-1');
    while ($my_query->have_posts()) : $my_query->the_post(); 

    $cat_objects = get_the_category();
    $categories = '';
    foreach ( $cat_objects as $cat ) {
        $categories .=  ' '. $cat->slug;
    }

    ?>
<?php $feat_image = wp_get_attachment_url(get_post_thumbnail_id($post->ID) );?>

<?php if($feat_image!=''){?>  <li class="grid-item<?php echo $categories; ?>"><a href="<?php the_permalink(); ?>"><div class="proimg"><img alt="" src="<?php echo $feat_image;?>" /></div></a>
<h5><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h5>
                       <div class="textblock"><?php echo $text = get_post_meta( $post->ID, 'text', true ); ?>
</div>
                       </li><?php } ?>
<?php endwhile;  wp_reset_query(); ?>
</div>
Tuesday, November 15, 2022
 
kolja
 
5

You should set the cookie with a PHP script called with ajax. Then when you load the next page, it will already be set for the PHP script to find it. I admit I don't know the ins and outs of jquery.cookie so this may not be the answer. But this is what I'd start with.

Friday, October 28, 2022
 
2

If you can include jQuery on your page, it has a shorthand method for doing exactly that: .load(). Your final javascript might look something like this:

$(document).ready(function() {

    $("#searchButton").bind('click', function() {
        $("#resultsDiv").load(
            'http://mysite.com/sorting.php',
            { // parameters, in object literal format
               sortDir: 'asc',
               sortCol: 'lastname'
               // etc.
            }
        );
    });

});

Where you substitute mysite.com, searchButton, and resultsDiv with the real information for your site/markup. You can also get the sort params from page elements with jquery selectors like so: $("#sortDir").val() - assumes a text box, text area or select box. There are other ways to retrieve checkboxes and radio buttons, assuming your form uses them. To answer your other questions:

1) Every type of sort or filter will be handled by different php. Is this good way how to make this kind of page? or is there some easier and better way?

It's not unreasonable for a small number. Not accepting any arguments on the server is one way to make sure you don't ever allow malicious input. It tends to get unwieldy when you need to change a table name or the columns you're selecting and have to modify every file. You also need to realize that if you allow combinations of filters and sorts, you're talking about supporting the intersection of them. If you have 3 filters and 4 sorts, that's 12 combinations. If you want to add another sort and another filter, you have to add 4 new pages for filters and 5 new pages for sorts - and it gets worse every time.

Most people would go the route of having all data go to the same page and have only that page be responsible for validating user input, formulating the query, and returning the results. This paradigm commonly called DRY for Don't Repeat Yourself. But if you are accepting user input, you need to be very careful about validating it (on the server side! Don't trust user input!) and not allowing e.g. a SQL injection attack.

2) And one more thing. Is it possible to have some transitions when different type of filter is selected? I would like something like this: quicksand

That particular animation is very complex. They are running a difference between the icons to be shown for each page and programmatically customizing which icons to shrink out, explode in, move etc. etc. I could go into more detail about how to do it yourself...

But your know what? It's a plugin, compatible with jQuery 1.3+ and licensed under MIT & GPLv2, so you should have no problems incorporating it into your site. Check the docs and take a stab at it yourself. I don't see anything inherently incompatible with sorting the type of markup you're returning. I do notice that their example is using li tags for sorting and your example return is using div. But that shouldn't be a major hangup, and if it is, just return lis instead. When you run into problems using it, post another question, tag it appropriately and be prepared to post everything you've tried in that regard.

Saturday, November 19, 2022
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :