Aravinth E Aravinth E - 1 month ago 9
Javascript Question

How to pass an array from php (using json_encode) to javascript

My java script. I want to display image. the javascript require image path as array format. I tried to supply the path throw ajax. its not working. when i use hard code its working. my javascipt below. its not working. the working code supply below the javascript and my php file code also there.

$(function () {
$.get( "php/building_edit_image_get_db.php", function( your_return_data ) {
alert(your_return_data);

$("#editimagefile").fileinput({
showUpload: false,
showCaption: false,
overwriteInitial: true,
initialPreview: [your_return_data],
initialPreviewAsData: true, // identify if you are sending preview data only and not the raw markup
initialPreviewFileType: 'image', // image is the default and can be overridden in config below
browseClass: "btn btn-primary btn-lg",
allowedFileExtensions : ['jpg', 'png','gif']
});
});
});


It's not working. when i place hardcode its working properly the script is below

$(function () {
$.get( "php/building_edit_image_get_db.php", function( your_return_data ) {
alert(your_return_data);

$("#editimagefile").fileinput({
showUpload: false,
showCaption: false,
overwriteInitial: true,
initialPreview: [
"http://lorempixel.com/800/460/people/1",
"http://lorempixel.com/800/460/people/2"
],
initialPreviewAsData: true, // identify if you are sending preview data only and not the raw markup
initialPreviewFileType: 'image', // image is the default and can be overridden in config below
browseClass: "btn btn-primary btn-lg",
allowedFileExtensions : ['jpg', 'png','gif']
});
});
});


My php file for returing array value.

session_start();
require_once ('../aiboc_admin/class/Buidling_Image.php');

$editid = $_SESSION['BUILD_LIST_EDIT_ID'];

$getimgs = Buidling_Image::GetGalleryImageByID($editid);

foreach ($getimgs as $setimgs)
{
$imgs[] = $setimgs['img_url'];
}
echo json_encode($imgs,JSON_UNESCAPED_SLASHES);

Answer

You should use $.parseJSON() since you're getting json format when you use json_encode :

$.get( "php/building_edit_image_get_db.php", function( your_return_data ) {

    $("#editimagefile").fileinput({
        showUpload: false,
        showCaption: false,
        overwriteInitial: true,

        initialPreview: $.parseJSON(your_return_data),

        initialPreviewAsData: true, // identify if you are sending preview data only and not the raw markup
        initialPreviewFileType: 'image', // image is the default and can be overridden in config below
        browseClass: "btn btn-primary btn-lg",
        allowedFileExtensions : ['jpg', 'png','gif']
    });

});

Or you could use $.getJSON() instead of $.get() request, then you don't need to parse it :

$.getJSON( "php/building_edit_image_get_db.php", function( your_return_data ) {

Hope this helps.