Hello,
The data for the focus keywords are saved in a meta key called rank_math_focus_keyword
and saved inside the postmeta table with the ID of the post where this should be present in the field post_id
.
That’s what our PHP code snippet does, it adds the data into this field using the init
hook from WordPress.
In this case, you would need to make sure that the AJAX request you are currently using is able to connect to the database and perform the same actions and save data into the database.
Please note that you can submit this with an AJAX request but you would still need to catch the response and use PHP to save the data into the postmeta table, so it would be better to skip the AJAX part and save it directly using the PHP code snippets we shared in the tutorial above.
If you want some code sample to save the data using AJAX this is a very simple example:
jQuery(document).ready(function($) {
// AJAX request to save data
$('#my-form').on('submit', function(e) {
e.preventDefault();
// Get form data
var formData = $(this).serialize();
// AJAX request
$.ajax({
url: ajaxurl,
type: 'POST',
data: {
action: 'save_data',
form_data: formData
},
success: function(response) {
// Handle success response
console.log(response);
},
error: function(error) {
// Handle error response
console.log(error);
}
});
});
});
And to catch the request you could use something like this in your functions.php
file or similar:
function save_data_callback() {
// Verify the AJAX request and user permissions
if (wp_verify_nonce($_POST['nonce'], 'my_ajax_nonce') && current_user_can('edit_posts')) {
// Get form data
$form_data = $_POST['form_data'];
parse_str($form_data, $form_fields);
// Get the post ID
$post_id = isset($form_fields['post_id']) ? intval($form_fields['post_id']) : 0;
// Save data into postmeta table
if ($post_id > 0) {
foreach ($form_fields as $key => $value) {
$sanitized_value = sanitize_text_field($value);
update_post_meta($post_id, $key, $sanitized_value);
}
// Return a success response
wp_send_json_success('Data saved successfully.');
}
}
// Return an error response
wp_send_json_error('Error saving data.');
}
add_action('wp_ajax_save_data', 'save_data_callback');
add_action('wp_ajax_nopriv_save_data', 'save_data_callback');
The code snippets shared above would need to be modified to cater to your specific needs on the website.
Don’t hesitate to get in touch if you have any other questions.