I am getting response in jquery as below. I want to show images from the db through the ajax request. My controller code :
public function images($id='')
{
$this->load->model('gallery');
$data = this->gallery_model->getimages($this->input->post('id'));
echo json_encode($data);
}
My ajax :
function imageslide(folderid){
$.ajax({
url: "<?php echo site_url() ?>/welcome/images",
type: "POST",
dataType: "json",
data: {id: folderid},
success: function(result) {
if(result){
resultObj = eval (result);
alert(JSON.stringify(resultObj));
}else{
alert("error");
}
}
});
The result which i received in the Network
tab is
[{"id":"153","file_name":"DSC00081.JPG","created":"2017-05-23 09:36:32","modified":"2017-05-23 09:36:32","status":null,"folder_id":"50"},{"id":"154","file_name":"DSC00082.JPG","created":"2017-05-23 09:36:32","modified":"2017-05-23 09:36:32","status":null,"folder_id":"50"},{"id":"155","file_name":"DSC00083.JPG","created":"2017-05-23 09:36:32","modified":"2017-05-23 09:36:32","status":null,"folder_id":"50"}]
I do not know how to show image in the browser in the <img>
tag. As you can see, I am getting jpeg
in the alert window. Kindly help me through.. Thanks in Advance!
You have received JSON object in result
. Just loop through it, using
$.each(result, function(key, value){ $('#container').append('<img src=" +value.file_name + " />'); })
You can append the imagen using jQuery, for example with the first index of array:
$('#container').append('<img src="' + result[0].file_name + '" />');
If you want to add each image, you can use forEach loop.
result.forEach(function (image) {
$('#container').append('<img src="' + image.file_name + '" />');
});
Copying from your code
function imageslide(folderid){
$.ajax({
url: "<?php echo site_url() ?>/welcome/images",
type: "POST",
dataType: "json",
data: {id: folderid},
success: function(result) {
if(result){
resultObj = eval (result);
var HTMLbuilder = "";
for(var i = 0; i < resultObj.length; i++){
var imgHtml = "<img src='path-toImage/" + resultObj[i].file_name + "'>";
HTMLbuilder = HTMLbuilder + imgHtml;
}
$("#imgContainer").html(HTMLbuilder);
}else{
alert("error");
}
}
});
Don't forget to have the div with the appropriate ID on the HTML
<div id="imgContainer"></div>
On pure js: Plunker
result.forEach(img => {
let element = document.createElement('img');
element.width = '100'
element.src = img.path;
parentEl.appendChild(element)
})