Saving api options in WordPress using ajax,

I have been dealing with this problem for a long time. I have a options page for a theme, and one option is registered.

I try to update the option via ajax every time the user clicks the save button, here is my code.

JS:

function save_main_options_ajax() { $('.main-options-form').submit( function () { var b = $(this).serialize(), optdata = { action : "wp_ajax_main_options_save", data: b }; $.post( ajaxurl, b, function (response) { if (response == 1 ) { alert('sucess'); } else { alert(optdata);} }); return false; }); } save_main_options_ajax(); 

php:

  function main_options_save_ajax() { check_ajax_referer('_wpnonce', '_wpnonce' ); $data = $_POST; unset($data['option_page'], $data['action'], $data['_wpnonce'], $data['_wp_http_referer']); if ( update_option('main_options', $data ) ) { die(1); } else { die (0); } } add_action('wp_ajax_main_options_save', 'main_options_save_ajax' ); 

The answer I see in firebug is 0. I'm not sure what is missing here, I tried this with some options, but nothing works.

+4
source share
2 answers

Found a way to save settings using ajax when using the settings API.

The main mistake I made in my code is that I used the wrong URL.

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

Since we are using this URL, there is no need for the php function to process the request, as options.php handles all this for us.

Therefore, we only need to process 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, after saving, I received a warning about successful completion, and my options were saved.

Note: There is only one feature that I noticed. Upon completion of the POST request and showing a warning of success, the page makes a GET request for the version page of the parameter page, in which the parameters &settings-updated=true added to the end of the URL.

I don’t know whether to worry about it, I did not encounter any problems, but in the end it may be something that needs to be considered.

+8
source

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

Read 5 great tips here for more recommendations.

+2
source

Source: https://habr.com/ru/post/1415855/


All Articles