I am trying to return HTML through $.ajax
, this is my code:
$(document).ready(function() {
$(".click").on('click',function() {
var id= $(this).attr("data-id");
$.ajax({
type: "POST",
url: "getevents.php",
data: {id:id},
dataType: "html",
success: function(response){
alert(response);
$('.headimg').html(response);
}
});
})})
My PHP code:
$singleevent = mysqli_query($link, "SELECT `content` FROM `events` WHERE `id`
= $id") ;
if(!$singleevent){
echo mysqli_error();
}
else {
$result = mysqli_fetch_array($singleevent);
echo $result;
}
Link to be clicked:
<a class='click' data-id='<?=$rows["id"];?>'><?=$rows['title'];?></a>
In alert() this is what I get Array
If I do print_r() instead of echo this is what I get
[0] => <div class='row'>
<div class='col-sm-12'>
<img src='img/img.png' class='img-responsive'>
</div>
<div class='col-xs-12'>
<p> October 14th | All Day</p>
</div>
</div>
[content] => <div class='row'>
<div class='col-sm-12'>
<img src='img/img.png' class='img-responsive'>
</div>
<div class='col-xs-12'>
<p> October 14th | All Day</p>
</div>
</div>
How to I put it in HTML rather than array?
The result is what you get if you do echo array(1,2,3)
, you can not echo a array. Besides that, a PHP array isn't a Javascript array, so javascript doesnt understand the result.
You currently fetch the result from the database, which has two values because you fetch it as fetch_array(), which returns the data double:
- Once as numerical values ([0],[1],[2] etc)
- Once as named values (['content'],['example'],['etc'])
To remedy this, use fetch_assoc(). That will only return the last one (the named).
But, then you still have an array with a value, so javascript will still get "Array" as you try to echo that. You can now do echo $result['content'];
to fix this.
There is a (IMO) better method, which is a bit more complex, but a lot more expendable (what if you want 2 or 3 or ... values returned?), which is called JSON format.
In PHP you do echo json_encode($result);
which will result in a weird look array in text format. Now you go to you Javascript AJAX function and add dataType: "json"
to it. You can now use response.content
, or response.example
, or response.whateverYouSelectInPHP