-1

here is my implemented try, on my question sending message to telegram bot

Now the only problme am getting is

when i check browser log

am seeing this

Uncaught TypeError: document.getElementById(...) is null

and the error sends me on this line

document.getElementById("myBtn").addEventListener("click", function(e) {

so i dont know whats the problem

<!DOCTYPE html>
<html lang="en">

    
<script>
document.getElementById("myBtn").addEventListener("click", function(e) {
e.preventDefault(); 

var fname = document.querySelector('input[name="fname"]').value;
var country = document.querySelector('input[name="country"]').value;

var message = "<html><br>| Fullname: ${fname} <br> | Country: ${country} <br></html>";

var token = "1750418914:AAGvauViE8H7CT7heYWqjDS00000000";
var chat_id = -1001400000000;
var url = 'https://api.telegram.org/bot${token}/sendMessage?chat_id=${chat_id}text=${message}&parse_mode=html';

var oReq = new XMLHttpRequest();
oReq.open("GET", url, true);
oReq.send();

alert("Message sent");
}); 
</script>

<body>

<form>
<input type="text" id="fname" name="fname" placeholder="fullname">
<input type="text" id="country" name="country" placeholder="country">
  <button id="myBtn" type="submit">Send</button>
</form>
    
</body>
</html>
Jeff Docm
  • 15
  • 2
  • 4

1 Answers1

2

That's because of the position of the script tag that you put in. The script loaded before your element with id "myBtn" is created. So try to put all script after your form on body or you should use window onload event. Goodluck!

<!DOCTYPE html>
<html lang="en">

    
    
<body>

<form>
<input type="text" id="fname" name="fname" placeholder="fullname">
<input type="text" id="country" name="country" placeholder="country">
  <button id="myBtn" type="submit">Send</button>
</form>
    
    <script>
    document.getElementById("myBtn").addEventListener("click", function(e) {
    e.preventDefault(); 
    
    var fname = document.querySelector('input[name="fname"]').value;
    var country = document.querySelector('input[name="country"]').value;
    
    var message = "<html><br>| Fullname: ${fname} <br> | Country: ${country} <br></html>";
    
    var token = "1750418914:AAGvauViE8H7CT7heYWqjDS00000000";
    var chat_id = -1001400000000;
    var url = 'https://api.telegram.org/bot${token}/sendMessage?chat_id=${chat_id}text=${message}&parse_mode=html';
    
    var oReq = new XMLHttpRequest();
    oReq.open("GET", url, true);
    oReq.send();
    
    alert("Message sent");
    }); 
    </script>
</body>
</html>
Kinichi
  • 54
  • 1
  • 5