An Ajax, JSON and PHP CMS problem

Let me start off describing the problem. I’m creating a blog for my website using Ajax, JSON and PHP so the user(s) won’t have the page reload every time it is save. I have it working except it doesn’t recognize carriage returns.

If I enter the following :
one
two
three
I get this
onetwothree
when I expect
one
two
three

The funny thing is it works in straight php.

Here’s the code:
index.php
[php]require_once ‘lib/includes/utilities.inc.php’;

use website_project\blog\Page;

$stmt = $blog->read();
require_once ‘lib/includes/header.inc.php’;
?>

<?php while ($row = $stmt->fetch()) { if ($row->sticky === 'yes') { $final_date = new DateTime($row->date_updated, new DateTimeZone('America/Detroit')); ?>
    <article id="blog" class="container blogArticle">

        <h1 class="title" contenteditable="true" data-id="<?php echo $row->id; ?>"><?php echo $row->title; ?></h1>
        <p class="author">by <?php echo $blog->getUsername($row->creator_id); ?> created on <?php echo $final_date->format("F j, Y"); ?></p>       
        <hr>
        <p class="content" contenteditable="true" data-id="<?php echo $row->id; ?>"><?php echo nl2br($row->content); ?></p>
        <hr>
    </article>
<?php } ?>
<?php } ?> <?php require_once 'lib/includes/footer.inc.php';[/php] cms.js [php]$(function () { var $blog = $('#blog'); function update(myData) { $.ajax({ type: "post", url: "forumsAjax.php", data: myData, success: function (info) { console.log(info); }, error: function (request, status, error) { output(request, status, error); // Not for production use: } }); // End of Ajax function: } // End of update function: $blog.on("focusout", function (event) { var article = event.target, id = $(article).data('id'), title = $(article).siblings('h1').text(), content = $(article).siblings('p.content').text(); if ($(article).hasClass('title')) { title = $(article).text(); } if ($(article).hasClass('content')) { content = $(article).text(); } var params = { id: id, title: title, content: content }; var myData = jQuery.param(params); console.log(myData); update(myData); }); // End of focusout function: }); // End of Document Ready Function;[/php] forumsAjax.php [php]<?php require_once 'lib/includes/utilities.inc.php'; /* Makes is so we don't have to decode the json coming from JQuery */ header('Content-type: application/json'); $data['id'] = filter_input(INPUT_POST, 'id', FILTER_SANITIZE_NUMBER_INT); $data['title'] = filter_input(INPUT_POST, 'title', FILTER_SANITIZE_FULL_SPECIAL_CHARS); $data['content'] = filter_input(INPUT_POST, 'content', FILTER_SANITIZE_FULL_SPECIAL_CHARS); $result = $blog->update($data); // Save the results from Ajax/JSON to a MySQL database table: if ($result) { $output = json_encode(['result' => "success"]); output($output); } /* If there is an error then change the error to the proper code and output the */ /* error message via Ajax /JQuery. */ function error($output, $code = 500) { http_response_code($code); echo $output; } /* If everything validates OK then send success message to Ajax/jQuery */ function output($output) { http_response_code(200); echo $output; }[/php] Any help would be appreciated and I will post more code if needed. I tried solving this on my own, but when I do a Google search I get these crazy scripts that in order to have carriage returns. There has to be an easier fix than doing that. P.S. I know I should had posted this in the Ajax category, but General PHP gets the most action and I visit this category the most. 8)

Here is a test script I came up for you solving the issue.
The form:
[php]
Article

	</form>[/php]

receiving ajax script:
[php]<?php
echo nl2br( $_POST[‘article’] );
[/php]

The javascript:
[php]
var mString = {};

	$('#btn').on('click', function() {
		
		mString.article = $('#text_val').val();

		$.post('ajax.php', mString, function(data) {
			$('#result').html(data);
		});
	});
</script>[/php]

Well after spending about a day on this problem I finally came up with the solution. I noticed that since I was using contenteditable=“true” in a p tag that it would give me a


, so I did a search that way.
http://stackoverflow.com/questions/18552336/prevent-contenteditable-adding-div-on-enter-chrome
This is on how I fixed the problem.
[php]$(function () {
var $blog = $(’#blog’);
function update(myData) {

    $.ajax({
        type: "post",
        url: "forumsAjax.php",
        data: myData,
        success: function (info) {
            console.log(info);
        },
        error: function (request, status, error) {
            output(request, status, error); // Not for production use:
        }
    }); // End of Ajax function:

} // End of update function:
 
/* This is the function(s) that solves the carriage return/new line problem */
$('p.content[contenteditable="true"]').keypress(function (event) {

    if (event.which != 13)
        return true;

    var docFragment = document.createDocumentFragment();

    //add a new line
    var newEle = document.createTextNode('\n');
    docFragment.appendChild(newEle);

    //add the br, or p, or something else
    newEle = document.createElement('br');
    docFragment.appendChild(newEle);

    //make the br replace selection
    var range = window.getSelection().getRangeAt(0);
    range.deleteContents();
    range.insertNode(docFragment);

    //create a new range
    range = document.createRange();
    range.setStartAfter(newEle);
    range.collapse(true);

    //make the cursor there
    var sel = window.getSelection();
    sel.removeAllRanges();
    sel.addRange(range);

    return false;
});

$blog.on("focusout", function (event) {

    var article = event.target,
            id = $(article).data('id'),
            title = $(article).siblings('h1').text(),
            content = $(article).siblings('p.content').text();

    if ($(article).hasClass('title')) {
        title = $(article).text();
    }
    if ($(article).hasClass('content')) {
        content = $(article).text();
    }



    var params = {id: id, title: title, content: content};

    var myData = jQuery.param(params);

    console.log(myData);

    update(myData);

}); // End of focusout function:

}); // End of Document Ready Function;[/php]

I have to say that I would not had in a million years come up with this solution, but I was always told that it was proper to give the solution. So that other people who might be having this problem will have an easier time in fixing it. Pay it forward. ;D

So, your new code converts a newline character to a br tag? Your problem, your solution, but my simple code does the same with less.

True (or should it be maybe?), but I’m not using a form, I’m using a

tag to insert my data with contenteditable. :wink: I theoretically will just have to use the class=“content” along with contenteditable to make it a CMS, the reason I say theoretically is that I haven’t tested out on multiple threads, but I’m pretty confident it will work. I don’t think I would be having the newline problem with the form in the first place, but I’m not going to convert it over to a form so I can’t say. So yes it’s probably safe to say it would be easier with your solution, but not the way I want to do it. :wink:

nl2br would replace the newline characters the same. The form was to show how I was doing it.

That wasn’t the problem, contenteditable was adding


instead of just
tag (I’m by no means a Javascript/JSON expert, but I would hazard a guess that it was also converting the
tags making nl2br useless )into the equation, with a form it doesn’t do that. I have nl2br added to the output. I’m trying to make it so if someone disables javascript it will still work (the output that is).

I eventually just want to make it where a person can add class=“cms” to their

or <h#> tags and it will be a mini CMS.

Sponsor our Newsletter | Privacy Policy | Terms of Service