Akash Gajbhiye
Akash Gajbhiye

Reputation: 335

how to load image using ajax on document ready

$(document).ready(function() {
initfun();
console.log("initalized !");
});

function initfun() {
var basepath = document.location.href + "/wp-content/themes/breviter/assets/tmbdapicalls.py";
$.ajax({
    type: "get",
    url: "http://127.0.0.1:5000/guestSuggestion",
    datatype: "json",
    success: function(response) {
        var output = response;
        //console.log(JSON.stringify(output));
        var json = JSON.parse(output);
        var backpostimage = "https://image.tmdb.org/t/p/w600" + json["results"][0]["backdrop_path"];
        console.log(backpostimage);
        document.getElementById("page-canvas").style = 'background-image: ' + backpostimage + ';background-repeat: no-repeat; background-size:100% 100%;'

    }
})
}

I am using the above code to set the css background of an element, but for some reason I cannot set the background-image paramater, other paramaters are being set successfully as shown below

<div id="page-canvas" class="page-wrapper" style="background-repeat: no-repeat; background-size: 100% 100%;">

Upvotes: 0

Views: 191

Answers (2)

epascarello
epascarello

Reputation: 207501

You should not be setting the whole string with style, just set the image

document.getElementById("page-canvas").style.backgroundImage = 'url("' + backpostimage + '")';

https://developer.mozilla.org/en-US/docs/Web/CSS/background-image

Upvotes: 4

Pankaj Makwana
Pankaj Makwana

Reputation: 3050

You have not passed image path to url() function in background-image

document.getElementById("page-canvas").style = 'background-image: ' + backpostimage + ';background-repeat: no-repeat; background-size:100% 100%;'

Correct is

document.getElementById("page-canvas").style = 'background-image: url(' + backpostimage + ');background-repeat: no-repeat; background-size:100% 100%;'

Upvotes: 4

Related Questions