I have created a small custom plugin which is just an HTML form. The HTML form is echo'd out using PHP and it includes a small JavaScript function that I want to run on submission. I cannot get it to work, however, and I am not sure what I am doing wrong. Is it not allowed to use JavaScript in this way? If not, what is the proper way to do it?
Running the below snippet does nothing when hitting the submit button.
echo "
<script type=\"text/javascript\">
function validateForm()
{
alert(\"FOOO\");
return false;
}
</script>
<h1>Header</h1><br>
<form method=\"post\" onsubmit=\"validateForm()\">
<input type=\"submit\" value=\"Submit me\" /><br>
</form>
";
Update:
Here is the entire plugin, stripped down to just a small test. The JavaScript console shows nothing except a jQuery warning: JQMIGRATE: jQuery.fn.live() is deprecated. I am not sure where this originates from, but I do not use jQuery directly.
When I activate the plugin and click the button, the page is reloaded with the button and all, but the message Yes, it was posted! is not displayed. Thus it seems that no POST request is made. Removing the script and the onsubmit from the PHP echo produces the same behavior.
<?php
/*
Plugin Name: Test Plugin
*/
// Create plugin menu.
add_action('admin_menu', 'create_test_plugin_menu');
function create_test_plugin_menu()
{
add_menu_page('The Test Plugin', 'Test Plugin', 'administrator', __FILE__, 'setup_test_plugin');
}
function setup_test_plugin()
{
$submit_name = 'test_button';
if ( $_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST[$submit_name]) )
{
echo "Yes, it was posted!";
}
else
{
echo "
<script type=\"text/javascript\">
function validateForm()
{
alert(\"FOOO\");
return false;
}
</script>
<h1>Header</h1><br>
<form method=\"post\" onsubmit=\"validateForm()\">
<input type=\"submit\" name=\"{$submit_name}\" value=\"Submit me\" /><br>
</form>
";
}
}
?>
Here is what is printed to the HTML source, copied from the JavaScript console.
<script type="text/javascript">
function validateForm()
{
alert("FOOO");
return false;
}
</script>
<h1>Header</h1><br>
<form method="post" onsubmit="validateForm()">
<input type="submit" name="test_button" value="Submit me" /><br>
</form>
test_button?alertis still not shown.