I am relatively new to javascript and am confused by this error.
I have one function that is supposed to send data to a server via ajax call. This function takes the elements id and includes it in the message to server. In various other practice functions I was able to console.log() and alert() the id of the element after I clicked the relevant element, in this case an icon.
In the code below however(ajax server call), I am able to console.log() the correct id of the element, but this id does not get passed to the ajax call, and rather prints the data inside the "data" object as is, instead of substituting the relevant id. So what i get is "x:on" instead of "correct id:on".
Note: I am using jinja templating. So "device_name" is the identifier in a for loop. In my html the correct id appears as "ph_up_switch".
If anyone can also explain why this is happening that would be great as this is confusing to me. thank you
html
<i id = "{{ device_name }}_switch" onclick=hardware(id); class="fa fa-power-off" style="color: rgba(96,0,29,0.79);"></i>
JS
function hardware(id){
let x = id
console.log(x)
$.ajax({
type: "GET",
url : $SCRIPT_ROOT + '/hardware',
data: {x:'on'},
success: function(text){
alert('sent')
}
});
};
Side note— Ive read that the onclick=() handler is insecure for various reasons. If so, what are some more secure ways to call a function? I have the same function to be run on dozens of elements and am looking how I can do this a dynamic or "pythonic" way in javascript. Any help would be awesome
2
Answers
You can get that using the attribute.
Try this one
script
To have a click listener in js, you should call this script