-1

the object calls this function, as usual. What happens? The function take this third parameter, which should change an attribute of the object, what not procced. Anybody could enlight?

  function insertbean(post_id, ip, imgcgn) {

     var request = new XMLHttpRequest();

  request.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
    document.getElementById("bn"+post_id).innerHTML = this.responseText;
    }
  };
  request.open("GET", "incrbean.php?postid="+post_id+"&ip="+ip, true);
  request.send();

      if(imgcgn){
              document.getElementById("lmp"+post_id).src = "SVG/lampsmall.svg";
              document.getElementById("lmp"+post_id).onclick = "insertbean("+post_id+", "+ip+", false)";
            
      }
      else {
              document.getElementById("lmp"+post_id).src = "SVG/lamponsmall.svg";
              document.getElementById("lmp"+post_id).onclick = "insertbean("+post_id+", "+ip+", true)";

    }
<button onclick="insertbean($post_id, $ip, true)">Clickme!</button>

Seemly everything is right, the files just exists in the folder and so on, that's why i'm so curious to know.

THanks.

  • First step would be to [avoid inline handlers](https://stackoverflow.com/a/59539045) like these, they have way too many problems to be worth using nowadays, such as a demented scope chain and quote escaping issues. Attach event listeners properly using Javascript with `addEventListener` instead. – CertainPerformance Dec 01 '20 at 01:16
  • Yes, the whole one is most complex. Tks – Ivan Zanoth Dec 01 '20 at 01:20
  • `Element.onevent` IDL properties do not accept strings, only the attribute does, but as has been said, that's bad anyway. You'll want to [bind](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind) the arguments to your function. – Kaiido Dec 01 '20 at 01:26

1 Answers1

0

I have no idea what you're attempting, but here's what is happening here:

On click, you are passing 1 parameter: true. You are not passing a second parameter, so it will always come through as undefined.

So in the function, you are passing true into post_id. undefined is falsey, so it will go to the else statement.

Then, "lmp" + post_id will give you what is very likely a nonsense string when adding a boolean to this string: "lmptrue". I think that will not match the id of anything on your page, so nothing will happen.

Dan Oswalt
  • 2,201
  • 2
  • 14
  • 24