So, I am developing my own blog type of website, and I bumped into a problem recently while trying to get rid of JS from my code. So I have show.js and showpost.php. Here is my JS code that was showing blog posts while I was using ajax js:
load: function () {
posts.ajax({ req: "show" }, function () {
document.getElementById("cwrap").innerHTML = this.response;
});
},
everything worked just fine. But when I tried to replace that with a JQuery version
jQuery.ajax({
type: "GET",
url: 'app/showpost.php',
dataType: 'text',
success: function (data) {
console.log(data);
console.log("okokok");
document.getElementById("cwrap").innerHTML = this.response;
}
});
it doesn’t work how it’s intended!
Now to explain how my showpost.php file works:
<?php
include_once 'config.php';
echo('');
try {
$stmt = $pdo->prepare("SELECT `name`, `likes`,`imagename`,`comment_id`, `timestamp`, `message` FROM `posts` WHERE `post_id`=? ORDER BY `timestamp` DESC");
$stmt->execute([$_POST['pid']]);
} catch (Exception $ex) {
die($ex->getMessage());
}
while ($r = $stmt->fetch(PDO::FETCH_NAMED)) {
?>
<div id="post" style="box-shadow: 0 .15rem 1.75rem 0 rgba(58,59,69,.15)!important;">
<button id="<?=$r['comment_id']?>" name="like" class="btn" style=" float: right;" action="likepost.php" method="post"><svg xmlns="http://www.w3.org/2000/svg" enable-background="new 0 0 24 24" height="24" viewBox="0 0 24 24" width="24"><g><rect fill="none" height="24" width="24" y="0"/></g><g><g><path d="M13.12,2.06L7.58,7.6C7.21,7.97,7,8.48,7,9.01V19c0,1.1,0.9,2,2,2h9c0.8,0,1.52-0.48,1.84-1.21l3.26-7.61 C23.94,10.2,22.49,8,20.34,8h-5.65l0.95-4.58c0.1-0.5-0.05-1.01-0.41-1.37C14.64,1.47,13.7,1.47,13.12,2.06z M3,21 c1.1,0,2-0.9,2-2v-8c0-1.1-0.9-2-2-2s-2,0.9-2,2v8C1,20.1,1.9,21,3,21z"/></g></g></svg></button>
<date><?=$r['timestamp']?></date>
<h4>Bugs: <?=$r['likes']?></h4>
<h3><?=$r['name']?></h3>
<div class="message">
<?=$r['message']?>
</div>
<img src="static/<?=$r['imagename']?>">
</div>
<?php }
$stmt = null;
$pdo = null;
?>
as you can see, its a Php file with a little of html. It worked fine when I was using Xhr, but now with Jquery it doesn’t work! Please help!
EDIT: document.getElementById("cwrap").innerHTML = data;
doesn’t change anything, it might be a problem of my showpost.php not sending out the html part.
2
Answers
datatype needs to be html or json
The problem is here in your
success(data)
callback function.You are getting
data
but you are usingthis.response
which is going to be undefined because there is no such variable defined. Also the dataType in ajax call should be html i.e.,dataType : 'html',
.So it should be like: