Js EventListener submit not working
-
Hi I am a developer and I am new to wordpress. I have a problem with some text fields.
I recently entered a project and I’ve got to fix some code that was developped by a previous developer.
In the project some text fields can be used to inject js code. To fix it I firstly wanted to change the values of these fields by using the html_entity_decode php function. It turned out to be complicated because there is no MVC structures in plugins, so I can’t change the values before they are sent to post.So I decided to add some js to handle the decoding manually. To do so I added an eventListener ‘submit’ to my form but it turns out that it is never triggered. I don’t understand why.
Here is the code (minized for the example) :
<form method="post" id="form1"> <label>Name</label><input type="text" id="name" name="name" value="<?= (isset($_POST['name']) && $_POST['name'] != '') ? $_POST['nom'] : '' ?>" /> <input type="submit" id="search1"> </form> <script> window.onload = () => { document.getElementById('form1').addEventListener('submit', function(e) { e.preventDefault(); name = document.getElementById('name').value; document.getElementById('name').value = escapeHtml(name); document.getElementById('form1').submit(); }); } </script>The expected behavior is that the values would get formatted by the ‘escapeHtml’ fonction (not showed here but working very well as I tested it externally).
But the actual behavior is the direct submission of the form. The code in the listener is not executed.If you know if this is about wordpress or about my code let me know please.
Maybe there is another way to avoid getting js injections in the text fields. In this case all I know if that it has to be processed before it is sent to $_POST for security.
Thank you in advance for your help.
-
You might try listening for the click event on the submit button. While sanitizing form data before sending to the server is nice, server side we still cannot trust user data no matter what efforts you take client side. An attacker could always disable JS or send form data through other means. We must always validate and sanitize data server side.
The topic ‘Js EventListener submit not working’ is closed to new replies.