show image from ajax response - javascript

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 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)
})

You have received JSON object in result. Just loop through it, using
$.each(result, function(key, value){
$('#container').append('<img src=" +value.file_name + " />');
})

Related

how to append a html tag from an ajax call response

I have an ajax function :
$('#app-name').change(function () {//1
console.log("inside change");
var applname= this.value;
console.log(applname);
$.ajax({//2
url: 'foo',
method : 'GET',
dataType : "json",
contentType: "application/json",
data: {"AppID":"appname"},
success: function(data){
var order_data = data;
$('#foo-name').html('');
$.each(order_data, function(i, item) {//3
console.log(order_data[i]);
$('<option value='+ order_data[i] +'>'+order_data[i]).html('</options>').appendTo('#foo-name');
});//3
}
});//2
});//1
This function is doing everything else except appending value to the html.
Am i doing it wrong? Can you help solve this issues.
Place the closing </option tag in the jQuery object you create. Don't set it through the html() method. Try this:
$('<option value="' + order_data[i] + '">' + order_data[i] + '</option>').appendTo('#foo-name');
That said, you can also improve performance of your code by building the string in the loop and appending it to the select once, like this:
success: function(data) {
var options = '';
$.each(data.split(/\n/), function(i, item) {
options += '<option value=' + item.trim() + '>' + item.trim() + '</option>');
});
$('#foo-name').html(options);
}
Update You also need to split() the text you state that you're returning before looping through it.
Please use below code in your ajax success event.
success: function(data) {
var _html = '';
$.each(order_data, function(i, item) {
_html += '<option value='+ item +'>'+item+'</options>';
});
$('#foo-name').append(_html);
}

How to append the JSON data to HTML in JavaScript?

I get some data using JSON array. I want to append each data in a div. But I don't get what's wrong in that?
controller
function get_performers()
{
$id = $this->input->post('id');
$exam = $this->input->post('exam');
$datas=$this->job->get_top_ten_st_data($id,$exam);
$out['student_details'] = $datas;
echo json_encode($out);
}
script
function get_performers(id,exam)
{
$.ajax({
url:"<? echo base_url();?>class_analysis/get_performers",
dataType: 'json',
type: "POST",
data: {id:id,exam:exam},
success:function(result) {
// alert("haii");
console.log(result);
result = JSON.parse(result);
var tab= "<div class='col-xs-2 blk-ht'> <span class='hd'>Names</span> </div>";
for(var i=0;i<result.student_details.length;i++)
{
tab=tab+"<div class='col-ds-1'><span class='subjNames'>" + result.student_details[i]["subject_name"]+ "</span></div> ";
}
jQuery("#subjectNames").append(tab);
}
});
}
Any problem in this?
Try html not append
jQuery("#subjectNames").html(tab);
Also if jQuery("#subjectNames") equal with null in your console this mean that you don't have element with id="subjectNames" in html not id="#subjectNames" or other. May be you use classes then try $(".subjectNames") with . not #
The Loop should work... Seems to be another problem with your result.
var tab= "<div class='col-xs-2 blk-ht'><span class='hd'>Names</span> </div>";
for(var i=0;i<20;i++)
{
tab=tab+"<div class='col-ds-1'><span class='subjNames'>" + "test: " + i + "</span></div> ";
}
jQuery("#subjectNames").append(tab);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="subjectNames"><div>
dataType: 'json' in $.ajax options - automaticaly parse your json
and USE JQUERY )))
IN SUCCES AJAX FUNCTION
$.each( result.student_details, function( key, value ) {
alert( key + ": " + value );
});
<?php
function get_performers()
{
$id = $this->input->post('id');
$exam = $this->input->post('exam');
$datas=$this->job->get_top_ten_st_data($id,$exam);
$out['student_details'] = $datas;
echo json_encode($out);
}
?>
<script>
$.ajax({
url:"<? echo base_url();?>class_analysis/get_performers",
dataType: 'json',
type: "POST",
data: {id:id,exam:exam},
success:function(result) {
$.each(response.student_details, function(key,value){
appendHtml(key,value);
});
}
});
function appendHtml(key,value)
{
var tab= "<div class='col-xs-2 blk-ht'> <span class='hd'>Names</span> </div>";
tab = tab+"<div class='col-ds-1'><span class='subjNames'>" +value+ "</span></div> ";
jQuery("#subjectNames").append(tab);
}
</script>

