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.
According to the AJAX model, web applications can send and retrieve data from a server asynchronously without interfering with the display and the behavior of the existing page. Many developers use JSON to pass AJAX updates between the client and the server.
Approach: To solve this problem, we will first consider a JSON file named “capitals. json” and try to get this JSON data as a response using AJAX. Then we will create an HTML file “capitals. html” which contains a table which we will use to populate the data we are getting in response.
You can use the admin_url( 'admin-ajax. php' ) function of WordPress to get this url. We write the script on both side (Client and Server) to send and handle an AJAX request.
jQuery / AJAX Basic AJAX function to pass the JSON data to the server-side script. $. ajax({ type: "POST", url: targetURL, async: false, data: JSON. stringify($('#form').
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With