I'm currently working on creating a button using JavaScript that, when clicked, will trigger an AJAX request to some PHP code.
Interestingly, I have already set up three buttons with the same functionality and they are all functioning perfectly.
What's puzzling is that if I call the method directly, it works just fine.
Here is the code for the button:
<button id="toggle-button">Toggle</button>
The JavaScript section:
var toggleButton = document.getElementById('toggle-button');
...
function init()
{
...
toggleButton.onClick = handleToggleClick;
...
}
function handleToggleClick(event)
{
alert("Sending Request");
var admin_url = "http://localhost/wp-admin/admin-ajax.php";
var data = {
action : 'toggle',
}
$.post(admin_url, data, function(resp) {
alert(resp);
});
}
In the Chrome Developer Tools Console, I tried the following:
handleToggleClick(null); // The request is sent
autoScheduleButton.onClick(); // The request is sent
autoScheduleButton.onClick; //It prints out the function
autoScheduleButton; //It displays the HTML of the button.
Despite having three other working buttons with similar functionalities, this specific one seems to be giving me trouble. It's quite puzzling because everything seems to be in order.
Hopefully, there's just something obvious that I missed here.
EDIT:
In my initial post, there was an error in the code due to anonymization. Now, the code shown above within the init method is correct.
Previously, the code looked like this: function init() { ... toggleButton.onClick() = handleToggleClick; ... }