-1

The onchange function can run properly but I face some problem that the $.post function is not working

Here is html

<input type="checkbox" id="chk" value="3" onchange="checkradio(this.value)"/>

Here is javascript

var total=0;
function checkradio(serid) {
var num = 0;
$.post( "getserprice.php",{ serid: serid}, function( data ) {
          alert(data);
          num = data;
      })
 if (document.getElementById('chk').checked) {
        total = total + num;
    } else {
        total = total - num;
    }
}

Here is PHP

$price = 3;
echo $price;
user6652240
  • 19
  • 1
  • 7

2 Answers2

1

I'm not sure if this is the problem, but num won't be set to anything when it is used in the conditional below the success callback passed to $.post. You should change the function to this:

function checkradio(serid) {

    var num = 0;
    $.post( "getserprice.php",{ serid: serid}, function( data ) {
          alert(data);
          num = data;
          if (document.getElementById('chk').checked) {
              total = total + num;
          } else {
              total = total - num;
          }
      })

}
Josh Rumbut
  • 2,640
  • 2
  • 32
  • 43
0

$.post is an asynchronous function, i.e; when it makes a call it won't wait for the success event to occur and get data. Instead it will execute the next if conditional without even getting the data. So, we will get unexpected results.

var total=0;
function checkradio(serid) {
var num = 0;
$.post( "getserprice.php",{ serid: serid}, function( data ) {
          alert(data);
          num = data;
          if (document.getElementById('chk').checked) {
             total = total + num;
          } else {
             total = total - num;
          }
}
lucifer
  • 110
  • 8