Codeigniter Jquery Ajax: How to loop returned data as html

Im new to JQuery AJAX thing, this is my script:
$(document).ready(function() {
$("#city").change(function() {
var city_id = $("#city").val();
if (city_id != '') {
$.ajax({
type: "POST",
url: "<?php echo base_url() ?>index.php/home/get_block_by_id/" + city_id,
success: function(block_list) {
// WHAT TO PUT HERE ?
},
});
}
});
If i put console.log(block_list) it returns the right data with JSON type:
[{"id":"1601","id_city":"16","block":"A"},
{"id":"1602","id_city":"16","block":"B"}]
What is the correct way to loop the returned data? I did this to see what the loop returned:
$.each(block_list, function() {
$.each(this, function(index, val) {
console.log(index + '=' + val);
});
});
But it was totally messed up :(, if the looped data is correct I also want to put the id as a value and block name as a text for my <option> tag how to do that? thank you.
UPDATE
Sorry, I have try both answer and its not working, I try to change my code to this:
$("#city").change(function(){
var city_id = $("#city").val();
$.get("<?php echo base_url() ?>index.php/home/get_block_by_id/" + city_id, function(data) {
$.each(data, function(id, val) {
console.log(val.id);
});
});
});
it returns :
**UNDEFINED**
I also try to change it into val[id] or val['id'] still not working, help :(
$.each(block_list, function(id, block){
console.log('<option value="' + block['id'] + '">' + block['block'] + '</option>')
});
The output would be:
<option value="1601">A</option>
<option value="1602">B</option>
try something like:
success: function(data, textStatus, jqXHR) {
if (typeof(data)=='object'){
for (var i = 0; i < data.length; i++) {
console.log(data[i].id + ':' + data[i].id_city);
}
}
}
if ur json output is in this format
[{"id":"1601","id_city":"16","block":"A"},
{"id":"1602","id_city":"16","block":"B"}]
then
var city_id = $("#city").val();
if (city_id != '') {
$.ajax({
type: "POST",
url: "<?php echo base_url() ?>index.php/home/get_block_by_id/" + city_id,
success: function(data) {
$.each(data, function(index)
{
console.log(data[index]['id']);
$('#'+ddname+'')
.append($("<option></option>")
.text(data[index]['id']+"-"+data[index]['block']));
});
},
});
}

How can I call ajax array passed from php json encode? zend framework 2

I can't call an arrays passed from the php json encode. I would concatenate 2 select state-contry-city. How can I do this??
This is the code:
I have 2 selects. I send the first value to an action:
php action into my controller:
public function regioniProvinceComuniAction(){
$response = $this->getResponse();
$request = $this->getRequest();
if ($request-> isPost()){
$post_data = $request->getPost();
$regione = (int)$post_data['regione'];
$province = (int)$post_data['province'];
}
if(isset($regione)){
$prov = $this->getProvincia($regione);
}
if(isset($province)){
$com = $this->getComuni($province);
}
$response->setContent(\Zend\Json\Json::encode(array('prov' => $prov, 'com' => $com)));
return $response;
}
This is my js file:
$("select#Regione").change(function () {
var regione = $("select#Regione option:selected").attr('value');
$.ajax({
type: 'POST',
url: '/zf-tutorial/public/regioni-province-comuni',
datatype: 'json',
data: { regione: regione },
success: function (data) {
alert (data);
}
});
});
An example of the alert function is like this:
{"prov":[{"id":"10","nome":"Genova"},{"id":"8","nome":"Imperia"},{"id":"11","nome":"La Spezia"},{"id":"9","nome":"Savona"}],"com":[]}
I tried to populate my second select via data.post like this, but the values are "undefined":
success: function (data) {
$('select#Provincia option').each(function(){$(this).remove()});
for(var i=0; i<data.length; i++){
$("select#Provincia").append('<option value="' + data[i].prov.id + '">' + data[i].prov.nome + '</option>');
}
i tried to do
for (var i = 0; i < data.prov.length; i++) {
$("select#Provincia").append('<option value="' + data.prov[i].id + '">' + data.prov[i].nome + '</option>');
}
if i set manually the var data, works fine, but with the response data doesn't work. i tried to do:
var prov = data.prov;
$("div#id").html(prov);
but it doesn't work. works only like this:
$("div#id").html(data);
and the output is the same
{"prov":[{"id":"10","nome":"Genova"},{"id":"8","nome":"Imperia"},{"id":"11","nome":"La Spezia"},{"id":"9","nome":"Savona"}],"com":[]}
You need to loop through the items in data.prov. Change your for loop to this:
for (var i=0; i<data.prov.length; i++){
$("select#Provincia").append('<option value="' + data.prov[i].id + '">' + data.prov[i].nome + '</option>');
}
jsFiddle Demo
EDIT
Solution found in comments: Can you try to change datatype in your $.ajax() call to dataType. I'm not sure if the case is important. Sounds like data is a string and not an object

$.ajax Get data does not append to var

I ve a problem with the output:i want to fill the ouptput whit some data from an ajaxcall.
the call is successfull(the output inside the each is filled with data)
but the output inside the each issnt apended to the output outside .
i always geht "
<ul id="listname" data-inset=true></ul>
and not
<ul id="listname" data-inset=true><li>some data</li></ul>
$("div:jqmData(role='collapsible')").each(function(){
var id = $(this).data("id");
var idDate=id.slice(7,18);
var listapp="id_col_"+idDate;
var listname="id_col_"+idDate;
output='<ul id="listname" data-inset=true>';
$.ajax({
url: 'lomodata.php',
data: 'timestamp='+idDate,
type: 'GET',
ContentType: "application/json",
dataType: "json",
success:function(res) {
if(res !='')
{
$.each(res, function(i, Object) {
output+='<li>'+Object.reg+'</li>';
console.log(output);
});
}
}
});
output+='</ul>';
$(this).append(output).trigger("create");
$(this).listview();
$(this).listview('refresh');
});
Note that $.ajax is by default asynchronous, and by the time you reach $(this).append(output), output is not yet defined, since the .ajax() call hasn't finished yet. You need to move the append to the success handler, or add the async: false option, so that $.ajax becomes a blocking call (although this defeats the purpose of using ajax):
success: function(res) {
if (res !='') {
var output='<ul id="listname" data-inset=true>';
$.each(res, function(i, Object) {
output+='<li>'+Object.reg+'</li>';
console.log(output);
});
output+='</ul>';
$(this).append(output).trigger("create");
}
}
AJAX is Asynchronous. When you write $.ajax( ... ), an HTTP request will be sent to the server, which will then move on to the next operation, output += '</ul>'. The HTTP request will not have finished by this time, and so your callback will not yet have been executed by the time you append output to the document.
$("div:jqmData(role='collapsible')").each(function () {
var el = this;
var id = $(this).data("id");
var idDate = id.slice(7, 18);
var listapp = "id_col_" + idDate;
var listname = "id_col_" + idDate;
$.ajax({
url: 'lomodata.php',
data: 'timestamp=' + idDate,
type: 'GET',
ContentType: "application/json",
dataType: "json",
success: function (res) {
output = '<ul id="listname" data-inset=true>';
if (res != '') {
$.each(res, function (i, Object) {
output += '<li>' + Object.reg + '</li>';
console.log(output);
});
}
output += '</ul>';
el.append(output).trigger("create");
el.listview();
el.listview('refresh');
}
});
});
If you move all lines of codes that use the output variable to the success function of the ajax call, you will see that it works. The problem is that you're using asynchronicity incorrectly.
Something like this:
$.ajax({
url: 'lomodata.php',
data: 'timestamp=' + idDate,
type: 'GET',
ContentType: "application/json",
dataType: "json",
success: function (res) {
if (res != '') {
var output = '<ul id="listname" data-inset=true>';
$.each(res, function (i, Object) {
output += '<li>' + Object.reg + '</li>';
});
output += '</ul>';
console.log(output);
$("#myObject").append(output).trigger("create");
$("#myObject").listview();
$("#myObject").listview('refresh');
}
}
});

Categories

Resources