Skip to content
Advertisement

How to call ajax in wordpress

My ajax call output is always showing 0 as output don’t know why

In functions.php I have this code

JavaScript

And my ajax call is in a javascript

JavaScript

I’m making ajax call in wordpress without use of plugin but not getting what I’m passing.Even If I output $abc still it shows 0.

Advertisement

Answer

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:

JavaScript

After localizing your JS file, you can use my_ajax_object object in your JS file:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement