JItendra
JItendra

Reputation: 75

setting asp image src property from javascript

I am trying to set asp image element src property from javascript but the url property is not being set.

function slideshow() {
  $.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    url: "/RollingScreen.aspx/GetNextImage",
    dataType: "json",
    data: "{}",
    success: function (data) {
      //this changes the image on the web page
      $('#imgSlideShow').attr("src","~/1.png");
      $("#txt1").val(data.d);
      //fires another sleep/image cycle
      setTimeout(slideshow,5000);
    },
    error: function (result) {
      alert(result.message);
    }
  });
}

$(document).ready(function () {
  //Kicks the slideshow
  slideshow();
});

My aspx image element is

<asp:Image ID="imgSlideShow" runat="server" Height="300px" Width="600px" ImageAlign="Middle" ImageUrl="~/1.png"/>....

Can anyone please help me...

Upvotes: 0

Views: 1943

Answers (1)

Viktor S.
Viktor S.

Reputation: 12815

Your mistake is that you are trying to use ID which you have set in asp.net. But runat="server" elements are rendered with different IDs. Something like Content1_Content2_imgSlideShow. You can get it using imgSlideShow.ClientID on server side and than $('#' + jsVariableWithClientID). But I prefer to use some unique class (no problem with passing client ID to JS):

<asp:Image ID="imgSlideShow" CssClass="imgSlideShow" runat="server" Height="300px" Width="600px" ImageAlign="Middle" ImageUrl="~/1.png"/>

And than in JS, using class selector:

$('.imgSlideShow').attr("src","/1.png");

Another problem is that JS does not know about ~ - that is asp.net feature only. And you should specify image url for src like this: "/1.png" (assuming it is located in root directory)

Upvotes: 2

Related Questions