infobitcoin
infobitcoin

Reputation: 59

jquery script runs only if page refresh

i have a button with the folowing code

<button type="button" class="btn btn-success btn-xs vote up" id="76" name="up"><span class="glyphicon glyphicon-thumbs-up"></span> Bueno</button>

the button does not work unless i reload the page, and i dont know why. any ideas? jquery code is at the beginning of the body

jquery

<script type="text/javascript">
$(function() {
$(".vote").click(function() 
{
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);
var _this = this;
if(name=='up')
{
$(this).fadeIn(600).html('<span class="glyphicon glyphicon-ok"></span>');
$.ajax({
   type: "POST",
   url: "up_vote.php",
   data: dataString,
   cache: false,

   success: function(html)
   {
    parent.html(html);
            $( _this ).remove();
            $( ".escondido" ).css( "display", "block" );
  }  });
return false;
    });
});
</script>

Upvotes: 0

Views: 89

Answers (3)

salasks
salasks

Reputation: 26

If the jQuery code is at the beginning of the code (before the HTML) as you state, the DOM would not have been created yet. Try moving the jQuery code to the bottom of the body (after the HTML).

Upvotes: 1

Brian Hoover
Brian Hoover

Reputation: 7991

In the jsFiddle I created, I'm seeing syntax errors - Original Code

If I change the code to Edited jsFiddle:

$(function () {
    $(".vote").click(function () {
        var id = $(this).attr("id");
        var name = $(this).attr("name");
        var dataString = 'id=' + id;
        var parent = $(this);
        var _this = this;
        if (name == 'up') {
            $(this).fadeIn(600).html('<span class="glyphicon glyphicon-ok"></span>');
            $.ajax({
                type: "POST",
                url: "up_vote.php",
                data: dataString,
                cache: false,

                success: function (html) {
                    parent.html(html);
                    $(_this).remove();
                    $(".escondido").css("display", "block");
                }
            });
            return false;
        }; // Removed ) from this line
    });
}); // Added this whole line

Upvotes: 0

EricBellDesigns
EricBellDesigns

Reputation: 965

I would assume you're getting an error in the button click event. Have you tried using the live('click') instead? Can you demonstrate the issue using JSFIDDLE?

Upvotes: 0

Related Questions