Problem of changing image using Javascript

Asked

Viewed 111 times

0

The idea is to change image after update.

I have the following code:

<div id="context1" data-toggle="context" data-target="#context-menu1">
    <img id="SizeImage1" src="@Url.Action("StreamImage1", "Account", new { id = Model.Id })" style="cursor:pointer" />
</div>

Full script:

    <script>
        $(document).ready(function () {
            $("#submit_button").click(function () {
                //mostra loading gif
                $('#loading1').show();
                //desabilita o botão
                document.getElementById("submit_button").disabled = true;
                var formData = new FormData();

                debugger;
                var images = $("#Image1")[0].files;
                for (var i = 0; i < images.length; i++)
                {
                    if(i == 0)
                    {
                        formData.append("Image1", images[i]);
                    }
                    else if(i == 1)
                    {
                        formData.append("Image2", images[i]);
                    }
                    else if(i == 2)
                    {
                        formData.append("Image3",images[i]);
                    }
                    else if(i == 3)
                    {
                        formData.append("Image4",images[i]);
                    }

                }

                $.ajax({
                    cache: false,
                    type: "POST",
                    url: '/Account/Upload',
                    data: formData,
                    dataType: 'json',
                    contentType: false,
                    processData: false,
                    success: function (response) {
                        if (response.Success)
                        {

                            debugger;
                            //Oculta loading gif
                            $('#loading1').hide();

                            $("#SizeImage1").attr("src","@Url.Action("StreamImage1", "Account", new { id = Model.Id })");

                        }
                        if (response.ErrorImage)
                        {
                            alert("Erro de imagem");
                        }
                    },
                    error: function (request, status, error)
                    {
                        alert('A chamada para o servidor não está funcionando.')
                    }
                });
            });
        });

function ApagarImagem1(){   
    swal({
        title: "Are you sure?",
        text: "You will not be able to recover this imaginary file!",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "Yes, delete it!",
        closeOnConfirm: false
    },
    function(){

        $.ajax({
            url: '/Account/Apagar_Imagem1',
            type: 'POST',
            data: { imagem :"Imagem1" },
            success: function (response) {
                if (response.Success)
                {
                    $("#SizeImage1").removeAttr("src");
                    swal("Deleted!", "Your imaginary file has been deleted.", "success");

                }
                if(response.Error)
                {
                    swal("Cancelled", "Your imaginary file is safe :)", "error");
                }

            }
        });
    });

}

    </script>

Before updating a new image, it deletes an image from the database and then deletes src with JS code removeAttr:

function ApagarImagem1(){
    $.ajax({
        url: '/Account/Apagar_Imagem1',
        type: 'POST',
        data: { imagem :"Imagem1" },
        success: function (response) {
            if (response.Success)
            {
                $("#SizeImage1").removeAttr("src");
            }
        }
});
}

HTML result:

<img id="SizeImage1" style="cursor:pointer">

With AJAX’s "true" Return, I use JS to add the image.

$.ajax({
    type: "POST",
    url: '/Account/Upload',
    data: formData,
    dataType: 'json',
    cache: false,
    contentType: false,
    processData: false,                                
    success: function (response) {
        if (response.Success)
        {
            $("#SizeImage1").attr("src","@Url.Action("StreamImage1", "Account", new { id= Model.Id})");
        }
    }
    });

So far it works normal, when I do the third time to "change image", the image remains the same. Why aren’t you running "Controller" to get the image from the database.

Code in the Controller:

public ActionResult StreamImage1(int id) // Na terceira vez não entra aqui
        {
           //... Aqui onde pega a imagem no banco de dados
        }

The problem is this code below:

$("#SizeImage1").attr("src","@Url.Action("StreamImage1", "Account", new { id = Model.Id})");

This code above is not making it pass the "Streamimage1" action on the third time.

Why does the third time not work ? Some solution ?

2 answers

1

I solved problem by disabling cache through Controller:

Code:

[OutputCache(NoStore = true, Location = OutputCacheLocation.None, VaryByParam = "*")]

Example:

[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult StreamImage1(int id) // Sempre entra aqui
        {
           //... Aqui onde pega a imagem no banco de dados
        }

0

 cache: false 

Set this in your AJAX that eliminate the possibility of caching and will always do the search in Controller Action.

  • Hi @Edvaldo Farias, I edited my post, and I put "cache: false" in AJAX, it didn’t work.

  • Could you send me the entire Ajax script?

  • yes I will edit my post

  • Hi @Edvaldo Farias, it is possible to refresh the <img id="Sizeimage1" src="@Url.Action("Streamimage1", "Account", new { id = Model.Id })" style="cursor:Pointer" /> without updating page ?

  • at some point he enters this '/Account/Upload' ?

  • Yes, to upload image

  • this @Url.Action("Streamimage1", "Account", new { id = Model.Id })" is returning an action? it should return the image path in string

  • What a miracle!!! I managed to solve my problem, I will post answer here.

  • 1

    thanks for the help :)

  • 1

    So it really was the cache, but in Controller.

Show 5 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.