0

What am I missing here? My jquery function isn't firing. Here's the HTML:

<div id="sum_income" class="col-sm-3" onload="sumIncome();">                     

</div>

and here's the jquery function:

function sumIncome() {

var cur_month = $('#month option:selected').attr("value");

$.ajax({
        type: "POST",
        url: 'inc/functions.php',
        data: {action: "get_sum_income", cur_month:cur_month},
        success: function(response){
            $('#sum_income').html(response);
            setTimeout(sumIncome, 5000);
                }
    })
};
hyphen
  • 957
  • 1
  • 11
  • 31

3 Answers3

3

change your jquery code.

 $(document).ready(function(){
            if($("#sum_income").length){
                var cur_month = $('#month option:selected').attr("value");

            $.ajax({
              type: "POST",
              url: 'inc/functions.php',
              data: {action: "get_sum_income", cur_month:cur_month},
              success: function(response){
              $('#sum_income').html(response);
                 setTimeout(sumIncome, 5000);
               }
            })
          }
        });

This will work definetly

Neeraj Kumar
  • 1,058
  • 1
  • 9
  • 22
2

Use $(window).onload(); instead of adding it to any HTML elements.

<script> 
  $(window).onload(function () {
    sumIncome();
  });
</script>
Andrew Surzhynskyi
  • 2,726
  • 1
  • 22
  • 32
1

html:

<body onload="sumIncome();">
</body>

js:

function sumIncome() {

    var m = $('#month option').val(); // assuming this is a selected tag

    var request = $.ajax({
        type: "POST",
        url: 'inc/functions.php',
        data: {action: "get_sum_income", cur_month:m},
        dataType: "html"
    });
    request.done(function( response ) {
        $('#sum_income').html(response);
    });
    request.fail(function( jqXHR, textStatus ) {
        alert( "Request failed: " + textStatus );
    });
    request.done(function() {
        setTimeout(sumIncome, 5000);
    })

}

PS: No onload method for divs.

0x_Anakin
  • 3,229
  • 5
  • 47
  • 86