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.

andy
  • 2,746
  • 7
  • 47
  • 63
  • 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? – omma2289 Aug 01 '13 at 16:09

1 Answers1

9

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.

The Alpha
  • 143,660
  • 29
  • 287
  • 307
  • And how to actually output that on the page with JS? – andy Jul 31 '13 at 23:25
  • You have to `loop` the `result` and `append` each row/some fields in the page. – The Alpha Jul 31 '13 at 23:34
  • Forgive me, Sheikh, but I don't know how to do that with JS! That was actually my question. – andy Jul 31 '13 at 23:37
  • 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](http://api.jquery.com/jQuery.each/) ([check this answer](http://stackoverflow.com/questions/6298599/jquery-each-json-array-object-iteration)) or [for()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for). – The Alpha Jul 31 '13 at 23:42
  • I'm checking the console and I'm not getting anything whatsoever when the mouseenter happens, though I can see in the network log that it is requesting data @wp-admin. I'll amend my question with your code. – andy Jul 31 '13 at 23:50
  • Yes, in my answer but you have made mistakes in your question's code (i mentioned in my answer). – The Alpha Aug 01 '13 at 00:04
  • Well I'm doing testing and it won't display an alert for data.success, edited my question. – andy Aug 01 '13 at 00:15
  • Try `console.log(data)` in your `success` callback, before `if(data.success)` and see what you get in the console. – The Alpha Aug 01 '13 at 00:17
  • Console log in firebug shows `GET http://localhost:8888/wp-admin/admin-ajax.php?action=do_ajax&fn=get_latest_posts&count=5`, console log in chrome shows nothing. Even without console.log(data) firebug shows the same thing. – andy Aug 01 '13 at 00:24
  • Do you have a category with id `20`, change the category in the example i've used and see what you get. – The Alpha Aug 01 '13 at 00:26
  • Yeah I definitely have a category ID 20, I changed it to 12 and some others and it gives the same message in firebug. – andy Aug 01 '13 at 00:30
  • Instead of `echo json_encode(array('success' => true, 'result' => $output));` try `print_r($output);exit;` and se what you get in the console, don't forget `console.log(data)`. – The Alpha Aug 01 '13 at 00:34
  • Same console message with `print_r($output);exit;` `GET http://localhost:8888/wp-admin/admin-ajax.php?action=do_ajax&fn=get_latest_posts‌​&count=5` – andy Aug 01 '13 at 00:37
  • Check `function our_ajax_function(){ exit('function called'); }` and see if it works and check this thing step by step. – The Alpha Aug 01 '13 at 00:39
  • Sorry, I don't understand what you mean. If I replace `function our_admin_ajax` with that, the page just doesn't load at all. – andy Aug 01 '13 at 00:43
  • This is to make sure that your function is working, just put `exit('function is working')` in side you function, at first line and see if you get `function is working` in the console. – The Alpha Aug 01 '13 at 00:45
  • Nope, I get the same message in the console, again. Perhaps you want to amend your answer with the full php code just to be extra sure I'm not doing something really stupid? I appreciate your help by the way, you're awesome. – andy Aug 01 '13 at 00:47
  • Is this a live site, if it's then give me your link or I'm sorry because I don't know what's going on. – The Alpha Aug 01 '13 at 00:51
  • It's not a live site :/ – andy Aug 01 '13 at 00:53
  • How can I help you then ? – The Alpha Aug 01 '13 at 00:54
  • I don't know, I guess I'll just have to accept defeat on this one, thanks for trying though. – andy Aug 01 '13 at 00:55
  • Maybe you can wait other answers or post the question on http://wordpress.stackexchange.com/ – The Alpha Aug 01 '13 at 00:58
  • 1
    Yeah I may well do that, Sheikh, I really appreciate you trying though, you're a champion. – andy Aug 01 '13 at 01:00