HTML string (& nbsp;) breaking JSON

I collect some data from my page, storing the data in an array for multiple use on the page and sending a copy of the array through AJAX, storing the data in the database on the PHP page.

One part of the data that I store in the array is the output of the TinyMCE WYSIWYG editor, so it contains HTML, but just found that this is a problem. I will explain:

After entering one line of text in my WYSIWYG editor and I fire the AJAX event, this is the JSON line displayed on my console and everything works fine, the database was sent and saved:

{"id":"229","topic":"","title":"","description":"","content":"<p>fgfgfdg.</p>","keywords":""}

If I write two lines of text, this is a JSON line and was successful:

{"id":"229","topic":"","title":"","description":"","content":"<p>fgfgfdg.</p>\n<p>fgfgfdg</p>","keywords":""}

Now, if I write one line of text and press return, and do not type anything in the second line, I get the next one that fails.

{"id":"229","topic":"","title":"","description":"","content":"<p>fgfgfdgdfgdfgdfgdfg.</p>\n<p>&nbsp;</p>","keywords":""}

, &nbsp; - JSON-. PHP , . print_r(json_decode($json)) . - ?

HTML- jQuery:

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

<script>
var post_data = {};

post_data.id = post_id;
post_data.topic = topic;
post_data.title = title;
post_data.description = description;
post_data.content = tinyMCE.activeEditor.getContent();
post_data.keywords = keywords;

post_data = JSON.stringify(post_data);

save_post_request = $.ajax({
    url: 'ajax/save-post.php',
    type: 'POST',
    data: "save_mode="+save_mode+"&post_data="+post_data,
    dataType: 'text',
    cache: false
});
</script>

PHP:

header('Content-type: application/json; charset=UTF-8');

$post_data = isset($_POST['post_data']) ? $_POST['post_data'] : null;
$post_data_arr = json_decode($post_data, true);
$post_id = $post_data_arr['id'];
$topic = $post_data_arr['topic'];
// others
$content = $post_data_arr['content'];

if (!$post_data_arr['id']) {
    // fails here
    // id is not accessible when the JSON contains <p>&nbsp;</p> in the 'content' item
}

, Firebug:

enter image description here

+4
1

JSON URL- , URL-.

& URL ( /), , .

encodeURIComponent :

data: "save_mode="+encodeURIComponent(save_mode)+"&post_data="+encodeURIComponent(post_data),

, jQuery, URL . jQuery . data :

data: {
    save_mode: save_mode,
    post_data: post_data
}, 
+7

All Articles