Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: invalid variable initialization

I have to call a function only if ajax call success.

Code:

<script>
    function removeFromCart(id) {
        var value = "";
        for(var i=0; i<id.length; i++)
            if(!isNaN(id[i]))
                value += id[i];
        $.ajax({
            type: "POST",
            url: "http://url.com/removefromcart.php",
            data: "id="+value,
            success: function(response){
                afterRemove(response);
            }
        });
    }

    function afterRemove(response) {
        if(response[0] == "r") {
            var prezzo = "";
            for(var i = 1; i<respose.length; i++)
                var prezzo += response[i];
            document.getElementByid("prezzo").innerHTML = prezzo+".00 &euro;";
            $("#segnale"+value).fadeOut();
        }
    }
</script>

The problem is that Firebug gives me this error on page load:

invalid variable initialization: var prezzo += response[i];

This because the afterRemove function is called on page load and not only if ajax success. How can fix this?

like image 438
pindol Avatar asked Jun 22 '26 10:06

pindol


2 Answers

you define/var the variable prezzo twice

var prezzo = ""; // <-- here
for(var i = 1; i<respose.length; i++)
    var prezzo += response[i]; // <-- and here
like image 94
Manuel van Rijn Avatar answered Jun 25 '26 01:06

Manuel van Rijn


var prezzo += response[i]

This is invalid because var prezzo means you are creating a new variable named prezzo. You are then trying to add to that variable. You can't add to a variable that is brand new because it doesn't have a value yet. Just drop the var.

like image 28
James Montagne Avatar answered Jun 24 '26 23:06

James Montagne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!