0

I have a page with an image. I would like to first display a loading gif, and then change the image src using Ajax...

I found this. Here is my code :

                    @{
                    if (Model.HavePhoto)
                    {
                        <img id="userPhoto" src="~/Content/images/ajax-loader.gif" align="right" class="user-img" />
                        <script>
                            $.ajax({
                                url: '@Url.Action("GetPersonPhoto", "Home")',
                                data: { name: "personName" },
                                cache: false,
                                type: "POST",
                                dataType: "image/png",
                                success: function (data) {
                                    $('#userPhoto').attr('src', data);
                                },
                                error: function (xhr, status, error) {
                                    alert(xhr.status);
                                }
                            });
                        </script>
                    }

                    else
                    {
                        <img id="userPhoto" src="~/Content/images/header-default_user.png" align="right" class="user-img" />
                    }
                }

My GetPersonPhoto method directly return the image :

return File(photo, "image/png");

But my Ajax call doesn't works and I get an emtpy error message, and the status is "200"...

It is certainly a wrong way to do it or a problem eith the DataType... How can I do it ?

Community
  • 1
  • 1
Gab
  • 1,861
  • 5
  • 26
  • 39

1 Answers1

1

You can use onload event of Image.

Use

<img id="userPhoto" src="~/Content/images/ajax-loader.gif" align="right" class ="user-img" />
<script>
    var img = new Image();
    img.src = '@Url.Action("GetPersonPhoto", "Home" , new { "name" = "personName" })';
    img.onload = function () {
        $('#userPhoto').attr('src', this.src);
    }; 
</script>
Satpal
  • 132,252
  • 13
  • 159
  • 168