Văn Lộc Văn Lộc - 1 month ago 6
Ajax Question

How to remove special character in Ajax?

I want to send the image to View through by Ajax.

But in Admin page with PHP I add multiple images. So, list image will have format like:

["image_1.jpg","image_2.jpg","image_3.jpg"]


I want to show list image in
div#res
.
It does not remove character like:
[" "," "]
.

Here my code:

$(document).ready(function(){
$('li.thang').click(function(){
var id_thang = $(this).attr('value');
$.ajax({
url: baseUrl+'/Home/getImage',
dataType: 'json',
type: 'POST',
data: {id_thang: id_thang},
}).done(function(result) {
var image_list = result.image_list;
for(m = 0; m < image_list.length; m++){
'<img data-u="image" src="img/product/' + image_list[m]+ ' alt="" />' + '</br>';
}
$('#res').html(image_list);
})
});
});


It becomes to:

<img data-u="image" src="img/product/["image_1.jpg","image_2.jpg","image_3.jpg"] alt="" />


I only need like this:

<img data-u="image" src="img/product/image_1.jpg" alt="" />
<img data-u="image" src="img/product/image_2.jpg" alt="" />
<img data-u="image" src="img/product/image_3.jpg" alt="" />


Updated 1 with more information:

I have function to get image by id:

function getImage(){
$id_thang = $this->input->post('id_thang');
$input = array();
$input['order'] = array('id','ASC');
$get_image_thang = $this->Mmenushoatnao->get_info($id_thang);
echo json_encode($get_image_thang);
}


And here my full code in Ajax:

$(document).ready(function(){
$('li.thang').click(function(){
var id_thang = $(this).attr('value');
$.ajax({
url: baseUrl+'/Home/getImage',
dataType: 'json',
type: 'POST',
data: {id_thang: id_thang},
}).done(function(result) {
// console.log(result);
var image_list = result.image_list;
for(m = 0; m < image_list.length; m++){
image_list += '<img data-u="image" src="upload/hoatnao/hinhanh/' + result.image_list[m]+ ' alt="" />' + '</br>';
console.log(image_list);
}
$('#res').html(image_list);
})
});
});


Finally, I print it with
id=res
:

<div id="res" class="col-md-4 col-sm-4 col-xs-4">

</div>


And here is an image.

Each row has about four an image.

You can see in my database.


Answer

Use concatenation

var image_list = "";
for(m = 0; m < result.image_list.length; m++){
    image_list += '<img data-u="image" src="img/product/' + result.image_list[m]+ ' alt="" />'  + '</br>';
}
$('#res').html(image_list);

FYI, do console.log to make sure that you're getting proper data as per your need and I shown you a way to achieve that but make sure that you're using proper variable names.