8

Ok so a fairly long question here. I'm fairly new to AJAX and especially using it in the context of WordPress, but I've been following along some tutorials online and I think I'm almost there.

I'll paste what I have so far and explain my thinking.

Ok so to start, the JS.

jQuery(document).ready(function(){
     jQuery('.gadgets-menu').mouseenter(function(){

          doAjaxRequest();
     });
});

Mouse enters .gadgets-menu and the request triggers, using mouseenter so it fires once.

The request itself.

function doAjaxRequest(){
     // here is where the request will happen
     jQuery.ajax({
          url: 'http://www.mysite.com/wp-admin/admin-ajax.php',
          data:{
               'action':'do_ajax',
               'fn':'get_latest_posts',
               'count':5
               },
          dataType: 'JSON',
          success:function(data){
                //Here is what I don't know what to do.                 

                             },
          error: function(errorThrown){
               alert('error');
               console.log(errorThrown);
          }


     });

} 

Now the php function.

add_action('wp_ajax_nopriv_do_ajax', 'our_ajax_function');
add_action('wp_ajax_do_ajax', 'our_ajax_function');
function our_ajax_function(){


     switch($_REQUEST['fn']){
          case 'get_latest_posts':
               $output = ajax_get_latest_posts($_REQUEST['count']);
          break;
          default:
              $output = 'No function specified, check your jQuery.ajax() call';
          break;

     }


         $output=json_encode($output);
         if(is_array($output)){
        print_r($output);   
         }
         else{
        echo $output;
         }
         die;
}

And the ajax_get_latest_posts function

function ajax_get_latest_posts($count){
     $posts = get_posts('numberposts='.'&category=20'.$count);

     return $posts;
}

So, if I've done this right the output should be $posts = get_posts('numberposts='.'&category=20'.$count); ie. the number of posts (5), from category 20. I don't know what to do with that now, how do I get the title and the thumbnail?

I'm sorry if this is silly, I'm just fumbling around here.

Amended php

add_action('wp_ajax_nopriv_do_ajax', 'our_ajax_function');
add_action('wp_ajax_do_ajax', 'our_ajax_function');
function our_ajax_function(){


      $output = ajax_get_latest_posts($_REQUEST['count']); // or $_GET['count']
    if($output) {
        echo json_encode(array('success' => true, 'result' => $output));
    }
    else {
        wp_send_json_error(); // {"success":false}
        // Similar to, echo json_encode(array("success" => false));
        // or you can use, something like -
        // echo json_encode(array('success' => false, 'message' => 'Not found!'));
    } 

         $output=json_encode($output);
         if(is_array($output)){
        print_r($output);   
         }
         else{
        echo $output;
         }
         die;
}


function ajax_get_latest_posts($count)
{
    $args = array( 'numberposts' => $count, 'order' => 'DESC','category' => 20 );
    $post = wp_get_recent_posts( $args );
    if( count($post) ) {
        return $post;
    }
    return false;
}

This does not work.

jQuery(document).ready(function(){
     jQuery('.gadgets-menu').mouseenter(function(){

          doAjaxRequest();
     });
});
function doAjaxRequest(){
     // here is where the request will happen
     jQuery.ajax({
          url: 'http://localhost:8888/wp-admin/admin-ajax.php',
          data:{
               'action':'do_ajax',
               'fn':'get_latest_posts',
               'count':5
               },
          dataType: 'JSON',
          success:function(data){
            if(data.success) {
               alert("It works");


                        }
            else {
                // alert(data.message); // or whatever...
            }
        }


     });

} 

No alert is shown.

1
  • have you checked the network tab on Chrome Dev Tools to check the response status and text? also are you sure the url for the ajax call is correct? aren't you missing the name of your folder/site or are you working on the root of htdocs on your localhost? Commented Aug 1, 2013 at 16:09

1 Answer 1

10

In your code get_posts('numberposts='.'&category=20'.$count); is wrong, but you can use wp_get_recent_posts function instead (though it uses get_posts anyway), for example

function ajax_get_latest_posts($count)
{
    $args = array( 'numberposts' => $count, 'order' => 'DESC','category' => 20 );
    $post = wp_get_recent_posts( $args );
    if( count($post) ) {
        return $post;
    }
    return false;
}

Then in your our_ajax-function you can use

    $output = ajax_get_latest_posts($_REQUEST['count']); // or $_GET['count']
    if($output) {
        echo json_encode(array('success' => true, 'result' => $output));
    }
    else {
        wp_send_json_error(); // {"success":false}
        // Similar to, echo json_encode(array("success" => false));
        // or you can use, something like -
        // echo json_encode(array('success' => false, 'message' => 'Not found!'));
    }

In you success callback function, you can then check

success:function(data){
    if(data.success) {
        // loop the array, and do whatever you want to do
        $.each(data.result, function(key, value){
            // you can use $(this) too
            // console.log($(this)); // check this for debug and get an idea
        });
    }
    else {
        // alert(data.message); // or whatever...
    }
}

You can read here about wp_send_json_error helper function to learn more about helper functions.

Update :

Also remember that, after $output=json_encode($output); the $output is not an array anymore, instead, it's a json string, so is_array($output) will return false but if you use is_array() just before you encode it using $output=json_encode($output); like

if( is_array( $output ) ) {
    $output = json_encode( $output );
}

In this case, is_array( $output ) will return true.

An example/simulation.

Sign up to request clarification or add additional context in comments.

23 Comments

And how to actually output that on the page with JS?
You have to loop the result and append each row/some fields in the page.
Forgive me, Sheikh, but I don't know how to do that with JS! That was actually my question.
If you get posts then data.results (according to my answer) will contain all the post as an array of Javascript objects and you can loop using $.each (check this answer) or for().
Yeah I may well do that, Sheikh, I really appreciate you trying though, you're a champion.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.