Ivijan Stefan Stipić
Ivijan Stefan Stipić

Reputation: 6678

How properly proccess jQuery AJAX in WordPress plugin

I'm trying to add ajax autosave to my settings page in plugin and made this code:

<?php
function cfgeo_settings_javascript() { ?>
    <script type="text/javascript" >
    (function($){
        $(document).ready(function(){
            $("input[id^='cf_geo_'], select[id^='cf_geo_'], textarea[id^='cf_geo_']").on("change keyup", function(){
                var This = $(this),
                    name = This.attr("name"),
                    value = This.val(),
                    data = {};

                data['action'] = 'cfgeo_settings';
                data[name] = value;

                console.log(data);
                console.log(ajaxurl);

                $.post(ajaxurl, data).done(function(returns){
                    console.log(returns);
                });
            });
        });
    }(window.jQuery));
    </script> <?php
}
add_action( 'admin_footer', 'cfgeo_settings_javascript');

function cfgeo_settings_callback() {
    global $wpdb; // this is how you get access to the database
    var_dump($_POST);
    if (isset($_POST)) {
        // Do the saving
        $front_page_elements = array();
        $updates=array();
        foreach($_POST as $key=>$val){
            if($key != 'cfgeo_settings')
              update_option($key, esc_attr($val));
        }
        echo 'true';
    }
    else
        echo 'false';

    wp_die(); // this is required to terminate immediately and return a proper response
}
add_action( 'wp_ajax_cfgeo_settings', 'cfgeo_settings_callback');
?>

I find problem that everytime I want to send this simple ajax request I get 0 what is realy enoying.

Here is Console Log when I try to made some change in select option box:

Object {action: "cfgeo_settings", cf_geo_enable_ssl: "true"}
admin.php?page=cf-geoplugin-settings:1733 /wp-admin/admin-ajax.php
admin.php?page=cf-geoplugin-settings:1736 0

What's wrong in my ajax call or PHP script?

I need to mention that both codes are in the one PHP file.

Upvotes: 0

Views: 278

Answers (2)

Shashank Sharma
Shashank Sharma

Reputation: 595

You should have to follow guideline of WordPress ajax method by this admin ajax reference. Please follow this.

https://codex.wordpress.org/AJAX_in_Plugins

Upvotes: 1

topdown
topdown

Reputation: 456

Here is a working example with notes included in the comments, there are a lot of don't does in your code and this example addresses those concerns in the code comments. https://gist.github.com/topdown/23070e48bfed00640bd190edaf6662dc

Upvotes: 1

Related Questions