1

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

3
  • $myObject = $_POST['obj']; Commented Jan 7, 2016 at 16:00
  • Yes, thanks for that. Commented Jan 7, 2016 at 16:04
  • Does this help: stackoverflow.com/a/6352070/870729 Commented Jan 7, 2016 at 16:09

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.