Event Listeners in AJAX
Adding Event Listener
Instead of executing JavaScript function on click event of the button. We can make it better by adding an Event Listener. First of all, I’ll update the button code by removing onclick event and adding an id with ajax-button.
Other Articles in Learn AJAX
- AJAX Basics
- Using Console Log in AJAX
- Passing Data with AJAX
- Event Listeners in AJAX
- AJAX Example
- AJAX Debugging
- Ajax Country State City Select Dropdown List
- Ajax Search Suggestions Dropdown
- AJAX CRUD application
Here is the button code.
1 |
<button id="ajax-button">Click Here</button> |
Then we should add Event Listener by just finding the button element with document.getElementById. Here is the code to add Event Listeners, It’s always good to use Event Listeners than the previous code.
1 2 3 4 5 |
<script type="text/javascript"> // Bind an Event to the Button var button = document.getElementById("ajax-button"); button.addEventListener("click", ajax); </script> |