I have come across quite an odd problem when using the update_option
function, and I am sure that I've tried everything I can think of to get it working, but unfortunately it isn't.
I'm using AJAX to submit a form (using the popular method described here) in the backend, on a custom options page. Everything is working, except for the update_option
part. I just don't understand, is there an issue with using that function in an AJAX function callback?
public function vmAddApp() {
parse_str( stripslashes( $_POST[ 'data' ] ), $data );
$nonce = $_POST[ 'nonce' ];
$app_info = $data[ 'vm_fbconnect' ];
$option = get_option( 'vm_fbconnect', array() );
$appId = $data[ 'vm_fbconnect' ][ 'appId' ];
$secret = $data[ 'vm_fbconnect' ][ 'secret' ];
$app_response = wp_remote_get( 'https://graph.facebook.com/' . $appId );
$response_body = json_decode( $app_response[ 'body' ] );
$app_name = $response_body->name;
$new_app = array(
'name' => $app_name,
'id' => $appId,
'secret' => $secret
);
$option[ 'apps' ][] = $new_app;
$data = update_option( 'vm_fbconnect', $option );
// UPDATE:
// If I put either:
// $data = $option; // <- this returns the option correctly, see below
// or
// $data = get_option( 'vm_fbconnect', array() ); // <- this returns 'Array' as a string
// But regardless, both SAVE 'Array' as the option's value..
header( "content-type: application/json" );
$response = array( 'data' => $data );
echo json_encode( $response ); // <- this is how I'm getting the response in the JS console
exit;
}
Edit 1: Debugging (I updated the code above, see comments)
This is what I get when I return the modified option from inside the function:
This is what I get when I use get_option
again.
After the option has been saved and I am done with the form, sometimes I will go right into the page currently displayed and do die( var_dump( get_option( 'vm_fbconnect', array() ) );
and it says just string(5) 'Array'
.
Also, I'm always careful to reset the option before trying each time, and careful to make sure I commented out the delete_option
function when trying again! :)
var_export
or similar on the$option
before it is updated to see if it's not happening before theupdate_option
?update_option
, I have narrowed it down to that exact function.