How to Load Ajax in Wordpress

How to Load Ajax in Wordpress

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.

Loading php file with AJAX in Wordpress frontend

Chetan Vaghela just helped with this problem on wordpress.stackexchange.com. If someone encounters with same problem as i had, please check Chetan Vaghela's answer below:

Solution provided by Chetan Vaghela on wordpress.stackexchange.com

Load PAGE content via AJAX in WordPress

Apparently, it had something to do with the local server I was running.

When published online, the AJAX loading works like this!

How to call ajax in Wordpress

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);
}
});

How to load wp ajax for not logged users?

All you need to do is just register your function to a hook named as wp_ajax_nopriv_{your_function_name}

So, for your case, add_action( 'wp_ajax_nopriv_data_fetch', 'data_fetch' ); should do the trick.


Registering an ajax function in WordPress:

1. Registering an ajax function in WordPress: You can add this in the theme functions.php file.

// Simple Ajax function
add_action( 'wp_ajax_nopriv_simple_ajax_func', 'simple_ajax_func' );
add_action( 'wp_ajax_simple_ajax_func', 'simple_ajax_func' );

function simple_ajax_func() {
echo json_encode(array('success' => true));

wp_die();
}

2. Calling that ajax function from JavaScript:

var ajax_url = '<?php echo admin_url( 'admin-ajax.php' ); ?>';

jQuery.ajax({
url : ajax_url,
type : 'post',
data : {
action : "simple_ajax_func",
},
success : function( response ) {
console.log('Success');
}
});

jQuery load Wordpress pages via ajax

So I was actually able to get this working by following the tutorial I mentioned previously; I think the tutorial may have just been written a bit unclearly..

Step 1

Create a custom page template which is done by creating a PHP file in the root directory with a comment header similar to this:

<?php
/*
Template Name: Ajax
*/
?>

I titled it Ajax for the purpose of semantics, but in the tutorial the original author titled it 'Triqui Ajax'. Keep note of the name of the PHP file you create as you'll use it again later in Step 4.

Step 2

Once that's done, you can continue coding your custom page template with the exception of adding the annotated lines below (lines 2 thru 5)

<?php
$post = get_post($_POST['id']); // this line is used to define the {id:post_id} which you will see in another snippet further down

if ($post) { // this is necessary and is a replacement of the typical `if (have_posts())`
setup_postdata($post); // needed to format custom query results for template tags ?>
<!-- everything below this line is your typical page template coding -->
<div <?php post_class() ?> id="post-<?php the_ID(); ?>">

<h2><?php the_title(); ?></h2>
<small><?php the_time('F jS, Y') ?></small>
<span><?php the_author() ?></span>

<div class="entry">
<?php the_content(); ?>
</div>

</div>

<?php }

Step 3

Once you've created your custom page template you should now login to the wp-admin and first, go to Settings -> Permalinks and set it to Day and Name or Custom Structure. The structure should look like this:

/%year%/%monthnum%/%day%/%postname%/

Whether you write that manually in Custom Structure or select Day Name it should look like the above snippet.

Step 4

Now go to create a new page. Pages ->Add New' and create a new page. Name it whatever you like, but it would be best to name it the same as the name of the page template you created in step 1.

Save it as an empty page. NOW THIS IS THE IMPORTANT PART You need to make sure that the permalink of the page has the exact same name as the file you created in Step 1. Only difference is it should be all lowercase.

Step 5

Before you save the page, also make sure you select the page template, from the select menu. If you do not see this menu it is because you probably did not create the template file correctly, or you did not create it in the root directory, or you did not create the comment header properly. Basically, the menu does not show if you do not have any custom page templates created, it only shows if it seems a proper custom page template saved in the root directory of your theme.

Sample Image

Review

You should now have a PHP file. And a page in the WP-admin. The page should have a permalink URL which matches the filename of the PHP file (all lowercase) and the page should be assigned the page template of that file.

This page should remain empty and should never be used.

Step 6

In header.php immediately following the code <?php wp_head() ?> add the following script:

<script>

jQuery(document).ready(function($){
$.ajaxSetup({cache:false});
$("THELINK").click(function(e){ // line 5
pageurl = $(this).attr('href');
if(pageurl!=window.location) {
window.history.pushState({path: pageurl}, '', pageurl);
}

var post_id = $(this).attr("rel")
$("#TARGET").load("http://<?php echo $_SERVER[HTTP_HOST]; ?>/ajax/",{id:post_id}); // line 12
return false;
});
});
</script>

Replace THELINK with the element where you have placed the <?php the_permalink ?> code.

The only lines that you need to change are lines 5 and 12. Notice on line 12 where it is written ajax this is the name of the PHP file I created in step 1 and the name of the permalink of the page I created in step 5.

Also on line 12 at the beginning of that line, you should change TARGET to the element in which the content should be loaded.

Make sure you've properly loaded jQuery before this script.

Step 7

Moving on to your index.php file or whichever file your loop is in. Find where-ever you have the code the_permalink which will be on an anchor tag. You will need to add a rel attribute with the_ID() which is used by {id:post_id} on line 12 in step 6:

<a href="<?php the_permalink(); ?>" class="bar" rel="<?php the_ID(); ?>" title="<?php the_title(); ?>">

Done

That's it. It should now work. The pages should be loaded with AJAX, and the URL of the browser will also change to match.

You can now go about creating as many pages as your hearts desire, creating other custom page templates, and assigning them, whatever you like.. Just let that file you created in Step 5 live where it is as an empty page forever.

If it still does not work, you are probably hopelessly lost and have no idea what your doing. You most likely have created some sort of jQuery conflict or have not loaded jQuery properly.

Wordpress load php content via AJAX

in your header.php add this to declare your ajax url

<script>var ajaxURL = '<?php echo esc_js(admin_url('admin-ajax.php'));?>';</script>

then in your JS.

$(document).delegate('h4.homus-partners-global-ajax', 'click', function(event) {
event.preventDefault();
var pb_cat = $(this).data('pb-cat');
var data = {
'action': 'GetPost',
catURL : "loop_"+ pb_cat,
};
$.post(ajaxURL, data, function(response) {
$( 'ul.homus-partners-section-slide' ).html(response);
});

});

then in your functions.php

function GetPost(){
$cat = $_POST['catURL'];
get_template_part($cat);
exit();
}
add_action('wp_ajax_nopriv_GetPost', 'GetPost');
add_action('wp_ajax_GetPost', 'GetPost');

How to load post in wordpress with ajax?

I want update my code, ajax load post with fetch api:

PHP code:

// Enqueue script.
wp_enqueue_script( 'ajax-load-post' );
wp_localize_script(
'ajax-load-post',
'ajax_load_post_data',
array(
'ajax_url' => admin_url( 'admin-ajax.php' ),
'ajax_nonce' => wp_create_nonce( 'ajax_load_post' ),
)
);

// Ajax handle.
add_action( 'wp_ajax_load_post', 'ajax_load_post' );
add_action( 'wp_ajax_nopriv_load_post', 'ajax_load_post' );
function ajax_load_post() {
check_ajax_referer( 'ajax_load_post', 'ajax_nonce' );

$post_query = new WP_Query(
array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 3,
)
);

ob_start();
if ( $post_query->have_posts() ) {
while ( $post_query->have_posts() ) {
$post_query->the_post();

echo get_the_title() . '<br>';
}
} else {
echo 'No posts found!';
}
$response['content'] = ob_get_clean();

wp_send_json_success( $response );
}

JS code:

// In js file.
document.addEventListener(
'load',
function() {
var data = {
action: 'load_post',
ajax_nonce: ajax_load_post_data.ajax_nonce,
};

data = new URLSearchParams( data ).toString();

var request = new Request(
ajax_load_post_data.ajax_url,
{
method: 'POST',
body: data,
credentials: 'same-origin',
headers: new Headers(
{
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
}
)
}
);

fetch( request )
.then(
function( res ) {
if ( 200 !== res.status ) {
console.log( 'Status Code: ' + res.status );
throw res;
}

return res.json();
}
).then(
function( json ) {
if ( ! json.success ) {
return;
}

console.log( 'Json data:', json.data );
}
).catch(
function( err ) {
console.log( err );
}
).finally(
function() {
console.log( 'All Done!' );
}
);
}
);


Related Topics



Leave a reply



Submit