Appending ajax return is not working.

I'm echoing some data from PHP to ajax, then I tried to append the result to an existing div, but ajax is returning html markup codes instead. How can I make this work please?

Ajax

function comment(cmt) {
    if (document.getElementById("comments").value == "") {
        alert('You can\'t submit an empty comment');
        exit();
    }
    $(document).ready(function() {
        comments = document.getElementById('comments').value;
        var input_id = cmt.parentNode.firstElementChild;
        post_id = input_id.id.split('_')[0];
        post_tag = input_id.id.split('_')[1];
        $.ajax({
            url: "functions/comments.php",
            type: "POST",
            data: { post_tag: post_tag, post_id: post_id, comments: comments },
            dataType: 'html',
            success: function(result) {
                document.getElementById("comment-id").append(result);
            }
        });
        document.getElementById("comments").value = "";
        //fetchComment();
    });
}

Open in new window


PHP - comments.php
<?php
// some codes here...
$commentResponse .= '<div class="commentDisplay">';
    $commentResponse .= '<a href="http://localhost:8080/reminderapp/user_audio.php?u='.$row['commenter'].'">'.'<img id="commentersid" src="user/'.$row['username'].'/'.$row['avatar'].'" alt="'.$row['username'].'">';
        if($row['aliascheck'] == '1') {
            $commentResponse .= '<span id="commentName">'.$row['fullname'].'</span>'.'</a>';
        } else {
            $commentResponse .= '<span id="commentName">'.$row['alias'].'</span>'.'</a>';
        }
        $commentResponse .= '<span id="commentDate">'.$readabledate.'</span>';
        $commentResponse .= '<span id="commentWords">'.$row['user_comments'].'</span>';
        if($row['commenter'] == $log_username) {
            $commentResponse .= '<span id="deleteCmt">'.'<input id='.$comment_id.' class="deleteComt" type="button" title="Delete" value="x" onclick="deleteComment(this.id);" style="background-color:lightgray;"/>'.'</span>';
        }
        $commentResponse .= '</div>';
        $commentResponse .= '<br />';
}
echo $commentResponse;
?>

Open in new window


When the comment function is fired, the PHP spit out the whole html markup back to my page via the ajax append method.

I'm getting this returned to my page:
HTML markup
Below is what I want to see on my page:
Expected result
Adebayo OjoRegional Network ManagerAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Leonidas DosasCommented:
In the success method can you type and post the result of
console.log(typeof  result);

Open in new window

and also could you post an image of console.log(result);
0
Leonidas DosasCommented:
Probably you have a string result and this causing the fail appending
0
Leonidas DosasCommented:
In the php code write:
$arr=array();
//all the code here...

array_push($arr,$commentResponse);
echo json_encode($arr);

Open in new window


And in the ajax success decode the string into html object via parseHTML or DOMparser and append this into the element that you want.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Determine the Perfect Price for Your IT Services

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden with our free interactive tool and use it to determine the right price for your IT services. Download your free eBook now!

Adebayo OjoRegional Network ManagerAuthor Commented:
Yes, console.log(typeof result) is returning a string as seen below:
console log
0
Adebayo OjoRegional Network ManagerAuthor Commented:
Thanks @Leonidas, your response gave me the heads-up to know what to do. The below gave me the expected result.

function comment(cmt) {
    if (document.getElementById("comments").value == "") {
        alert('You can\'t submit an empty comment');
        exit();
    }
    $(document).ready(function() {
        comments = document.getElementById('comments').value;
        var input_id = cmt.parentNode.firstElementChild;
        post_id = input_id.id.split('_')[0];
        post_tag = input_id.id.split('_')[1];
        $.ajax({
            url: "functions/comments.php",
            type: "POST",
            data: { post_tag: post_tag, post_id: post_id, comments: comments },
            dataType: 'html',
            success: function(result) {
                output = $.parseHTML(result),
                    $("#comment-id").prepend(output);
            }
        });
        document.getElementById("comments").value = "";
    });
}

Open in new window

0
Adebayo OjoRegional Network ManagerAuthor Commented:
I didn't have to use the below suggestion though:

$arr=array();
//all the code here...

array_push($arr,$commentResponse);
echo json_encode($arr);
0
Leonidas DosasCommented:
Happy New Year Adebayo. Greetings from  Greece.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
HTML

From novice to tech pro — start learning today.