I want to send current category of the page to ajax. I am using WordPress for my blog website. I want to send current page category to infi.php, But I don’t know how to do this.
my ajax
$.ajax({
type: "POST",
async: false,
url: "/infi.php",
data: {pcount:post_page_count},
success:
function(result){
$("#gizinfi").append(result);
}
});
To use AJAX properly in WordPress there are a few steps you need to take.
Firstly, assuming you are registering and enqueueing your javascript file properly (if you aren’t or don’t know what this means you should check out how to enqueue files in WordPress), you need to localise the file. In your functions.php file you can localize a file like so…
Now you need some way of accessing the category ID from your javascript. You could simply include an empty span in your template somewhere and store your category_id as a data attribute, then you can find it easily using javascript. You can also add a ‘nonce’ for security reasons, this allows you to check that it is your ajax call that is accessing your PHP, not a randomer. So we’ll add this to your header.php…
Now in your example.js file you can create your AJAX function…
Then you need to create a PHP function that handles your AJAX request (could go in your infi.php file as long as you are including that file properly but may be better in your functions.php file). for example…
Those last 2 lines bind the function to your ajax call. And that should be all you need.
Hope that helps
Dan