My ajax call output is always showing 0 as output don't know why
In functions.php
I have this code
function get_data() { $abc = '1'; $result = $wpdb->get_results("SELECT * FROM ".$wpdb->options ." WHERE option_name LIKE '_transient_%'"); echo $result; //returning this value but still shows 0 wp_die(); } add_action( 'wp_ajax_nopriv_get_data', 'get_data' ); add_action( 'wp_ajax_get_data', 'get_data' );
And my ajax call is in a javascript
$('body').on("click", ".re-reset-btn", function(e){ var panel = $('#re-compare-bar'); $.ajax({ type : "GET", dataType : "json", url : "/wp-admin/admin-ajax.php", data : {action: "get_data"}, success: function(response) { alert("Your vote could not be added"); alert(response); } }); $("#re-compare-bar-tabs div").remove(); $('.re-compare-icon-toggle .re-compare-notice').text(0); });
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.
When you're going to make an Ajax call you'll need to send the request to the admin-ajax. php file, which is a part of WordPress core. This file is responsible for handling and processing all of your Ajax requests within the WordPress context. Do NOT use the direct URL of the file path.
Since WordPress uses Ajax by default in the admin dashboard, adding more Ajax functionality there is not difficult. If you want to use Ajax on the front end of your site, however, you will need to understand how the Ajax URL works. In WordPress, your admin-ajax. php file has a URL.
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); } });
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