Saving wordpress settings api options with ajax,

久未见 提交于 2019-12-03 14:12:49
Alex

Found a way to save settings via ajax when using Settings API.

The main mistake that i made in my code is that i used the wrong url path.

Instead of using the standard ajaxurl which is what you would usually use when making ajax calls in wordpress; we use the action call of your settings api form, which is options.php.

Because we use this url path, there is no need for a php function to handle the request as options.php handles all of this for us.

Therefore we only need to handle the js function which looks like this in my instance.

 function save_main_options_ajax() {
           $('.main-options-form').submit( function () {
                var b =  $(this).serialize();
                $.post( 'options.php', b ).error( 
                    function() {
                        alert('error');
                    }).success( function() {
                        alert('success');   
                    });
                    return false;    
                });
            }
 save_main_options_ajax();

That is it, after saving i got the success alert, and my options were saved.

Note: There is only one peculiarity that I noticed. After finishing the POST request, and showing the success alert, the page makes a GET request for a page version of your options page which has the parameters &settings-updated=true added onto the end of the url.

I don't know if this is something to be worried about, I have not encountered any problems, but it could be something to consider in the long run.

Mr2P

Try to change action value from wp_ajax_main_options_save to main_options_save. Wordpress adds the prefix wp_ajax_ to your action value automatically like wp_ajax_{your_posted_action}.

Read 5 excellent tips here for additional best practises.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!