I’ve been trying to solve this using various methods like JSON.stringify
, JSON.parse
, json_encode()
, json_decode()
, stripslashes()
, find and replace
, etc, etc.
But I can’t figure out where and if to encode the JS object to get it back from the database intact.
Here is what I’m doing at the moment:
1. Send the JS object via ajax to the WP plugin:
var data = {
action : 'store_object',
obj: myObject
};
$.post(ajaxurl, data).done(function(res) {
console.log(res);
});
2. Save the object in the WP plugin’s options:
$myObject = $_POST['obj'];
$options = $this->get_admin_options();
$options['settings'] = $myObject;
update_option($this->admin_options_name, $options);
3. Print the saved object as a JavaScript object:
$options = $this->get_admin_options();
?>
<script>
;(function ($, window, document, undefined ) {
$(document).ready(function() {
$('#el').pluginName(<?php echo stripslashes(json_encode($options['settings'])); ?>);
});
})(jQuery, window, document);
</script>
The contents of myObject may contain HTML code or special characters, and this is where the problem comes from. I can’t figure out how to cover all corner cases. For example, the code above will translate this:
<a href="http://google.com">Link</a>
Hello!
This is a new line.
Into this:
<a href="http://google.com">Link</a>
Hello!n
This is a new line.n
The HTML renders properly, but the n symbol does not.
So, what is the safest way to do something like this?
JS Object -> ajax -> wp database -> echo the object as a JS Object