• Status: Solved
  • Priority: Low
  • Security: Public
  • Views: 203
  • Last Modified:

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
0
Adebayo Ojo
Asked:
Adebayo Ojo
  • 4
  • 3
1 Solution
 
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
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy 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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

  • 4
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now